Skip to content

Commit

Permalink
Merge pull request #522 from bojanpotocnik/develop
Browse files Browse the repository at this point in the history
Add error description to BleakDBusError in addition to error name
  • Loading branch information
dlech authored Apr 23, 2021
2 parents 3c388dd + 63e77f0 commit d8fba81
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 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 @@ Changed
* Added ``Programming Language :: Python :: 3.9`` classifier in ``setup.py``
* Deprecated ``BleakScanner.get_discovered_devices()`` async method.
* Added capability to handle async functions as detection callbacks in ``BleakScanner``.
* Added error description in addition to error name when ``BleakDBusError`` is converted to string

Fixed
~~~~~
Expand Down
2 changes: 1 addition & 1 deletion bleak/backends/bluezdbus/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def assert_reply(reply: Message):
AssentationError: if the message type is not ``MessageType.METHOD_RETURN``
"""
if reply.message_type == MessageType.ERROR:
raise BleakDBusError(reply.error_name)
raise BleakDBusError(reply.error_name, reply.body)
assert reply.message_type == MessageType.METHOD_RETURN


Expand Down
25 changes: 23 additions & 2 deletions bleak/exc.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
from typing import Optional


class BleakError(Exception):
Expand All @@ -16,18 +17,38 @@ class BleakDotNetTaskError(BleakError):
class BleakDBusError(BleakError):
"""Specialized exception type for D-Bus errors."""

def __init__(self, dbus_error: str):
def __init__(self, dbus_error: str, error_body: list):
"""
Args:
dbus_error (str): The D-Bus error, e.g. ``org.freedesktop.DBus.Error.UnknownObject``.
error_body (list): Body of the D-Bus error, sometimes containing error description or details.
"""
super().__init__(dbus_error)
super().__init__(dbus_error, *error_body)

@property
def dbus_error(self) -> str:
"""Gets the D-Bus error name, e.g. ``org.freedesktop.DBus.Error.UnknownObject``."""
return self.args[0]

@property
def dbus_error_details(self) -> Optional[str]:
"""Gets the optional D-Bus error details, e.g. 'Invalid UUID'."""
if len(self.args) > 1:
details = self.args[1]
# Some error descriptions can be further parsed to be even more helpful
if "ATT error: 0x" in details:
more_detail = CONTROLLER_ERROR_CODES.get(
int(details.rsplit("x")[1], 16), "Unknown code"
)
details += f" ({more_detail})"
return details
return None

def __str__(self) -> str:
name = f"[{self.dbus_error}]"
details = self.dbus_error_details
return (name + " " + details) if details else name


CONTROLLER_ERROR_CODES = {
0x00: "Success",
Expand Down

0 comments on commit d8fba81

Please sign in to comment.