device.py 36 KB

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