device.py 35 KB

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