Skip to content

Commit

Permalink
backends/bluezdbus/manager: Cancel the discovery on disconnect to avo…
Browse files Browse the repository at this point in the history
…id a timeout

If a device disconnects while waiting for the services to be
discovered, the manager will wait forever.
This commit fixes that by throwing an exception in case of a disconnect.
  • Loading branch information
arthur-proglove committed Oct 26, 2022
1 parent b48e4cf commit 5efc2f4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Expand Up @@ -13,6 +13,8 @@ and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0
Fixed
-----
* Fixed crash in Android backend introduced in v0.19.0. Fixes #1085.
* BlueZ: Cancel the device discovery wait task if the device disconnects in
between to avoid a timeout

`0.19.0`_ (2022-10-13)
======================
Expand Down
29 changes: 25 additions & 4 deletions bleak/backends/bluezdbus/manager.py
Expand Up @@ -665,20 +665,41 @@ async def _wait_condition(
):
return

event = asyncio.Event()
services_discovered_event = asyncio.Event()
device_disconnected_event = asyncio.Event()

def callback():
if (
self._properties[device_path][defs.DEVICE_INTERFACE]["Connected"]
is False
):
device_disconnected_event.set()
elif (
self._properties[device_path][defs.DEVICE_INTERFACE][property_name]
== property_value
):
event.set()
services_discovered_event.set()

self._condition_callbacks.add(callback)

try:
# can be canceled
await event.wait()
services_discovered_wait_task = asyncio.create_task(
services_discovered_event.wait()
)
device_disconnected_wait_task = asyncio.create_task(
device_disconnected_event.wait()
)
done, pending = await asyncio.wait(
{services_discovered_wait_task, device_disconnected_wait_task},
return_when=asyncio.FIRST_COMPLETED,
)

for p in pending:
p.cancel()

# device disconnected before the completion of the services discovery
if device_disconnected_wait_task in done:
raise BleakError("failed to discover services, device disconnected")
finally:
self._condition_callbacks.remove(callback)

Expand Down

0 comments on commit 5efc2f4

Please sign in to comment.