diff --git a/libraries/BLE/src/BLEServer.cpp b/libraries/BLE/src/BLEServer.cpp index 73d60c81..a63278c4 100644 --- a/libraries/BLE/src/BLEServer.cpp +++ b/libraries/BLE/src/BLEServer.cpp @@ -202,13 +202,19 @@ void BLEServer::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t // If we receive a disconnect event then invoke the callback for disconnects (if one is present). // we also want to start advertising again. case ESP_GATTS_DISCONNECT_EVT: { - m_connectedCount--; // Decrement the number of connected devices count. if (m_pServerCallbacks != nullptr) { // If we have callbacks, call now. m_pServerCallbacks->onDisconnect(this); } - startAdvertising(); //- do this with some delay from the loop() - removePeerDevice(param->disconnect.conn_id, false); - break; + if(m_connId == ESP_GATT_IF_NONE) { + return; + } + + // only decrement if connection is found in map and removed + // sometimes this event triggers w/o a valid connection + if(removePeerDevice(param->disconnect.conn_id, false)) { + m_connectedCount--; // Decrement the number of connected devices count. + } + break; } // ESP_GATTS_DISCONNECT_EVT @@ -395,8 +401,8 @@ void BLEServer::addPeerDevice(void* peer, bool _client, uint16_t conn_id) { m_connectedServersMap.insert(std::pair(conn_id, status)); } -void BLEServer::removePeerDevice(uint16_t conn_id, bool _client) { - m_connectedServersMap.erase(conn_id); +bool BLEServer::removePeerDevice(uint16_t conn_id, bool _client) { + return m_connectedServersMap.erase(conn_id) > 0; } /* multi connect support */ diff --git a/libraries/BLE/src/BLEServer.h b/libraries/BLE/src/BLEServer.h index d2f8038d..c97f093e 100644 --- a/libraries/BLE/src/BLEServer.h +++ b/libraries/BLE/src/BLEServer.h @@ -79,7 +79,7 @@ public: /* multi connection support */ std::map getPeerDevices(bool client); void addPeerDevice(void* peer, bool is_client, uint16_t conn_id); - void removePeerDevice(uint16_t conn_id, bool client); + bool removePeerDevice(uint16_t conn_id, bool client); BLEServer* getServerByConnId(uint16_t conn_id); void updatePeerMTU(uint16_t connId, uint16_t mtu); uint16_t getPeerMTU(uint16_t conn_id);