hbldh / bleak

A cross platform Bluetooth Low Energy Client for Python using asyncio
MIT License
1.61k stars 279 forks source link

Asyncio task hang during connection attempt #1591

Open mlaz opened 3 weeks ago

mlaz commented 3 weeks ago

Description

Every time there is an attempt to connect to a device and during this attempt the device disappears, the task performing the attempt to connect hangs. We found an uncaught asyncio.exceptions.CancelledError on dbus-fast/aio/message_bus.py on the implementation of the call method, where it awaits for a reply to the performed d-bus call. We quickly fixed this by catching this exception on dbus-fast. Even though this exception gets caught and raised, and later caught in bleak client.py it still hangs.

What I Did

We implemented a program that scans using a characteristic filter, periodically during 5sec. At the end of each scanning period it sorts and filters a list of devices based on the average RSSI values(and some other calculations) and attempts to connect to some of them. This connection is done to one device at a time, and of course after disabling the scanner (also passing the BLEDevice to the BleakClient constructor). We did implement a few variations, one of them spawns one task per device, using a lock whenever we are either connecting+subscribing to characteristics, another just attempts to connect inside the same task that scans. Both approaches work quite well, unless one of the target devices disappears during the connection attempt, as described previously.

Logs

We will soon provide a code sample with a similar implementation to what we have and corresponding logs so we can provide a clean output and not expose information that is inherent to our application.

dlech commented 3 weeks ago

Can you provide a minimal reproducible test case and logs showing timing of when connections are started and completed along with the full stack trace of the error?