OpenBluetoothToolbox / SimpleBLE

SimpleBLE - the all-in-one Bluetooth library for MacOS, iOS, Windows, Linux and Android.
https://www.simpleble.org
Other
619 stars 107 forks source link

Deadlock when calling `connect` from scan callback on macOS #311

Open TellowKrinkle opened 1 month ago

TellowKrinkle commented 1 month ago

If you attempt to call peripheral.connect from the callback of set_callback_on_scan_found or set_callback_on_scan_updated, self.peripheral.state will be forever stuck in CBPeripheralStateConnecting until the WAIT_UNTIL_FALSE_WITH_TIMEOUT(self, _task.pending, 5.0) times out.

This is because set_callback_on_scan_found callbacks are called from delegate_did_discover_peripheral which is called from a CBCentralManager delegate callback, which is run on the CBCentralManager's queue. I'd guess the CBCentralManager does updates to all of its data structures on that queue (this is generally how Apple APIs handle thread safety), so by blocking the queue (by sleeping in connect) you prevent the code that updates peripheral.state from running.

This probably applies to any other callbacks as well (e.g. the notify callback).