Skip to content

Commit

Permalink
Improve error handling when a device is not present in BlueZ
Browse files Browse the repository at this point in the history
  • Loading branch information
Siecje committed Feb 15, 2024
1 parent f1b8425 commit b783fae
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Fixed
-----
* Fixed BlueZ version in passive scanning error message. Fixes #1433.
* Fixed mypy requiring ``Unpack[ExtraArgs]`` that were intended to be optional. Fixes #1487.
* Fixed ``KeyError`` in BlueZ ``is_connected()`` and ``get_global_bluez_manager()`` when device is not present. Fixes #1507.

`0.21.1`_ (2023-09-08)
======================
Expand Down
35 changes: 27 additions & 8 deletions bleak/backends/bluezdbus/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,28 @@ def _check_device(self, device_path: str) -> None:
if device_path not in self._properties:
raise BleakError(f"device '{device_path.split('/')[-1]}' not found")

def _get_device_property(
self, device_path: str, interface: str, property_name: str
) -> Any:
self._check_device(device_path)
device_properties = self._properties[device_path]

try:
interface_properties = device_properties[interface]
except KeyError:
raise BleakError(
f"Interface {interface} not found for device '{device_path}'"
)

try:
value = interface_properties[property_name]
except KeyError:
raise BleakError(
f"Property '{property_name}' not found for '{interface}' in '{device_path}'"
)

return value

async def async_init(self):
"""
Connects to the D-Bus message bus and begins monitoring signals.
Expand Down Expand Up @@ -711,9 +733,7 @@ def get_device_name(self, device_path: str) -> str:
Raises:
BleakError: if the device is not present in BlueZ
"""
self._check_device(device_path)

return self._properties[device_path][defs.DEVICE_INTERFACE]["Name"]
return self._get_device_property(device_path, defs.DEVICE_INTERFACE, "Name")

def is_connected(self, device_path: str) -> bool:
"""
Expand Down Expand Up @@ -820,12 +840,11 @@ async def _wait_condition(
Raises:
BleakError: if the device is not present in BlueZ
"""
self._check_device(device_path)
value = self._get_device_property(
device_path, defs.DEVICE_INTERFACE, property_name
)

if (
self._properties[device_path][defs.DEVICE_INTERFACE][property_name]
== property_value
):
if value == property_value:
return

event = asyncio.Event()
Expand Down

0 comments on commit b783fae

Please sign in to comment.