device.py 30 KB

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