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 14, 2024
1 parent f1b8425 commit c9bc45a
Showing 1 changed file with 30 additions and 8 deletions.
38 changes: 30 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.split('/')[-1]}'"
)

try:
value = interface_properties[property_name]
except KeyError:
raise BleakError(
f"Property '{property_name}' not found for '{device_path.split('/')[-1]} and {interface}'"
)

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 Expand Up @@ -917,6 +936,9 @@ def _parse_msg(self, message: Message):
except KeyError:
pass

if obj_path in self._properties and not self._properties[obj_path]:
del self._properties[obj_path]

if interface == defs.ADAPTER_INTERFACE:
try:
self._adapters.remove(obj_path)
Expand Down

0 comments on commit c9bc45a

Please sign in to comment.