Skip to content

Commit 32848f9

Browse files
Ensure connectBLE doesn't return before HCI conn (#3229)
gap_connect() is async, so we need to pause until either it connects or we timeout so that we can ger an accurate connection state. Fixes #3221 (again)
1 parent 51e0673 commit 32848f9

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

libraries/BluetoothHCI/src/BluetoothHCI.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ class BluetoothHCI {
4949

5050
void scanFree(); // Free allocated scan buffers
5151

52+
bool connected() {
53+
return _hciConn != HCI_CON_HANDLE_INVALID;
54+
}
55+
5256
friend class BluetoothHIDMaster;
5357

5458
protected:

libraries/BluetoothHIDMaster/src/BluetoothHIDMaster.cpp

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,22 @@ bool BluetoothHIDMaster::connectBLE(const uint8_t *addr, int addrType) {
225225
}
226226
uint8_t a[6];
227227
memcpy(a, addr, sizeof(a));
228-
return ERROR_CODE_SUCCESS == gap_connect(a, (bd_addr_type_t)addrType);
228+
if (ERROR_CODE_SUCCESS != gap_connect(a, (bd_addr_type_t)addrType)) {
229+
return false;
230+
}
231+
// GAP connection running async. Wait for HCI connect
232+
uint32_t now = millis();
233+
while (millis() - now < 5000) {
234+
if (_hci.connected()) {
235+
break;
236+
}
237+
delay(25);
238+
}
239+
if (!_hci.connected()) {
240+
gap_connect_cancel();
241+
return false;
242+
}
243+
return _hci.connected();
229244
}
230245

231246
bool BluetoothHIDMaster::connectBLE() {

0 commit comments

Comments
 (0)