1
0

device.py 25 KB

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