esp32-snippets icon indicating copy to clipboard operation
esp32-snippets copied to clipboard

Question: How to tear down BLE Client connection correctly?

Open Tuet opened this issue 6 years ago • 11 comments

Hi, within an own class for a BLE device I connect to the device and in the end I build up the following hierarchy: BLEClient* pBLEClient = BLEDevice::createClient() BLEREmoteServer* pBLEService = pBLEClient->getService("...") BLERemoteCharacteristic* pBLECharaA = pBLEService->getCharacteristic("...") pBLECharaA->registerForNotify(pCallbackA)

Then, I receive a onDisconnect event via my class that is public of BLEClientCallbacks. The question is now how to handle this and which and how should I destroy/delete the objects that I can reconnect later? I tried using delete pBLECharaA, then delete pBLEService. Do I have to delete all characteristic pointers myself? Do I have to unregister the notifications first? Or is there some kind of auto-delete that I just have to delete pBLEClient? Currently, it either crashes the CPU with some sort of heap-Errors or I am not able to connect again if I just don't delete anything. Please give me an advise how to do it correctly. Thank you very much for the very great BLE library so far!

Tuet avatar Apr 24 '18 11:04 Tuet

Im not good at C++ and garbage collecting, but i think you can setup BLERemoteServis* and BLERemoteCharacteristic* as global variables and reuse on every connection, unless you want to have multiple connections at the same time.

chegewara avatar Apr 26 '18 06:04 chegewara

Hi, of course I can reuse the pointers to class instances, but the problem is that the getService and getCharacteristic functions seems to allocate some resources on the heap as well as in the lower BLE stack areas. When I just try to reconnect to the same device then I get messages like "BT: application already registered.". So what I am looking for is a function that de-register the stuff I have got via getService and getCharacteristics to release the resources properly, so that I can re-register them later correctly. I tried to do so by invoking a delete on the pointers I have got in the hope that the destructor is called and does the clean up. Unfortunately I am not a C++ expert and maybe I am just doing something simple quite wrong...

Tuet avatar Apr 26 '18 10:04 Tuet

This may be another bad idea, but you can try to create task. In this task create BLEClient, service, characteristics etc, all you need during connectection. Then on disconnect you can try to vTaskDestroy() that task. I have no idea how this will affect heap and stack, but worth to try.

chegewara avatar Apr 26 '18 10:04 chegewara

I solved it for me! Short answer first:

  1. When a onDisconnect() callback comes in, you have to manually invoke the disconnect() function of BLEClient.
  2. After that, the instance of the BLEClient can be deleted. The destructor within this function seems to clean up all the hierarchy of many BLERemoteService and BLERemoteCharacteristics by itself. Don't try to delete these instances manually, otherwise a heap corruption will appear. It seems that most of the resources get released this way.
  3. You can now connect and recreate the hierarchy again - without issues like "..already registered".

Long answer: I am doing all this with Arduino, out of an Arduino library I am writing. I don't know much about creating tasks and due to the nature of the BLE implementation I try to call all BLE functions out of the main loop. As soon as I call any BLE function from within a BLE callback, everything crashes or does not work.

However, it seems I understood the nkolban BLE stack a little bit more: When I tried to delete any BLERemoteService manually the system crashed with heap corruption. In the exception decoder I realized that the destructor of BLEREmoteService still tried to destruct the BLERemoteCharacteristics, that I already deleted myself. It seems that there is already a mechanism in nkolban's stack that tears down all the BLERemoteService and BLERemoteCharacteristics instances. That should be triggered on BLEClient-Level, but a call to disconnect() seems to be usefull as well.

Tuet avatar Apr 26 '18 11:04 Tuet

You just saved me a lot of time and tests.

chegewara avatar Apr 26 '18 13:04 chegewara

Hi,

i'm running a BLE client on a ESP32-PICO-D4 (revision 1) with these settings:

image

The snippet code i'm testing is the following and the purpose is to:

  1. init ble device2
  2. scan for a specific ble advertising name
  3. connect to the service
  4. read the answer of a specific characteristic
  5. de-init ble device.
  6. restart to 1.
#include "Arduino.h"
#include "BLEDevice.h"


#define CONNECT_TIMEOUT_MS 5000
#define DISCONNECT_TIMEOUT_MS 5000


static BLEUUID 	  				serviceUUID	  ("49535343-fe7d-4ae5-8fa9-9fafd205e455");
static BLEUUID    				charUUID_read ("49535343-1e4d-4bd9-ba61-23c647249616");
static BLEUUID    				charUUID_write("49535343-8841-43f4-a8d4-ecbe34729bb3");
static const char 				UUID_NAME[] = "XXXXXXXXXXXXXXXXXXXXXX";
static boolean 					connected = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLERemoteService* 		pRemoteService;
static BLEAdvertisedDevice* 	myDevice;
static boolean doConnect = false;
static boolean fScanInProgress = false;


bool ble_initialized = false;
volatile bool commandSequenceComplete = false;
volatile bool messageReceived = false;
volatile bool fScanFinished = false;
volatile uint8_t foundBLEDevices = 0;


char TX_BUFFER[50];
char RX_BUFFER[256];
uint8_t RX_INDEX = 0;
uint8_t TEMP_INDEX = 0;
uint8_t RX_LENGTH = 0;



static BLEScan*    pBLEScan;
static BLEClient*  pClient;


void printHeapStatus()
{
	Serial.print("HEAP: "); Serial.print( ESP.getFreeHeap() ); Serial.println();
}




class MyClientCallback : public BLEClientCallbacks
{

  void onConnect(BLEClient* pclient)
  {
	  Serial.println("onConnect: OK");
	  connected = true;
  }

  void onDisconnect(BLEClient* pclient)
  {

	  if (fScanInProgress) BLEDevice::getScan()->erase(pclient->getPeerAddress());

	    printHeapStatus();
	    Serial.println("onDisconnect: OK");
	    Serial.println("pClient->disconnect();");

	  	pClient->disconnect();

	    printHeapStatus();

	  	connected = false;

  }
};


class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
 /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice)
  {

	  if (strcmp(advertisedDevice.getName().c_str(), UUID_NAME) == 0)
	  {

		    Serial.print(F("FOUND -->  "));
		  	Serial.print(advertisedDevice.getName().c_str());
		  	Serial.println();

		  	myDevice = new BLEAdvertisedDevice(advertisedDevice);
		  	doConnect = true;
	  }
	  Serial.print(F("*** Added device: "));
	  Serial.print(advertisedDevice.getName().c_str());
	  Serial.println();

	  foundBLEDevices+=1;

  } // onResult
}; // MyAdvertisedDeviceCallbacks

MyClientCallback* my_callback = new MyClientCallback();
MyAdvertisedDeviceCallbacks* my_advertisedcallback = new MyAdvertisedDeviceCallbacks();


static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify)
{
	Serial.print(F("INCOMING: "));

	for ( TEMP_INDEX = 0	;	TEMP_INDEX < length	;	TEMP_INDEX++ , RX_INDEX++	)
	{
		RX_BUFFER[RX_INDEX] = (char)pData[TEMP_INDEX];

		Serial.print((char)pData[TEMP_INDEX]);

	}

	Serial.print(F("     length:"));
	Serial.println(length);

	if (RX_INDEX == RX_LENGTH)
	{
			RX_INDEX = 0;
			RX_BUFFER[RX_LENGTH+1] = '\0';

			if (RX_BUFFER[3] == '1') //command type #1
			{
						// decode(1,RX_BUFFER);
						Serial.println(F("PACKETS DECODED"));
						Serial.println(F("Write command :01403A"));

						strcpy(TX_BUFFER,":01403A");
						RX_LENGTH = 39;
						messageReceived = true;
			}
			else if (RX_BUFFER[3] == '4') //command type #2
			{
						// decode(4,RX_BUFFER);
						Serial.println(F("PACKETS DECODED"));
						Serial.println(F("Write command :01D0101540001539"));
						strcpy(TX_BUFFER,":01D0101540001539");
						RX_LENGTH = 97;
						messageReceived = true;
			}
			else if (RX_BUFFER[3] == 'D')   //command type #3
			{
				// decoce(13,RX_BUFFER);
				Serial.println(F("PACKETS DECODED"));
				Serial.println(F("Write command type #1"));
				strcpy(TX_BUFFER,":0116D");
				RX_LENGTH = 101;
				commandSequenceComplete = true;
				messageReceived = true;
			}
	}//if (RX_INDEX == _RXLENGTH)
}//static void notifyCallback


static void scanCompleteCB(BLEScanResults scanResults)
{
	fScanFinished=true;
}

void closeConnections()
{


		Serial.println("closeConnections();");
		printHeapStatus();
		pBLEScan->clearResults();
		printHeapStatus();
		Serial.println(F("delete myDevice;"));

		delete myDevice;

		printHeapStatus();
		Serial.println(F("BLEDevice::deinit(false);"));


		BLEDevice::deinit(false);
		ble_initialized = false;
		printHeapStatus();

		//Serial.println(F("pClient->~BLEClient();"));
		//pClient->~BLEClient();	//CRASH
		//printHeapStatus();


		Serial.println(F("pRemoteCharacteristic->~BLERemoteCharacteristic();"));
		pRemoteCharacteristic->~BLERemoteCharacteristic();
		printHeapStatus();

		/*
		Serial.println(F("pRemoteService->~BLERemoteService();"));
		pRemoteService->~BLERemoteService();	//CRASH
		printHeapStatus();
		*/

		Serial.println(F("free(pRemoteCharacteristic);"));
		free(pRemoteCharacteristic);
		printHeapStatus();
		Serial.println(F("free(pRemoteService);"));
		free(pRemoteService);
		printHeapStatus();
}





int scan_BLE()
{

	doConnect = false;
	foundBLEDevices = 0;

	Serial.println("--------------------------------------");

	if (!ble_initialized)
	{



		printHeapStatus();
		Serial.println("BLEDevice::init()");


		BLEDevice::init("test");
		ble_initialized = true;


		printHeapStatus();

	 }

	Serial.print("BLEScan: ");

	pBLEScan = BLEDevice::getScan();
	pBLEScan->setAdvertisedDeviceCallbacks(my_advertisedcallback);
	pBLEScan->setInterval(1349);
	pBLEScan->setWindow(449);
	pBLEScan->setActiveScan(true);
	pBLEScan->start(3,scanCompleteCB,false);  // not blocking methods, jump to callback when scan finished


	Serial.print("ok");
	Serial.println();
	printHeapStatus();



	fScanFinished = false;
	fScanInProgress = false;


	Serial.println("Scan in progress...");


	while (!fScanFinished)
	{
		fScanInProgress = true;
	}

	fScanInProgress = false;


	Serial.println(F("scan complete!"));


	BLEDevice::getScan()->stop();


	Serial.print(F("Device(s) found: "));
	Serial.println(foundBLEDevices);


	if (doConnect)
	{

		Serial.println(F("Create client..."));

		pClient  = BLEDevice::createClient();

		printHeapStatus();
		Serial.println(F("Set callback..."));

		pClient->setClientCallbacks(my_callback);

		printHeapStatus();
		Serial.println(F("Connecting..."));

		pClient->connect(myDevice);

		printHeapStatus();

		unsigned long _elapsedTimeout = millis();
		bool timeoutElapsed = false;
		do
		{
			if (millis() - _elapsedTimeout > CONNECT_TIMEOUT_MS) timeoutElapsed = true;

			Serial.println(F("Waiting connection..."));
			delay(1000);

		}while(!connected && !timeoutElapsed);

		if (timeoutElapsed && !connected)
		{
			Serial.println(F("Unable to connect to device"));
			closeConnections();
			delay(3000);
		}

		pRemoteService = pClient->getService(serviceUUID);
		if (pRemoteService == nullptr)
		{

			Serial.println(F("Unable to connect to service"));
			delay(3000);

			closeConnections();
			return -1;
		}


		pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID_read);
		if (pRemoteCharacteristic == nullptr)
		{

			Serial.println(F("Unable to connect to characteristic"));
			delay(3000);

			closeConnections();
			return -1;
		}


		if(pRemoteCharacteristic->canNotify()) 	pRemoteCharacteristic->registerForNotify(notifyCallback);
		else
		{

			Serial.println(F("Unable to connect to characteristic"));
			delay(3000);
			closeConnections();
			return -1;
		}

		pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID_write);
		messageReceived = true;
		commandSequenceComplete = false;

		Serial.println(F("Write command type #1"));


		strcpy(TX_BUFFER,":0116D");
		RX_LENGTH = 101;


		while (1)
		{
			if (!connected)	//onDisconnected event
			{
				closeConnections();
				return 1;
			}

			if (commandSequenceComplete)
			{
				Serial.println(F("commandSequenceComplete"));
				commandSequenceComplete = false;
				messageReceived = false;

				printHeapStatus();
				Serial.println(F("pClient->disconnect();"));
				pClient->disconnect();
				printHeapStatus();

				unsigned long _elapsedTimeout = millis();
				bool timeoutElapsed = false;
				do
				{
					if (millis() - _elapsedTimeout > DISCONNECT_TIMEOUT_MS) timeoutElapsed = true;

					Serial.println(F("Waiting connection..."));
					delay(1000);

				}while(connected && !timeoutElapsed);


				closeConnections();
				return 1;

			}//if (commandSequenceComplete)
			else //if (!commandSequenceComplete)
			{
				if (messageReceived)
				{
					messageReceived = false;
					pRemoteCharacteristic->writeValue(TX_BUFFER, false);
				}
				else
				{
					//waiting...
				}
			}//if (commandSequenceComplete)
		}//while (1)

	}//	if (doConnect)
	else	//if (!doConnect)
	{
		Serial.println("Unable to connect");
		closeConnections();
		delay(3000);
		return -1;
	}

	closeConnections();
	return -1;

}






void setup()
{
	Serial.begin(115200);
}


void loop()
{
	if (scan_BLE()<0)
	{
			//error
			Serial.println("return -1");
	}
	else if (scan_BLE()>0)
	{
			//complete
			Serial.println("return 1");
	}
}

From the serial i get something similar:


HEAP: 275104 BLEDevice::init() HEAP: 184788 BLEScan: ok HEAP: 184668 Scan in progress... FOUND --> XXXXXXXXXX *** Added device: XXXXXXXXXX *** Added device: *** Added device: *** Added device: *** Added device: scan complete! Device(s) found: 5 Create client... HEAP: 182052 Set callback... HEAP: 182052 Connecting... onConnect: OK HEAP: 177972 Waiting connection... Write command :0116D INCOMING: :0110020000000000000 length:20 INCOMING: 00000000000000000000 length:20 INCOMING: 00000060021000000003 length:20 INCOMING: 10001000000000004001 length:20 INCOMING: 06518183012550020005 length:20 INCOMING: 9 length:1 PACKETS DECODED Write command :01403A INCOMING: :0140000000002600000 length:20 INCOMING: 0000720201218111216 length:19 PACKETS DECODED Write command :01D0101540001539 INCOMING: :01D0101540001500015 length:20 INCOMING: 00007020200001100037 length:20 INCOMING: 00011000150000702020 length:20 INCOMING: 00011000370001365535 length:20 INCOMING: 6553500005eeeeeBB length:17 CALIB PACKETS DECODED Write command :0116D commandSequenceComplete HEAP: 175004 pClient->disconnect(); HEAP: 176956 Waiting connection... HEAP: 177668 onDisconnect: OK pClient->disconnect(); HEAP: 177628 closeConnections(); HEAP: 178916 HEAP: 180560 delete myDevice; HEAP: 180772 BLEDevice::deinit(false); HEAP: 266728 pRemoteCharacteristic->~BLERemoteCharacteristic(); HEAP: 267012 free(pRemoteCharacteristic); HEAP: 267304 free(pRemoteService); HEAP: 271976 return 1

HEAP: 271976 BLEDevice::init() HEAP: 181680 BLEScan: ok HEAP: 181560 Scan in progress... *** Added device: FOUND --> XXXXXXXXXX *** Added device: XXXXXXXXXX *** Added device: *** Added device: *** Added device: scan complete! Device(s) found: 5 Create client... HEAP: 178936 Set callback... HEAP: 178936 Connecting... onConnect: OK HEAP: 174864 Waiting connection... Write command :0116D INCOMING: :0110020000000000000 length:20 INCOMING: 00000000000000000000 length:20 INCOMING: 00000060021000000003 length:20 INCOMING: 10001000000000004001 length:20 INCOMING: 06518183012550020005 length:20 INCOMING: 9 length:1 PACKETS DECODED Write command :01403A INCOMING: :0140000000002600000 length:20 INCOMING: 0000720201218111216 length:19 PACKETS DECODED Write command :01D0101540001539 INCOMING: :01D0101540001500015 length:20 INCOMING: 00007020200001100037 length:20 INCOMING: 00011000150000702020 length:20 INCOMING: 00011000370001365535 length:20 INCOMING: 6553500005eeeeeBB length:17 PACKETS DECODED Write command :0116D commandSequenceComplete HEAP: 171888 pClient->disconnect(); HEAP: 173568 Waiting connection... HEAP: 174528 onDisconnect: OK pClient->disconnect(); HEAP: 174424 closeConnections(); HEAP: 175784 HEAP: 177444 delete myDevice; HEAP: 177648 BLEDevice::deinit(false); HEAP: 263584 pRemoteCharacteristic->~BLERemoteCharacteristic(); HEAP: 263864 free(pRemoteCharacteristic); HEAP: 264156 free(pRemoteService); HEAP: 268828

HEAP: 268828 BLEDevice::init() HEAP: 178524 BLEScan: ok HEAP: 178404 Scan in progress... FOUND --> XXXXXXXXXX *** Added device: XXXXXXXXXX *** Added device: *** Added device: *** Added device: *** Added device: scan complete! Device(s) found: 5 Create client... HEAP: 175780 Set callback... HEAP: 175780 Connecting... onConnect: OK HEAP: 171716 Waiting connection... Write command :0116D INCOMING: :0110020000000000000 length:20 INCOMING: 00000000000000000000 length:20 INCOMING: 00000060021000000003 length:20 INCOMING: 20001000000000004001 length:20 INCOMING: 06518183012550020005 length:20 INCOMING: 8 length:1 PACKETS DECODED Write command :01403A INCOMING: :0140000000002600000 length:20 INCOMING: 0000720201218111216 length:19 PACKETS DECODED Write command :01D0101540001539 INCOMING: :01D0101540001500015 length:20 INCOMING: 00007020200001100037 length:20 INCOMING: 00011000150000702020 length:20 INCOMING: 00011000370001365535 length:20 INCOMING: 6553500005eeeeeBB length:17 PACKETS DECODED Write command :0116D commandSequenceComplete HEAP: 168728 pClient->disconnect(); HEAP: 170420 Waiting connection... HEAP: 171380 onDisconnect: OK pClient->disconnect(); HEAP: 171340 closeConnections(); HEAP: 172628 HEAP: 174284 delete myDevice; HEAP: 174496 BLEDevice::deinit(false); HEAP: 260440 pRemoteCharacteristic->~BLERemoteCharacteristic(); HEAP: 260720 free(pRemoteCharacteristic); HEAP: 261012 free(pRemoteService); HEAP: 265684 return 1

HEAP: 265684 BLEDevice::init() HEAP: 175404 BLEScan: ok HEAP: 175284 Scan in progress... *** Added device: FOUND --> XXXXXXXXXX *** Added device: XXXXXXXXXX *** Added device: *** Added device: *** Added device: scan complete! Device(s) found: 5 Create client... HEAP: 172664 Set callback... HEAP: 172664 Connecting... onConnect: OK

it seems that I have a loss of heap of approximately 3k between every de-init and re-init I think the problem is that I don't call the destructors of the following objects

pClient->~BLEClient(); //CRASH pRemoteService->~BLERemoteService(); //CRASH

but if I do I get a crash where am i going wrong?

Thanks

biccius avatar Jan 17 '21 21:01 biccius

myDevice = new BLEAdvertisedDevice(advertisedDevice); MyClientCallback* my_callback = new MyClientCallback(); MyAdvertisedDeviceCallbacks* my_advertisedcallback = new MyAdvertisedDeviceCallbacks();

For sure you are having memory leak here. I did not read full code, but i am guessing you never delete any of these.

chegewara avatar Jan 17 '21 22:01 chegewara

Hi chegewara,

wow, thank you for your super fast answer!

myDevice is already deleted in the function closeConnections();

added my_advertisedcallback->~BLEAdvertisedDeviceCallbacks(); and my_callback->~BLEClientCallbacks(); inside closeConection that is executed in the deinit phase but i'm still having heap leakage

**rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 188777542, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:1216 ho 0 tail 12 room 4 load:0x40078000,len:9720 ho 0 tail 12 room 4 load:0x40080400,len:6352 entry 0x400806b8

HEAP: 220292 BLEDevice::init() HEAP: 129776 pBLEScan: ok HEAP: 129356 Scan in progress... FOUND --> XXXXXXXXXX *** Added device: XXXXXXXXXX *** Added device: *** Added device: *** Added device: *** Added device: *** Added device: scan complete! Device(s) found: 6 Create client... HEAP: 126556 Set callback... HEAP: 126556 Connecting... onConnect: OK HEAP: 122480 Waiting connection... Write command :0116D INCOMING: :0110020000000000000 length:20 INCOMING: 00000000000000000000 length:20 INCOMING: 00000060021000000002 length:20 INCOMING: 30001000000000004001 length:20 INCOMING: 06518183012550000005 length:20 INCOMING: A length:1 PACKETS DECODED Write command :01403A INCOMING: :0140000000002600000 length:20 INCOMING: 0000720201218111216 length:19 PACKETS DECODED Write command :01D0101540001539 INCOMING: :01D0101540001500015 length:20 INCOMING: 00007020200001100037 length:20 INCOMING: 00011000150000702020 length:20 INCOMING: 00011000370001365535 length:20 INCOMING: 6553500005eeeeeBB length:17 PACKETS DECODED Write command :0116D HEAP: 118868 pClient->disconnect(); HEAP: 119460 wait... HEAP: 122160 onDisconnect: OK pClient->disconnect(); HEAP: 122116 closeConnections(); HEAP: 123404 pBLEScan->clearResults(); HEAP: 125312 delete myDevice; HEAP: 125520 BLEDevice::deinit(false); HEAP: 211468 pRemoteCharacteristic->~BLERemoteCharacteristic(); HEAP: 211748 free(pRemoteCharacteristic); HEAP: 216528 free(pRemoteService); HEAP: 216708 my_callback->~BLEClientCallbacks(); HEAP: 216708 my_advertisedcallback->~BLEAdvertisedDeviceCallbacks(); HEAP: 216708 UNIT_TEST: BLE scan terminated

HEAP: 216708 BLEDevice::init() HEAP: 126424 pBLEScan: ok HEAP: 126180 Scan in progress... *** Added device: *** Added device: *** Added device: FOUND --> XXXXXXXXXX *** Added device: XXXXXXXXXX *** Added device: *** Added device: scan complete! Device(s) found: 6 Create client... HEAP: 123436 Set callback... HEAP: 123436 Connecting... onConnect: OK HEAP: 119360 Waiting connection... Write command :0116D INCOMING: :0110020000000000000 length:20 INCOMING: 00000000000000000000 length:20 INCOMING: 00000060021000000002 length:20 INCOMING: 30001000000000004001 length:20 INCOMING: 06518183012550000005 length:20 INCOMING: A length:1 STATUS PACKETS DECODED Write command :01403A INCOMING: :0140000000002600000 length:20 INCOMING: 0000720201218111216 length:19 CTP PACKETS DECODED Write command :01D0101540001539 INCOMING: :01D0101540001500015 length:20 INCOMING: 00007020200001100037 length:20 INCOMING: 00011000150000702020 length:20 INCOMING: 00011000370001365535 length:20 INCOMING: 6553500005eeeeeBB length:17 CALIB PACKETS DECODED Write command :0116D HEAP: 115740 pClient->disconnect(); HEAP: 116468 wait... HEAP: 118972 onDisconnect: OK pClient->disconnect(); HEAP: 118928 closeConnections(); HEAP: 120284 pBLEScan->clearResults(); HEAP: 122192 delete myDevice; HEAP: 122400 BLEDevice::deinit(false); HEAP: 208332 pRemoteCharacteristic->~BLERemoteCharacteristic(); HEAP: 208616 free(pRemoteCharacteristic); HEAP: 208908 free(pRemoteService); HEAP: 213576 my_callback->~BLEClientCallbacks(); HEAP: 213576 my_advertisedcallback->~BLEAdvertisedDeviceCallbacks(); HEAP: 213576

HEAP: 213576 BLEDevice::init() HEAP: 123288 pBLEScan: ok HEAP: 123044 Scan in progress...

biccius avatar Jan 17 '21 22:01 biccius

Scan object is a single instance, so you dont have to delete it. Scanned devices you can clear anytime you want. pClient should be deleted by library, but you can try to delete it (most likely it will crash app). My suggestion is to create variable/object for any callback you are passing. That way you dont have to worry about memory leak from that, because you will have only one instance which you can pass instead of creating new Callback().

chegewara avatar Jan 17 '21 22:01 chegewara

The only instances i cannot delete are pRemoteService and pClient I call 'delete pRemoteService' and 'delete pClient' but what i have is an error like this:

delete(pRemoteService);
assertion "head != NULL" failed: file "/home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/heap/multi_heap_poisoning.c", line 214, function: multi_heap_free

Backtrace: 0x4009456c:0x3ffcf020 0x4009479d:0x3ffcf040 0x4010e0db:0x3ffcf060 0x400941e1:0x3ffcf090 0x40085c72:0x3ffcf0b0 0x40087731:0x3ffcf0d0 0x4000bec7:0x3ffcf0f0 0x40090b9f:0x3ffcf110 0x400ddb5b:0x3ffcf130 0x400db857:0x3ffcf150 0x400dbf47:0x3ffcf170 0x400dc322:0x3ffcf190 0x400dc341:0x3ffcf1b0 0x400d1bf1:0x3ffcf1d0 0x400d235c:0x3ffcf1f0 0x400d3bb2:0x3ffcf230 0x400d3bcd:0x3ffcf250 0x400d3ec1:0x3ffcf270 0x400e0ecd:0x3ffcf2c0 0x40090c81:0x3ffcf2e0

Rebooting...
ets Jun  8 2016 00:22:57

This step of destroying used instances is done after OnDisconnect has been executed. I'm not really familiar with C++ but I'd say that 'delete' call the destructor and free lists of elements previously allocated What's wrong with that?

biccius avatar Jan 20 '21 22:01 biccius

pClient is deleted by library after disconnection, dont remember about remote services, probably too.

chegewara avatar Jan 25 '21 02:01 chegewara