Skip to content

Commit

Permalink
feat: rethrow UnknownObject as BleakNotFoundError (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Aug 8, 2022
1 parent 11a47b3 commit a07c50e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/bleak_retry_connector/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
# These errors are transient with dbus, and we should retry
TRANSIENT_ERRORS = {"le-connection-abort-by-local", "br-connection-canceled"}

DEVICE_MISSING_ERRORS = {"org.freedesktop.DBus.Error.UnknownObject"}

# Currently the same as transient error
ABORT_ERRORS = TRANSIENT_ERRORS

Expand All @@ -46,6 +48,10 @@
"Extension cables reduce USB 3 port interference"
)

DEVICE_MISSING_ADVICE = (
"The device disappeared; " "Try restarting the scanner or moving the device closer"
)


class BleakNotFoundError(BleakError):
"""The device was not found."""
Expand Down Expand Up @@ -92,6 +98,10 @@ def _raise_if_needed(name: str, exc: Exception) -> None:
error in str(exc) for error in ABORT_ERRORS
):
raise BleakAbortedError(f"{msg}: {ABORT_ADVICE}") from exc
if isinstance(exc, BleakError) and any(
error in str(exc) for error in DEVICE_MISSING_ERRORS
):
raise BleakNotFoundError(f"{msg}: {DEVICE_MISSING_ADVICE}") from exc
raise BleakConnectionError(msg) from exc

while True:
Expand Down
33 changes: 33 additions & 0 deletions tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,39 @@ async def disconnect(self, *args, **kwargs):
)


@pytest.mark.asyncio
async def test_device_disappeared_error():
class FakeBleakClient(BleakClient):
def __init__(self, *args, **kwargs):
pass

async def connect(self, *args, **kwargs):
raise BleakError(
'[org.freedesktop.DBus.Error.UnknownObject] Method "Connect" with '
'signature "" on interface '
'"org.bluez.Device1" '
"doesn't exist"
)

async def disconnect(self, *args, **kwargs):
pass

try:
await establish_connection(FakeBleakClient, MagicMock(), "test")
except BleakError as e:
exc = e

assert isinstance(exc, BleakNotFoundError)
assert str(exc) == (
"test: "
"Failed to connect: "
"[org.freedesktop.DBus.Error.UnknownObject] "
'Method "Connect" with signature "" on interface "org.bluez.Device1" '
"doesn't exist: The device disappeared; "
"Try restarting the scanner or moving the device closer"
)


@pytest.mark.asyncio
async def test_establish_connection_has_one_unknown_error():

Expand Down

0 comments on commit a07c50e

Please sign in to comment.