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 27, 2022
1 parent b48e4cf commit d128393
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
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
25 changes: 24 additions & 1 deletion bleak/backends/bluezdbus/manager.py
Expand Up @@ -570,7 +570,7 @@ async def get_services(
logger.debug("Using cached services for %s", device_path)
return services

await self._wait_condition(device_path, "ServicesResolved", True)
await self._wait_for_service_disovery(device_path)

services = BleakGATTServiceCollection()

Expand Down Expand Up @@ -648,6 +648,29 @@ def is_connected(self, device_path: str) -> bool:
except KeyError:
return False

async def _wait_for_service_disovery(self, device_path: str) -> None:
"""Wait for the device services to be discovered.
If a disconnect happens before the completion a BleakError exception is raised.
"""
services_discovered_wait_task = asyncio.create_task(
self._wait_condition(device_path, "ServicesResolved", True)
)
device_disconnected_wait_task = asyncio.create_task(
self._wait_condition(device_path, "Connected", False)
)
done, pending = await asyncio.wait(
{services_discovered_wait_task, device_disconnected_wait_task},
return_when=asyncio.FIRST_COMPLETED,
)

for p in pending:
p.cancel()

if device_disconnected_wait_task in done:
raise BleakError("failed to discover services, device disconnected")

async def _wait_condition(
self, device_path: str, property_name: str, property_value: Any
) -> None:
Expand Down

0 comments on commit d128393

Please sign in to comment.