device.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. """Library to handle connection with Switchbot."""
  2. from __future__ import annotations
  3. import asyncio
  4. import binascii
  5. import logging
  6. import time
  7. from dataclasses import replace
  8. from enum import Enum
  9. from typing import Any, Callable, TypeVar, cast
  10. from uuid import UUID
  11. import async_timeout
  12. from bleak.backends.device import BLEDevice
  13. from bleak.backends.service import BleakGATTCharacteristic, BleakGATTServiceCollection
  14. from bleak.exc import BleakDBusError
  15. from bleak_retry_connector import (
  16. BLEAK_RETRY_EXCEPTIONS,
  17. BleakClientWithServiceCache,
  18. BleakNotFoundError,
  19. ble_device_has_changed,
  20. establish_connection,
  21. )
  22. from bleak_retry_connector import BLEAK_RETRY_EXCEPTIONS
  23. from ..const import DEFAULT_RETRY_COUNT, DEFAULT_SCAN_TIMEOUT
  24. from ..discovery import GetSwitchbotDevices
  25. from ..models import SwitchBotAdvertisement
  26. _LOGGER = logging.getLogger(__name__)
  27. REQ_HEADER = "570f"
  28. # Keys common to all device types
  29. DEVICE_GET_BASIC_SETTINGS_KEY = "5702"
  30. DEVICE_SET_MODE_KEY = "5703"
  31. DEVICE_SET_EXTENDED_KEY = REQ_HEADER
  32. # Base key when encryption is set
  33. KEY_PASSWORD_PREFIX = "571"
  34. DBUS_ERROR_BACKOFF_TIME = 0.25
  35. # How long to hold the connection
  36. # to wait for additional commands for
  37. # disconnecting the device.
  38. DISCONNECT_DELAY = 8.5
  39. class ColorMode(Enum):
  40. OFF = 0
  41. COLOR_TEMP = 1
  42. RGB = 2
  43. EFFECT = 3
  44. # If the scanner is in passive mode, we
  45. # need to poll the device to get the
  46. # battery and a few rarely updating
  47. # values.
  48. PASSIVE_POLL_INTERVAL = 60 * 60 * 24
  49. class CharacteristicMissingError(Exception):
  50. """Raised when a characteristic is missing."""
  51. class SwitchbotOperationError(Exception):
  52. """Raised when an operation fails."""
  53. def _sb_uuid(comms_type: str = "service") -> UUID | str:
  54. """Return Switchbot UUID."""
  55. _uuid = {"tx": "002", "rx": "003", "service": "d00"}
  56. if comms_type in _uuid:
  57. return UUID(f"cba20{_uuid[comms_type]}-224d-11e6-9fb8-0002a5d5c51b")
  58. return "Incorrect type, choose between: tx, rx or service"
  59. READ_CHAR_UUID = _sb_uuid(comms_type="rx")
  60. WRITE_CHAR_UUID = _sb_uuid(comms_type="tx")
  61. WrapFuncType = TypeVar("WrapFuncType", bound=Callable[..., Any])
  62. def update_after_operation(func: WrapFuncType) -> WrapFuncType:
  63. """Define a wrapper to update after an operation."""
  64. async def _async_update_after_operation_wrap(
  65. self: SwitchbotBaseDevice, *args: Any, **kwargs: Any
  66. ) -> None:
  67. ret = await func(self, *args, **kwargs)
  68. await self.update()
  69. return ret
  70. return cast(WrapFuncType, _async_update_after_operation_wrap)
  71. def _merge_data(old_data: dict[str, Any], new_data: dict[str, Any]) -> dict[str, Any]:
  72. """Merge data but only add None keys if they are missing."""
  73. merged = old_data.copy()
  74. for key, value in new_data.items():
  75. if value is not None or key not in old_data:
  76. merged[key] = value
  77. return merged
  78. class SwitchbotBaseDevice:
  79. """Base Representation of a Switchbot Device."""
  80. def __init__(
  81. self,
  82. device: BLEDevice,
  83. password: str | None = None,
  84. interface: int = 0,
  85. **kwargs: Any,
  86. ) -> None:
  87. """Switchbot base class constructor."""
  88. self._interface = f"hci{interface}"
  89. self._device = device
  90. self._sb_adv_data: SwitchBotAdvertisement | None = None
  91. self._override_adv_data: dict[str, Any] | None = None
  92. self._scan_timeout: int = kwargs.pop("scan_timeout", DEFAULT_SCAN_TIMEOUT)
  93. self._retry_count: int = kwargs.pop("retry_count", DEFAULT_RETRY_COUNT)
  94. self._connect_lock = asyncio.Lock()
  95. self._operation_lock = asyncio.Lock()
  96. if password is None or password == "":
  97. self._password_encoded = None
  98. else:
  99. self._password_encoded = "%08x" % (
  100. binascii.crc32(password.encode("ascii")) & 0xFFFFFFFF
  101. )
  102. self._client: BleakClientWithServiceCache | None = None
  103. self._read_char: BleakGATTCharacteristic | None = None
  104. self._write_char: BleakGATTCharacteristic | None = None
  105. self._disconnect_timer: asyncio.TimerHandle | None = None
  106. self._expected_disconnect = False
  107. self.loop = asyncio.get_event_loop()
  108. self._callbacks: list[Callable[[], None]] = []
  109. self._notify_future: asyncio.Future[bytearray] | None = None
  110. self._last_full_update: float = -PASSIVE_POLL_INTERVAL
  111. self._timed_disconnect_task: asyncio.Task[None] | None = None
  112. def advertisement_changed(self, advertisement: SwitchBotAdvertisement) -> bool:
  113. """Check if the advertisement has changed."""
  114. return bool(
  115. not self._sb_adv_data
  116. or ble_device_has_changed(self._sb_adv_data.device, advertisement.device)
  117. or advertisement.data != self._sb_adv_data.data
  118. )
  119. def _commandkey(self, key: str) -> str:
  120. """Add password to key if set."""
  121. if self._password_encoded is None:
  122. return key
  123. key_action = key[3]
  124. key_suffix = key[4:]
  125. return KEY_PASSWORD_PREFIX + key_action + self._password_encoded + key_suffix
  126. async def _send_command(self, key: str, retry: int | None = None) -> bytes | None:
  127. """Send command to device and read response."""
  128. if retry is None:
  129. retry = self._retry_count
  130. command = bytearray.fromhex(self._commandkey(key))
  131. _LOGGER.debug("%s: Scheduling command %s", self.name, command.hex())
  132. max_attempts = retry + 1
  133. if self._operation_lock.locked():
  134. _LOGGER.debug(
  135. "%s: Operation already in progress, waiting for it to complete; RSSI: %s",
  136. self.name,
  137. self.rssi,
  138. )
  139. async with self._operation_lock:
  140. for attempt in range(max_attempts):
  141. try:
  142. return await self._send_command_locked(key, command)
  143. except BleakNotFoundError:
  144. _LOGGER.error(
  145. "%s: device not found, no longer in range, or poor RSSI: %s",
  146. self.name,
  147. self.rssi,
  148. exc_info=True,
  149. )
  150. raise
  151. except CharacteristicMissingError as ex:
  152. if attempt == retry:
  153. _LOGGER.error(
  154. "%s: characteristic missing: %s; Stopping trying; RSSI: %s",
  155. self.name,
  156. ex,
  157. self.rssi,
  158. exc_info=True,
  159. )
  160. raise
  161. _LOGGER.debug(
  162. "%s: characteristic missing: %s; RSSI: %s",
  163. self.name,
  164. ex,
  165. self.rssi,
  166. exc_info=True,
  167. )
  168. except BLEAK_RETRY_EXCEPTIONS:
  169. if attempt == retry:
  170. _LOGGER.error(
  171. "%s: communication failed; Stopping trying; RSSI: %s",
  172. self.name,
  173. self.rssi,
  174. exc_info=True,
  175. )
  176. raise
  177. _LOGGER.debug(
  178. "%s: communication failed with:", self.name, exc_info=True
  179. )
  180. raise RuntimeError("Unreachable")
  181. @property
  182. def name(self) -> str:
  183. """Return device name."""
  184. return f"{self._device.name} ({self._device.address})"
  185. @property
  186. def data(self) -> dict[str, Any]:
  187. """Return device data."""
  188. if self._sb_adv_data:
  189. return self._sb_adv_data.data
  190. return {}
  191. @property
  192. def parsed_data(self) -> dict[str, Any]:
  193. """Return parsed device data."""
  194. return self.data.get("data") or {}
  195. @property
  196. def rssi(self) -> int:
  197. """Return RSSI of device."""
  198. if self._sb_adv_data:
  199. return self._sb_adv_data.rssi
  200. return self._device.rssi
  201. async def _ensure_connected(self):
  202. """Ensure connection to device is established."""
  203. if self._connect_lock.locked():
  204. _LOGGER.debug(
  205. "%s: Connection already in progress, waiting for it to complete; RSSI: %s",
  206. self.name,
  207. self.rssi,
  208. )
  209. if self._client and self._client.is_connected:
  210. self._reset_disconnect_timer()
  211. return
  212. async with self._connect_lock:
  213. # Check again while holding the lock
  214. if self._client and self._client.is_connected:
  215. self._reset_disconnect_timer()
  216. return
  217. _LOGGER.debug("%s: Connecting; RSSI: %s", self.name, self.rssi)
  218. client: BleakClientWithServiceCache = await establish_connection(
  219. BleakClientWithServiceCache,
  220. self._device,
  221. self.name,
  222. self._disconnected,
  223. use_services_cache=True,
  224. ble_device_callback=lambda: self._device,
  225. )
  226. _LOGGER.debug("%s: Connected; RSSI: %s", self.name, self.rssi)
  227. self._client = client
  228. try:
  229. self._resolve_characteristics(client.services)
  230. except CharacteristicMissingError as ex:
  231. _LOGGER.debug(
  232. "%s: characteristic missing, clearing cache: %s; RSSI: %s",
  233. self.name,
  234. ex,
  235. self.rssi,
  236. exc_info=True,
  237. )
  238. await client.clear_cache()
  239. self._cancel_disconnect_timer()
  240. await self._execute_disconnect_with_lock()
  241. raise
  242. self._reset_disconnect_timer()
  243. await self._start_notify()
  244. def _resolve_characteristics(self, services: BleakGATTServiceCollection) -> None:
  245. """Resolve characteristics."""
  246. self._read_char = services.get_characteristic(READ_CHAR_UUID)
  247. if not self._read_char:
  248. raise CharacteristicMissingError(READ_CHAR_UUID)
  249. self._write_char = services.get_characteristic(WRITE_CHAR_UUID)
  250. if not self._write_char:
  251. raise CharacteristicMissingError(WRITE_CHAR_UUID)
  252. def _reset_disconnect_timer(self):
  253. """Reset disconnect timer."""
  254. self._cancel_disconnect_timer()
  255. self._expected_disconnect = False
  256. self._disconnect_timer = self.loop.call_later(
  257. DISCONNECT_DELAY, self._disconnect_from_timer
  258. )
  259. def _disconnected(self, client: BleakClientWithServiceCache) -> None:
  260. """Disconnected callback."""
  261. if self._expected_disconnect:
  262. _LOGGER.debug(
  263. "%s: Disconnected from device; RSSI: %s", self.name, self.rssi
  264. )
  265. return
  266. _LOGGER.warning(
  267. "%s: Device unexpectedly disconnected; RSSI: %s",
  268. self.name,
  269. self.rssi,
  270. )
  271. def _disconnect_from_timer(self):
  272. """Disconnect from device."""
  273. if self._operation_lock.locked() and self._client.is_connected:
  274. _LOGGER.debug(
  275. "%s: Operation in progress, resetting disconnect timer; RSSI: %s",
  276. self.name,
  277. self.rssi,
  278. )
  279. self._reset_disconnect_timer()
  280. return
  281. self._cancel_disconnect_timer()
  282. self._timed_disconnect_task = asyncio.create_task(
  283. self._execute_timed_disconnect()
  284. )
  285. def _cancel_disconnect_timer(self):
  286. """Cancel disconnect timer."""
  287. if self._disconnect_timer:
  288. self._disconnect_timer.cancel()
  289. self._disconnect_timer = None
  290. async def _execute_forced_disconnect(self) -> None:
  291. """Execute forced disconnection."""
  292. self._cancel_disconnect_timer()
  293. _LOGGER.debug(
  294. "%s: Executing forced disconnect",
  295. self.name,
  296. )
  297. await self._execute_disconnect()
  298. async def _execute_timed_disconnect(self) -> None:
  299. """Execute timed disconnection."""
  300. _LOGGER.debug(
  301. "%s: Executing timed disconnect after timeout of %s",
  302. self.name,
  303. DISCONNECT_DELAY,
  304. )
  305. await self._execute_disconnect()
  306. async def _execute_disconnect(self) -> None:
  307. """Execute disconnection."""
  308. _LOGGER.debug("%s: Executing disconnect", self.name)
  309. async with self._connect_lock:
  310. await self._execute_disconnect_with_lock()
  311. async def _execute_disconnect_with_lock(self) -> None:
  312. """Execute disconnection while holding the lock."""
  313. assert self._connect_lock.locked(), "Lock not held"
  314. _LOGGER.debug("%s: Executing disconnect with lock", self.name)
  315. if self._disconnect_timer: # If the timer was reset, don't disconnect
  316. _LOGGER.debug("%s: Skipping disconnect as timer reset", self.name)
  317. return
  318. client = self._client
  319. self._expected_disconnect = True
  320. self._client = None
  321. self._read_char = None
  322. self._write_char = None
  323. if not client:
  324. _LOGGER.debug("%s: Already disconnected", self.name)
  325. return
  326. _LOGGER.debug("%s: Disconnecting", self.name)
  327. try:
  328. await client.disconnect()
  329. except BLEAK_RETRY_EXCEPTIONS as ex:
  330. _LOGGER.warning(
  331. "%s: Error disconnecting: %s; RSSI: %s",
  332. self.name,
  333. ex,
  334. self.rssi,
  335. )
  336. _LOGGER.debug("%s: Disconnect completed", self.name)
  337. async def _send_command_locked(self, key: str, command: bytes) -> bytes:
  338. """Send command to device and read response."""
  339. await self._ensure_connected()
  340. try:
  341. return await self._execute_command_locked(key, command)
  342. except BleakDBusError as ex:
  343. # Disconnect so we can reset state and try again
  344. await asyncio.sleep(DBUS_ERROR_BACKOFF_TIME)
  345. _LOGGER.debug(
  346. "%s: RSSI: %s; Backing off %ss; Disconnecting due to error: %s",
  347. self.name,
  348. self.rssi,
  349. DBUS_ERROR_BACKOFF_TIME,
  350. ex,
  351. )
  352. await self._execute_forced_disconnect()
  353. raise
  354. except BLEAK_RETRY_EXCEPTIONS as ex:
  355. # Disconnect so we can reset state and try again
  356. _LOGGER.debug(
  357. "%s: RSSI: %s; Disconnecting due to error: %s", self.name, self.rssi, ex
  358. )
  359. await self._execute_forced_disconnect()
  360. raise
  361. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  362. """Handle notification responses."""
  363. if self._notify_future and not self._notify_future.done():
  364. self._notify_future.set_result(data)
  365. return
  366. _LOGGER.debug("%s: Received unsolicited notification: %s", self.name, data)
  367. async def _start_notify(self) -> None:
  368. """Start notification."""
  369. _LOGGER.debug("%s: Subscribe to notifications; RSSI: %s", self.name, self.rssi)
  370. await self._client.start_notify(self._read_char, self._notification_handler)
  371. async def _execute_command_locked(self, key: str, command: bytes) -> bytes:
  372. """Execute command and read response."""
  373. assert self._client is not None
  374. assert self._read_char is not None
  375. assert self._write_char is not None
  376. self._notify_future = asyncio.Future()
  377. client = self._client
  378. _LOGGER.debug("%s: Sending command: %s", self.name, key)
  379. await client.write_gatt_char(self._write_char, command, False)
  380. async with async_timeout.timeout(5):
  381. notify_msg = await self._notify_future
  382. _LOGGER.debug("%s: Notification received: %s", self.name, notify_msg.hex())
  383. self._notify_future = None
  384. if notify_msg == b"\x07":
  385. _LOGGER.error("Password required")
  386. elif notify_msg == b"\t":
  387. _LOGGER.error("Password incorrect")
  388. return notify_msg
  389. def get_address(self) -> str:
  390. """Return address of device."""
  391. return self._device.address
  392. def _override_state(self, state: dict[str, Any]) -> None:
  393. """Override device state."""
  394. if self._override_adv_data is None:
  395. self._override_adv_data = {}
  396. self._override_adv_data.update(state)
  397. self._update_parsed_data(state)
  398. def _get_adv_value(self, key: str) -> Any:
  399. """Return value from advertisement data."""
  400. if self._override_adv_data and key in self._override_adv_data:
  401. _LOGGER.debug(
  402. "%s: Using override value for %s: %s",
  403. self.name,
  404. key,
  405. self._override_adv_data[key],
  406. )
  407. return self._override_adv_data[key]
  408. if not self._sb_adv_data:
  409. return None
  410. return self._sb_adv_data.data["data"].get(key)
  411. def get_battery_percent(self) -> Any:
  412. """Return device battery level in percent."""
  413. return self._get_adv_value("battery")
  414. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  415. """Update device data from advertisement."""
  416. # Only accept advertisements if the data is not missing
  417. # if we already have an advertisement with data
  418. self._device = advertisement.device
  419. async def get_device_data(
  420. self, retry: int | None = None, interface: int | None = None
  421. ) -> SwitchBotAdvertisement | None:
  422. """Find switchbot devices and their advertisement data."""
  423. if retry is None:
  424. retry = self._retry_count
  425. if interface:
  426. _interface: int = interface
  427. else:
  428. _interface = int(self._interface.replace("hci", ""))
  429. _data = await GetSwitchbotDevices(interface=_interface).discover(
  430. retry=retry, scan_timeout=self._scan_timeout
  431. )
  432. if self._device.address in _data:
  433. self._sb_adv_data = _data[self._device.address]
  434. return self._sb_adv_data
  435. async def _get_basic_info(self) -> bytes | None:
  436. """Return basic info of device."""
  437. _data = await self._send_command(
  438. key=DEVICE_GET_BASIC_SETTINGS_KEY, retry=self._retry_count
  439. )
  440. if _data in (b"\x07", b"\x00"):
  441. _LOGGER.error("Unsuccessful, please try again")
  442. return None
  443. return _data
  444. def _fire_callbacks(self) -> None:
  445. """Fire callbacks."""
  446. _LOGGER.debug("%s: Fire callbacks", self.name)
  447. for callback in self._callbacks:
  448. callback()
  449. def subscribe(self, callback: Callable[[], None]) -> Callable[[], None]:
  450. """Subscribe to device notifications."""
  451. self._callbacks.append(callback)
  452. def _unsub() -> None:
  453. """Unsubscribe from device notifications."""
  454. self._callbacks.remove(callback)
  455. return _unsub
  456. async def update(self, interface: int | None = None) -> None:
  457. """Update position, battery percent and light level of device."""
  458. if info := await self.get_basic_info():
  459. self._last_full_update = time.monotonic()
  460. self._update_parsed_data(info)
  461. self._fire_callbacks()
  462. async def get_basic_info(self) -> dict[str, Any] | None:
  463. """Get device basic settings."""
  464. if not (_data := await self._get_basic_info()):
  465. return None
  466. return {
  467. "battery": _data[1],
  468. "firmware": _data[2] / 10.0,
  469. }
  470. def _check_command_result(
  471. self, result: bytes | None, index: int, values: set[int]
  472. ) -> bool:
  473. """Check command result."""
  474. if not result or len(result) - 1 < index:
  475. result_hex = result.hex() if result else "None"
  476. raise SwitchbotOperationError(
  477. f"{self.name}: Sending command failed (result={result_hex} index={index} expected={values} rssi={self.rssi})"
  478. )
  479. return result[index] in values
  480. def _update_parsed_data(self, new_data: dict[str, Any]) -> bool:
  481. """Update data.
  482. Returns true if data has changed and False if not.
  483. """
  484. if not self._sb_adv_data:
  485. _LOGGER.exception("No advertisement data to update")
  486. return
  487. old_data = self._sb_adv_data.data.get("data") or {}
  488. merged_data = _merge_data(old_data, new_data)
  489. if merged_data == old_data:
  490. return False
  491. self._set_parsed_data(self._sb_adv_data, merged_data)
  492. return True
  493. def _set_parsed_data(
  494. self, advertisement: SwitchBotAdvertisement, data: dict[str, Any]
  495. ) -> None:
  496. """Set data."""
  497. self._sb_adv_data = replace(
  498. advertisement, data=self._sb_adv_data.data | {"data": data}
  499. )
  500. def _set_advertisement_data(self, advertisement: SwitchBotAdvertisement) -> None:
  501. """Set advertisement data."""
  502. new_data = advertisement.data.get("data") or {}
  503. if advertisement.active:
  504. # If we are getting active data, we can assume we are
  505. # getting active scans and we do not need to poll
  506. self._last_full_update = time.monotonic()
  507. if not self._sb_adv_data:
  508. self._sb_adv_data = advertisement
  509. elif new_data:
  510. self._update_parsed_data(new_data)
  511. self._override_adv_data = None
  512. def switch_mode(self) -> bool | None:
  513. """Return true or false from cache."""
  514. # To get actual position call update() first.
  515. return self._get_adv_value("switchMode")
  516. def poll_needed(self, seconds_since_last_poll: float | None) -> bool:
  517. """Return if device needs polling."""
  518. if (
  519. seconds_since_last_poll is not None
  520. and seconds_since_last_poll < PASSIVE_POLL_INTERVAL
  521. ):
  522. return False
  523. time_since_last_full_update = time.monotonic() - self._last_full_update
  524. if time_since_last_full_update < PASSIVE_POLL_INTERVAL:
  525. return False
  526. return True
  527. class SwitchbotDevice(SwitchbotBaseDevice):
  528. """Base Representation of a Switchbot Device.
  529. This base class consumes the advertisement data during connection. If the device
  530. sends stale advertisement data while connected, use
  531. SwitchbotDeviceOverrideStateDuringConnection instead.
  532. """
  533. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  534. """Update device data from advertisement."""
  535. super().update_from_advertisement(advertisement)
  536. self._set_advertisement_data(advertisement)
  537. class SwitchbotDeviceOverrideStateDuringConnection(SwitchbotBaseDevice):
  538. """Base Representation of a Switchbot Device.
  539. This base class ignores the advertisement data during connection and uses the
  540. data from the device instead.
  541. """
  542. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  543. super().update_from_advertisement(advertisement)
  544. if self._client and self._client.is_connected:
  545. # We do not consume the advertisement data if we are connected
  546. # to the device. This is because the advertisement data is not
  547. # updated when the device is connected for some devices.
  548. _LOGGER.debug("%s: Ignore advertisement data during connection", self.name)
  549. return
  550. self._set_advertisement_data(advertisement)
  551. class SwitchbotSequenceDevice(SwitchbotDevice):
  552. """A Switchbot sequence device.
  553. This class must not use SwitchbotDeviceOverrideStateDuringConnection because
  554. it needs to know when the sequence_number has changed.
  555. """
  556. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  557. """Update device data from advertisement."""
  558. current_state = self._get_adv_value("sequence_number")
  559. super().update_from_advertisement(advertisement)
  560. new_state = self._get_adv_value("sequence_number")
  561. _LOGGER.debug(
  562. "%s: update advertisement: %s (seq before: %s) (seq after: %s)",
  563. self.name,
  564. advertisement,
  565. current_state,
  566. new_state,
  567. )
  568. if current_state != new_state:
  569. asyncio.ensure_future(self.update())