Skip to content

Commit 3dbf481

Browse files
committed
fix(ble): Fix deinit function
1 parent 4852eb9 commit 3dbf481

File tree

1 file changed

+41
-6
lines changed

1 file changed

+41
-6
lines changed

libraries/BLE/src/BLEDevice.cpp

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -867,13 +867,47 @@ void BLEDevice::removePeerDevice(uint16_t conn_id, bool _client) {
867867

868868
/**
869869
* @brief de-Initialize the %BLE environment.
870-
* @param release_memory release the internal BT stack memory
870+
* @param release_memory release the internal BT stack memory (prevents reinitialization)
871871
*/
872872
void BLEDevice::deinit(bool release_memory) {
873873
if (!initialized) {
874874
return;
875875
}
876876

877+
// Stop advertising and scanning first
878+
if (m_bleAdvertising != nullptr) {
879+
m_bleAdvertising->stop();
880+
}
881+
882+
if (m_pScan != nullptr) {
883+
m_pScan->stop();
884+
}
885+
886+
// Delete all BLE objects
887+
if (m_bleAdvertising != nullptr) {
888+
delete m_bleAdvertising;
889+
m_bleAdvertising = nullptr;
890+
}
891+
892+
if (m_pScan != nullptr) {
893+
delete m_pScan;
894+
m_pScan = nullptr;
895+
}
896+
897+
if (m_pServer != nullptr) {
898+
delete m_pServer;
899+
m_pServer = nullptr;
900+
}
901+
902+
if (m_pClient != nullptr) {
903+
delete m_pClient;
904+
m_pClient = nullptr;
905+
}
906+
907+
// Clear the connected clients map
908+
m_connectedClientsMap.clear();
909+
910+
// Always deinit the BLE stack
877911
#ifdef CONFIG_BLUEDROID_ENABLED
878912
esp_bluedroid_disable();
879913
esp_bluedroid_deinit();
@@ -893,19 +927,20 @@ void BLEDevice::deinit(bool release_memory) {
893927
esp_bt_controller_deinit();
894928
#endif
895929

896-
#ifdef ARDUINO_ARCH_ESP32
930+
// Only release memory if requested (this prevents reinitialization)
897931
if (release_memory) {
932+
#ifdef ARDUINO_ARCH_ESP32
898933
// Require tests because we released classic BT memory and this can cause crash (most likely not, esp-idf takes care of it)
899934
#if CONFIG_BT_CONTROLLER_ENABLED
900935
esp_bt_controller_mem_release(ESP_BT_MODE_BTDM);
901936
#endif
902-
} else {
903-
#ifdef CONFIG_NIMBLE_ENABLED
904-
m_synced = false;
905937
#endif
906-
initialized = false;
907938
}
939+
940+
#ifdef CONFIG_NIMBLE_ENABLED
941+
m_synced = false;
908942
#endif
943+
initialized = false;
909944
}
910945

911946
void BLEDevice::setCustomGapHandler(gap_event_handler handler) {

0 commit comments

Comments
 (0)