device.py 34 KB

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