Skip to content

Commit 34d5c82

Browse files
authored
Add method to check if advertisement has actually changed (#104)
1 parent 8188fbe commit 34d5c82

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

switchbot/adv_parser.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Library to handle connection with Switchbot."""
22
from __future__ import annotations
3+
from functools import lru_cache
34

45
import logging
56
from collections.abc import Callable
@@ -104,11 +105,19 @@ def parse_advertisement_data(
104105
if not _service_data:
105106
return None
106107
_mfr_data = _mgr_datas[0] if _mgr_datas else None
107-
_model = chr(_service_data[0] & 0b01111111)
108108

109+
data = _parse_data(_service_data, _mfr_data)
110+
return SwitchBotAdvertisement(device.address, data, device)
111+
112+
113+
@lru_cache(maxsize=128)
114+
def _parse_data(
115+
_service_data: bytes, _mfr_data: bytes | None
116+
) -> SwitchBotAdvertisement | None:
117+
"""Parse advertisement data."""
118+
_model = chr(_service_data[0] & 0b01111111)
109119
data = {
110-
"address": device.address, # MacOS uses UUIDs
111-
"rawAdvData": list(advertisement_data.service_data.values())[0],
120+
"rawAdvData": _service_data,
112121
"data": {},
113122
"model": _model,
114123
"isEncrypted": bool(_service_data[0] & 0b10000000),
@@ -124,6 +133,4 @@ def parse_advertisement_data(
124133
}
125134
)
126135

127-
data["data"]["rssi"] = device.rssi
128-
129-
return SwitchBotAdvertisement(device.address, data, device)
136+
return data

switchbot/devices/device.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,14 @@ def __init__(
110110
self.loop = asyncio.get_event_loop()
111111
self._callbacks: list[Callable[[], None]] = []
112112

113+
def advertisement_changed(self, advertisement: SwitchBotAdvertisement) -> bool:
114+
"""Check if the advertisement has changed."""
115+
return bool(
116+
not self._sb_adv_data
117+
or ble_device_has_changed(self._sb_adv_data.device, advertisement.device)
118+
or advertisement.data != self._sb_adv_data.data
119+
)
120+
113121
def _commandkey(self, key: str) -> str:
114122
"""Add password to key if set."""
115123
if self._password_encoded is None:

0 commit comments

Comments
 (0)