Skip to content

Commit

Permalink
feat: add ble_device_has_changed helper (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Aug 11, 2022
1 parent d2e8733 commit 0a23bb8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/bleak_retry_connector/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,19 @@ def set_cached_services(self, services: BleakGATTServiceCollection | None) -> No
self._cached_services = services


def ble_device_has_changed(original: BLEDevice, new: BLEDevice) -> bool:
"""Check if the device has changed."""
if original.address != new.address:
return True
if (
isinstance(original.details, dict)
and "path" in original.details
and original.details["path"] != new.details["path"]
):
return True
return False


async def establish_connection(
client_class: type[BleakClient],
device: BLEDevice,
Expand Down
18 changes: 18 additions & 0 deletions tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import pytest
from bleak import BleakClient, BleakError
from bleak.backends.device import BLEDevice
from bleak.backends.service import BleakGATTServiceCollection

import bleak_retry_connector
Expand All @@ -12,6 +13,7 @@
BleakClientWithServiceCache,
BleakConnectionError,
BleakNotFoundError,
ble_device_has_changed,
establish_connection,
)

Expand Down Expand Up @@ -390,3 +392,19 @@ async def disconnect(self, *args, **kwargs):
BleakNotFoundError
):
await establish_connection(FakeBleakClient, MagicMock(), "test")


def test_ble_device_has_changed():
"""Test that the BLEDevice has changed when the underlying device has changed."""
assert not ble_device_has_changed(
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}),
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}),
)
assert ble_device_has_changed(
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}),
BLEDevice("ab:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}),
)
assert ble_device_has_changed(
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/1"}),
BLEDevice("aa:bb:cc:dd:ee:ff", "name", {"path": "/dev/2"}),
)

0 comments on commit 0a23bb8

Please sign in to comment.