device.py 35 KB

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