1
0

device.py 32 KB

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