Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix BlueZ wait condition disconnect race #1399

Merged
merged 3 commits into from
Aug 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Changed
* Scanner backends modified to allow multiple advertisement callbacks. Merged #1367.
* Changed default handling of the ``response`` argument in ``BleakClient.write_gatt_char``.
Fixes #909.
* Changed `BlueZManager` methods to raise `BleakError` when device is not in BlueZ.

Fixed
-----
Expand All @@ -31,6 +32,7 @@ Fixed
* Fixed typing for ``BaseBleakScanner`` detection callback.
* Fixed possible crash in ``_stopped_handler()`` in WinRT backend. Fixes #1330.
* Reduced expensive logging in the BlueZ backend. Merged #1376.
* Fixed race condition with ``"InterfaceRemoved"`` when getting services in BlueZ backend.

`0.20.2`_ (2023-04-19)
======================
Expand Down
149 changes: 126 additions & 23 deletions bleak/backends/bluezdbus/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""

import asyncio
import contextlib
import logging
import os
from typing import (
Expand Down Expand Up @@ -66,6 +67,12 @@ class CallbackAndState(NamedTuple):
"""


DevicePropertiesChangedCallback = Callable[[], None]
"""
A callback that is called when the properties of a device change in BlueZ.
"""


DeviceRemovedCallback = Callable[[str], None]
"""
A callback that is called when a device is removed from BlueZ.
Expand Down Expand Up @@ -167,9 +174,25 @@ def __init__(self):
self._advertisement_callbacks: List[CallbackAndState] = []
self._device_removed_callbacks: List[DeviceRemovedCallbackAndState] = []
self._device_watchers: Set[DeviceWatcher] = set()
self._condition_callbacks: Set[Callable] = set()
self._condition_callbacks: Dict[str, Set[DevicePropertiesChangedCallback]] = {}
self._services_cache: Dict[str, BleakGATTServiceCollection] = {}

def _check_adapter(self, adapter_path: str) -> None:
"""
Raises:
BleakError: if adapter is not present in BlueZ
"""
if adapter_path not in self._properties:
raise BleakError(f"adapter '{adapter_path.split('/')[-1]}' not found")

def _check_device(self, device_path: str) -> None:
"""
Raises:
BleakError: if device is not present in BlueZ
"""
if device_path not in self._properties:
raise BleakError(f"device '{device_path.split('/')[-1]}' not found")

async def async_init(self):
"""
Connects to the D-Bus message bus and begins monitoring signals.
Expand Down Expand Up @@ -326,13 +349,15 @@ async def active_scan(

Returns:
An async function that is used to stop scanning and remove the filters.

Raises:
BleakError: if the adapter is not present in BlueZ
"""
async with self._bus_lock:
# If the adapter doesn't exist, then the message calls below would
# fail with "method not found". This provides a more informative
# error message.
if adapter_path not in self._properties:
raise BleakError(f"adapter '{adapter_path.split('/')[-1]}' not found")
self._check_adapter(adapter_path)

callback_and_state = CallbackAndState(advertisement_callback, adapter_path)
self._advertisement_callbacks.append(callback_and_state)
Expand Down Expand Up @@ -432,13 +457,15 @@ async def passive_scan(

Returns:
An async function that is used to stop scanning and remove the filters.

Raises:
BleakError: if the adapter is not present in BlueZ
"""
async with self._bus_lock:
# If the adapter doesn't exist, then the message calls below would
# fail with "method not found". This provides a more informative
# error message.
if adapter_path not in self._properties:
raise BleakError(f"adapter '{adapter_path.split('/')[-1]}' not found")
self._check_adapter(adapter_path)

callback_and_state = CallbackAndState(advertisement_callback, adapter_path)
self._advertisement_callbacks.append(callback_and_state)
Expand Down Expand Up @@ -534,7 +561,12 @@ def add_device_watcher(

Returns:
A device watcher object that acts a token to unregister the watcher.

Raises:
BleakError: if the device is not present in BlueZ
"""
self._check_device(device_path)

watcher = DeviceWatcher(
device_path, on_connected_changed, on_characteristic_value_changed
)
Expand Down Expand Up @@ -571,7 +603,12 @@ async def get_services(

Returns:
A new :class:`BleakGATTServiceCollection`.

Raises:
BleakError: if the device is not present in BlueZ
"""
self._check_device(device_path)

if use_cached:
services = self._services_cache.get(device_path)
if services is not None:
Expand Down Expand Up @@ -644,7 +681,12 @@ def get_device_name(self, device_path: str) -> str:

Returns:
The current property value.

Raises:
BleakError: if the device is not present in BlueZ
"""
self._check_device(device_path)

return self._properties[device_path][defs.DEVICE_INTERFACE]["Name"]

def is_connected(self, device_path: str) -> bool:
Expand All @@ -655,7 +697,7 @@ def is_connected(self, device_path: str) -> bool:
device_path: The D-Bus object path of the device.

Returns:
The current property value.
The current property value or ``False`` if the device does not exist in BlueZ.
"""
try:
return self._properties[device_path][defs.DEVICE_INTERFACE]["Connected"]
Expand All @@ -667,23 +709,76 @@ async def _wait_for_services_discovery(self, device_path: str) -> None:
Waits for the device services to be discovered.

If a disconnect happens before the completion a BleakError exception is raised.

Raises:
BleakError: if the device is not present in BlueZ
"""
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,
)
self._check_device(device_path)

with contextlib.ExitStack() as stack:
services_discovered_wait_task = asyncio.create_task(
self._wait_condition(device_path, "ServicesResolved", True)
)
stack.callback(services_discovered_wait_task.cancel)

device_disconnected_wait_task = asyncio.create_task(
self._wait_condition(device_path, "Connected", False)
)
stack.callback(device_disconnected_wait_task.cancel)

for p in pending:
p.cancel()
# in some cases, we can get "InterfaceRemoved" without the
# "Connected" property changing, so we need to race against both
# conditions
device_removed_wait_task = asyncio.create_task(
self._wait_removed(device_path)
)
stack.callback(device_removed_wait_task.cancel)

done, _ = await asyncio.wait(
{
services_discovered_wait_task,
device_disconnected_wait_task,
device_removed_wait_task,
},
return_when=asyncio.FIRST_COMPLETED,
)

dlech marked this conversation as resolved.
Show resolved Hide resolved
if device_disconnected_wait_task in done:
raise BleakError("failed to discover services, device disconnected")
# check for exceptions
for task in done:
task.result()

if not done.isdisjoint(
{device_disconnected_wait_task, device_removed_wait_task}
):
raise BleakError("failed to discover services, device disconnected")

async def _wait_removed(self, device_path: str) -> None:
"""
Waits for the device interface to be removed.

If the device is not present in BlueZ, this returns immediately.

Args:
device_path: The D-Bus object path of a Bluetooth device.
"""
if device_path not in self._properties:
return

event = asyncio.Event()

def callback(_: str):
event.set()

device_removed_callback_and_state = DeviceRemovedCallbackAndState(
callback, self._properties[device_path][defs.DEVICE_INTERFACE]["Adapter"]
)

with contextlib.ExitStack() as stack:
self._device_removed_callbacks.append(device_removed_callback_and_state)
stack.callback(
self._device_removed_callbacks.remove, device_removed_callback_and_state
)
await event.wait()

async def _wait_condition(
self, device_path: str, property_name: str, property_value: Any
Expand All @@ -695,7 +790,12 @@ async def _wait_condition(
device_path: The D-Bus object path of a Bluetooth device.
property_name: The name of the property to test.
property_value: A value to compare the current property value to.

Raises:
BleakError: if the device is not present in BlueZ
"""
self._check_device(device_path)

if (
self._properties[device_path][defs.DEVICE_INTERFACE][property_name]
== property_value
Expand All @@ -711,13 +811,14 @@ def callback():
):
event.set()

self._condition_callbacks.add(callback)
device_callbacks = self._condition_callbacks.setdefault(device_path, set())
device_callbacks.add(callback)

try:
# can be canceled
await event.wait()
finally:
self._condition_callbacks.remove(callback)
device_callbacks.remove(callback)

def _parse_msg(self, message: Message):
"""
Expand Down Expand Up @@ -851,7 +952,9 @@ def _parse_msg(self, message: Message):
)

# handle device condition watchers
for condition_callback in self._condition_callbacks:
for condition_callback in self._condition_callbacks.get(
message.path, ()
):
condition_callback()

# handle device connection change watchers
Expand Down
Loading