Skip to content

Commit 76cd2e2

Browse files
authored
Fix BLE connection handling (#4137)
Remove device from Peer list if connection fails. Only call onConnect callback if connection was successful. Only call onDisconnect callback if the connection was previously connected (ESP_GATTC_DISCONNECT_EVT is fired on a unsuccessful connection attempt also). Resolves a number of issues with phantom events and callbacks being fired.
1 parent 9f7ff00 commit 76cd2e2

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

Diff for: libraries/BLE/src/BLEClient.cpp

+9-5
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type) {
105105
esp_err_t errRc = ::esp_ble_gattc_app_register(m_appId);
106106
if (errRc != ESP_OK) {
107107
log_e("esp_ble_gattc_app_register: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
108+
BLEDevice::removePeerDevice(m_appId, true);
108109
return false;
109110
}
110111

@@ -122,6 +123,7 @@ bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type) {
122123
);
123124
if (errRc != ESP_OK) {
124125
log_e("esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
126+
BLEDevice::removePeerDevice(m_appId, true);
125127
return false;
126128
}
127129

@@ -181,10 +183,10 @@ void BLEClient::gattClientEventHandler(
181183
if (evtParam->disconnect.conn_id != getConnId()) break;
182184
// If we receive a disconnect event, set the class flag that indicates that we are
183185
// no longer connected.
184-
m_isConnected = false;
185-
if (m_pClientCallbacks != nullptr) {
186+
if (m_isConnected && m_pClientCallbacks != nullptr) {
186187
m_pClientCallbacks->onDisconnect(this);
187188
}
189+
m_isConnected = false;
188190
esp_ble_gattc_app_unregister(m_gattc_if);
189191
m_semaphoreOpenEvt.give(ESP_GATT_IF_NONE);
190192
m_semaphoreRssiCmplEvt.give();
@@ -203,11 +205,13 @@ void BLEClient::gattClientEventHandler(
203205
//
204206
case ESP_GATTC_OPEN_EVT: {
205207
m_conn_id = evtParam->open.conn_id;
206-
if (m_pClientCallbacks != nullptr) {
207-
m_pClientCallbacks->onConnect(this);
208-
}
209208
if (evtParam->open.status == ESP_GATT_OK) {
210209
m_isConnected = true; // Flag us as connected.
210+
if (m_pClientCallbacks != nullptr) {
211+
m_pClientCallbacks->onConnect(this);
212+
}
213+
} else {
214+
log_e("Failed to connect, status=%s", GeneralUtils::errorToString(evtParam->open.status));
211215
}
212216
m_semaphoreOpenEvt.give(evtParam->open.status);
213217
break;

0 commit comments

Comments
 (0)