device.py 32 KB

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