manolofdez / AsyncBluetooth

A small library that adds concurrency to CoreBluetooth APIs.
MIT License
160 stars 30 forks source link

Batching the connection requests #7

Closed mickeyl closed 2 years ago

mickeyl commented 2 years ago

CoreBluetooth devices such as the iPhone or the iPad can only be connected to a certain amount of devices at the same time – I think the limitation is in the range of about 5-12.

If you continue to try connecting to more devices, unfortunate things can happen, i.e. the bluetooth daemon reset, timeouts, etc.

I wonder whether AsyncBluetooth could do anything to help circumventing this by allowing to specify a threshold number. Any more connection request would then either fail or halt until the number of connected devices has decreased again.

A concrete example… in my app I can't filter to scan for a specific service, since it's not standardized. Hence, I need to connect to each and every available device, do some tests and then decide whether the device is eligible for displaying or not. In theory this could mean tens or hundreds of connection attempts in parallel, which is a recipe for desaster.

manolofdez commented 2 years ago

Hi! There are no current plans for tracking connected peripherals. That said, AsyncBluetooth can still be useful in your app. The AsyncStream returned from the central manager's scanForPeripherals is buffered. You should be able to connect to a number of peripherals by iterating over the stream, and either use await inside the loop to wait for available slots or stop iterating (without stopping the scan). If you didn't find the peripheral you were looking for, you can then resume iteration with the rest of the peripherals discovered during your connection attempts.

mickeyl commented 2 years ago

Ok, I can implement my own connection tracking. It won't be as accurate as if it were be done in the library, since I'm not the delegate and can only base it on the connect / cancelConnection requests I do though – i.e. then I won't be able to catch devices that disconnect on their own terms.

manolofdez commented 2 years ago

You should be able to subscribe to the central manager's eventPublisher and get disconnection events.