device.py 32 KB

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