Skip to content

Commit

Permalink
feat: improve handling of out of esp32 proxy connection slots (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco committed Oct 24, 2022
1 parent f076fd2 commit 982b7ae
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 8 deletions.
31 changes: 23 additions & 8 deletions src/bleak_retry_connector/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
# to run their cleanup callbacks or the
# retry call will just fail in the same way.
BLEAK_DBUS_BACKOFF_TIME = 0.25
BLEAK_OUT_OF_SLOTS_BACKOFF_TIME = 1.5
BLEAK_BACKOFF_TIME = 0.1


Expand Down Expand Up @@ -91,6 +92,8 @@

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

OUT_OF_SLOTS_ERRORS = {"available connection", "connection slot"}

# Currently the same as transient error
ABORT_ERRORS = TRANSIENT_ERRORS

Expand All @@ -104,6 +107,11 @@
"The device disappeared; " "Try restarting the scanner or moving the device closer"
)

OUT_OF_SLOTS_ADVICE = (
"The proxy/adapter is out of connection slots; "
"Add additional proxies near this device"
)


class BleakNotFoundError(BleakError):
"""The device was not found."""
Expand All @@ -117,6 +125,10 @@ class BleakAbortedError(BleakError):
"""The connection was aborted."""


class BleakOutOfConnectionSlotsError(BleakError):
"""The proxy/adapter is out of connection slots."""


class BleakClientWithServiceCache(BleakClient):
"""A BleakClient that implements service caching."""

Expand Down Expand Up @@ -183,6 +195,8 @@ def address_to_bluez_path(address: str, adapter: str | None = None) -> str:

def calculate_backoff_time(exc: Exception) -> float:
"""Calculate the backoff time based on the exception."""
if isinstance(exc, BleakOutOfConnectionSlotsError):
return BLEAK_OUT_OF_SLOTS_BACKOFF_TIME
if isinstance(
exc, (BleakDBusError, EOFError, asyncio.TimeoutError, BrokenPipeError)
):
Expand Down Expand Up @@ -431,14 +445,15 @@ def _raise_if_needed(name: str, description: str, exc: Exception) -> None:
# Sure would be nice if bleak gave us typed exceptions
if isinstance(exc, asyncio.TimeoutError) or "not found" in str(exc):
raise BleakNotFoundError(msg) from exc
if isinstance(exc, BleakError) and any(
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
if isinstance(exc, BleakError):
if any(error in str(exc) for error in ABORT_ERRORS):
raise BleakAbortedError(f"{msg}: {ABORT_ADVICE}") from exc
if any(error in str(exc) for error in DEVICE_MISSING_ERRORS):
raise BleakNotFoundError(f"{msg}: {DEVICE_MISSING_ADVICE}") from exc
if any(error in str(exc) for error in OUT_OF_SLOTS_ERRORS):
raise BleakOutOfConnectionSlotsError(
f"{msg}: {OUT_OF_SLOTS_ADVICE}"
) from exc
raise BleakConnectionError(msg) from exc

create_client = True
Expand Down
37 changes: 37 additions & 0 deletions tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@
from bleak_retry_connector import (
BLEAK_BACKOFF_TIME,
BLEAK_DBUS_BACKOFF_TIME,
BLEAK_OUT_OF_SLOTS_BACKOFF_TIME,
MAX_TRANSIENT_ERRORS,
BleakAbortedError,
BleakClientWithServiceCache,
BleakConnectionError,
BleakNotFoundError,
BleakOutOfConnectionSlotsError,
ble_device_has_changed,
calculate_backoff_time,
establish_connection,
Expand Down Expand Up @@ -434,6 +436,37 @@ async def disconnect(self, *args, **kwargs):
)


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

async def connect(self, *args, **kwargs):
raise BleakError("out of connection slots")

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

try:
await establish_connection(
FakeBleakClient,
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}),
"test",
)
except BleakError as e:
exc = e

assert isinstance(exc, BleakOutOfConnectionSlotsError)
assert str(exc) == (
"test - /dev/1: "
"Failed to connect: "
"out of connection slots: "
"The proxy/adapter is out of connection slots; "
"Add additional proxies near this device"
)


@pytest.mark.asyncio
async def test_device_disappeared_error():
class FakeBleakClient(BleakClient):
Expand Down Expand Up @@ -1443,6 +1476,10 @@ def test_calculate_backoff_time():
calculate_backoff_time(BleakDBusError(MagicMock(), MagicMock()))
== BLEAK_DBUS_BACKOFF_TIME
)
assert (
calculate_backoff_time(BleakOutOfConnectionSlotsError())
== BLEAK_OUT_OF_SLOTS_BACKOFF_TIME
)


@pytest.mark.asyncio
Expand Down

0 comments on commit 982b7ae

Please sign in to comment.