device.py 25 KB

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