@@ -109,7 +109,16 @@ bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type) {
109109 return false ;
110110 }
111111
112- m_semaphoreRegEvt.wait (" connect" );
112+ uint32_t rc = m_semaphoreRegEvt.wait (" connect" );
113+
114+ if (rc != ESP_GATT_OK) {
115+ // fixes ESP_GATT_NO_RESOURCES error mostly
116+ log_e (" esp_ble_gattc_app_register_error: rc=%d" , rc);
117+ BLEDevice::removePeerDevice (m_appId, true );
118+ // not sure if this is needed here
119+ // esp_ble_gattc_app_unregister(m_gattc_if);
120+ return false ;
121+ }
113122
114123 m_peerAddress = address;
115124
@@ -127,7 +136,12 @@ bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type) {
127136 return false ;
128137 }
129138
130- uint32_t rc = m_semaphoreOpenEvt.wait (" connect" ); // Wait for the connection to complete.
139+ rc = m_semaphoreOpenEvt.wait (" connect" ); // Wait for the connection to complete.
140+ // check the status of the connection and cleanup in case of failure
141+ if (rc != ESP_GATT_OK) {
142+ BLEDevice::removePeerDevice (m_appId, true );
143+ esp_ble_gattc_app_unregister (m_gattc_if);
144+ }
131145 log_v (" << connect(), rc=%d" , rc==ESP_GATT_OK);
132146 return rc == ESP_GATT_OK;
133147} // connect
@@ -159,6 +173,11 @@ void BLEClient::gattClientEventHandler(
159173 log_d (" gattClientEventHandler [esp_gatt_if: %d] ... %s" ,
160174 gattc_if, BLEUtils::gattClientEventTypeToString (event).c_str ());
161175
176+ // it is possible to receive events from other connections while waiting for registration
177+ if (m_gattc_if == ESP_GATT_IF_NONE && event != ESP_GATTC_REG_EVT) {
178+ return ;
179+ }
180+
162181 // Execute handler code based on the type of event received.
163182 switch (event) {
164183
@@ -183,15 +202,16 @@ void BLEClient::gattClientEventHandler(
183202 if (evtParam->disconnect .conn_id != getConnId ()) break ;
184203 // If we receive a disconnect event, set the class flag that indicates that we are
185204 // no longer connected.
186- if (m_isConnected && m_pClientCallbacks != nullptr ) {
187- m_pClientCallbacks->onDisconnect (this );
188- }
205+ bool m_wasConnected = m_isConnected;
189206 m_isConnected = false ;
190207 esp_ble_gattc_app_unregister (m_gattc_if);
191208 m_semaphoreOpenEvt.give (ESP_GATT_IF_NONE);
192209 m_semaphoreRssiCmplEvt.give ();
193210 m_semaphoreSearchCmplEvt.give (1 );
194211 BLEDevice::removePeerDevice (m_appId, true );
212+ if (m_wasConnected && m_pClientCallbacks != nullptr ) {
213+ m_pClientCallbacks->onDisconnect (this );
214+ }
195215 break ;
196216 } // ESP_GATTC_DISCONNECT_EVT
197217
@@ -227,7 +247,8 @@ void BLEClient::gattClientEventHandler(
227247 //
228248 case ESP_GATTC_REG_EVT: {
229249 m_gattc_if = gattc_if;
230- m_semaphoreRegEvt.give ();
250+ // pass on the registration status result, in case of failure
251+ m_semaphoreRegEvt.give (evtParam->reg .status );
231252 break ;
232253 } // ESP_GATTC_REG_EVT
233254
0 commit comments