device.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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 ..adv_parser import populate_model_to_mac_cache
  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. ColorMode, # noqa: F401
  29. SwitchbotAccountConnectionError,
  30. SwitchbotApiError,
  31. SwitchbotAuthenticationError,
  32. SwitchbotModel,
  33. )
  34. from ..discovery import GetSwitchbotDevices
  35. from ..helpers import create_background_task
  36. from ..models import SwitchBotAdvertisement
  37. from ..utils import format_mac_upper
  38. _LOGGER = logging.getLogger(__name__)
  39. def _extract_region(userinfo: dict[str, Any]) -> str:
  40. """Extract region from user info, defaulting to 'us'."""
  41. if "botRegion" in userinfo and userinfo["botRegion"] != "":
  42. return userinfo["botRegion"]
  43. return "us"
  44. # Mapping from API model names to SwitchbotModel enum values
  45. API_MODEL_TO_ENUM: dict[str, SwitchbotModel] = {
  46. "WoHand": SwitchbotModel.BOT,
  47. "WoCurtain": SwitchbotModel.CURTAIN,
  48. "WoHumi": SwitchbotModel.HUMIDIFIER,
  49. "WoPlug": SwitchbotModel.PLUG_MINI,
  50. "WoPlugUS": SwitchbotModel.PLUG_MINI,
  51. "WoContact": SwitchbotModel.CONTACT_SENSOR,
  52. "WoStrip": SwitchbotModel.LIGHT_STRIP,
  53. "WoSensorTH": SwitchbotModel.METER,
  54. "WoMeter": SwitchbotModel.METER,
  55. "WoMeterPlus": SwitchbotModel.METER_PRO,
  56. "WoPresence": SwitchbotModel.MOTION_SENSOR,
  57. "WoBulb": SwitchbotModel.COLOR_BULB,
  58. "WoCeiling": SwitchbotModel.CEILING_LIGHT,
  59. "WoLock": SwitchbotModel.LOCK,
  60. "WoBlindTilt": SwitchbotModel.BLIND_TILT,
  61. "WoIOSensor": SwitchbotModel.IO_METER, # Outdoor Meter
  62. "WoButton": SwitchbotModel.REMOTE, # Remote button
  63. "WoLinkMini": SwitchbotModel.HUBMINI_MATTER, # Hub Mini
  64. "W1083002": SwitchbotModel.RELAY_SWITCH_1, # Relay Switch 1
  65. "W1079000": SwitchbotModel.METER_PRO, # Meter Pro (another variant)
  66. "W1102001": SwitchbotModel.STRIP_LIGHT_3, # RGBWW Strip Light 3
  67. "W1106000": SwitchbotModel.S20_VACUUM,
  68. "W1101000": SwitchbotModel.PRESENCE_SENSOR,
  69. }
  70. REQ_HEADER = "570f"
  71. # Keys common to all device types
  72. DEVICE_GET_BASIC_SETTINGS_KEY = "5702"
  73. DEVICE_SET_MODE_KEY = "5703"
  74. DEVICE_SET_EXTENDED_KEY = REQ_HEADER
  75. COMMAND_GET_CK_IV = f"{REQ_HEADER}2103"
  76. # Base key when encryption is set
  77. KEY_PASSWORD_PREFIX = "571"
  78. DBUS_ERROR_BACKOFF_TIME = 0.25
  79. # How long to hold the connection
  80. # to wait for additional commands for
  81. # disconnecting the device.
  82. DISCONNECT_DELAY = 8.5
  83. # If the scanner is in passive mode, we
  84. # need to poll the device to get the
  85. # battery and a few rarely updating
  86. # values.
  87. PASSIVE_POLL_INTERVAL = 60 * 60 * 24
  88. class CharacteristicMissingError(Exception):
  89. """Raised when a characteristic is missing."""
  90. class SwitchbotOperationError(Exception):
  91. """Raised when an operation fails."""
  92. def _sb_uuid(comms_type: str = "service") -> UUID | str:
  93. """Return Switchbot UUID."""
  94. _uuid = {"tx": "002", "rx": "003", "service": "d00"}
  95. if comms_type in _uuid:
  96. return UUID(f"cba20{_uuid[comms_type]}-224d-11e6-9fb8-0002a5d5c51b")
  97. return "Incorrect type, choose between: tx, rx or service"
  98. READ_CHAR_UUID = _sb_uuid(comms_type="rx")
  99. WRITE_CHAR_UUID = _sb_uuid(comms_type="tx")
  100. WrapFuncType = TypeVar("WrapFuncType", bound=Callable[..., Any])
  101. def update_after_operation(func: WrapFuncType) -> WrapFuncType:
  102. """Define a wrapper to update after an operation."""
  103. async def _async_update_after_operation_wrap(
  104. self: SwitchbotBaseDevice, *args: Any, **kwargs: Any
  105. ) -> None:
  106. ret = await func(self, *args, **kwargs)
  107. await self.update()
  108. return ret
  109. return cast(WrapFuncType, _async_update_after_operation_wrap)
  110. def _merge_data(old_data: dict[str, Any], new_data: dict[str, Any]) -> dict[str, Any]:
  111. """Merge data but only add None keys if they are missing."""
  112. merged = old_data.copy()
  113. for key, value in new_data.items():
  114. if isinstance(value, dict) and isinstance(old_data.get(key), dict):
  115. merged[key] = _merge_data(old_data[key], value)
  116. elif value is not None or key not in old_data:
  117. merged[key] = value
  118. return merged
  119. def _handle_timeout(fut: asyncio.Future[None]) -> None:
  120. """Handle a timeout."""
  121. if not fut.done():
  122. fut.set_exception(asyncio.TimeoutError)
  123. class SwitchbotBaseDevice:
  124. """Base Representation of a Switchbot Device."""
  125. _turn_on_command: str | None = None
  126. _turn_off_command: str | None = None
  127. _open_command: str | None = None
  128. _close_command: str | None = None
  129. _press_command: str | None = None
  130. def __init__(
  131. self,
  132. device: BLEDevice,
  133. password: str | None = None,
  134. interface: int = 0,
  135. **kwargs: Any,
  136. ) -> None:
  137. """Switchbot base class constructor."""
  138. self._interface = f"hci{interface}"
  139. self._device = device
  140. self._sb_adv_data: SwitchBotAdvertisement | None = None
  141. self._override_adv_data: dict[str, Any] | None = None
  142. self._scan_timeout: int = kwargs.pop("scan_timeout", DEFAULT_SCAN_TIMEOUT)
  143. self._retry_count: int = kwargs.pop("retry_count", DEFAULT_RETRY_COUNT)
  144. self._connect_lock = asyncio.Lock()
  145. self._operation_lock = asyncio.Lock()
  146. if password is None or password == "":
  147. self._password_encoded = None
  148. else:
  149. self._password_encoded = "%08x" % (
  150. binascii.crc32(password.encode("ascii")) & 0xFFFFFFFF
  151. )
  152. self._client: BleakClientWithServiceCache | None = None
  153. self._read_char: BleakGATTCharacteristic | None = None
  154. self._write_char: BleakGATTCharacteristic | None = None
  155. self._disconnect_timer: asyncio.TimerHandle | None = None
  156. self._expected_disconnect = False
  157. self.loop = asyncio.get_event_loop()
  158. self._callbacks: list[Callable[[], None]] = []
  159. self._notify_future: asyncio.Future[bytearray] | None = None
  160. self._last_full_update: float = -PASSIVE_POLL_INTERVAL
  161. self._timed_disconnect_task: asyncio.Task[None] | None = None
  162. @classmethod
  163. async def _async_get_user_info(
  164. cls,
  165. session: aiohttp.ClientSession,
  166. auth_headers: dict[str, str],
  167. ) -> dict[str, Any]:
  168. try:
  169. return await cls.api_request(
  170. session, "account", "account/api/v1/user/userinfo", {}, auth_headers
  171. )
  172. except Exception as err:
  173. raise SwitchbotAccountConnectionError(
  174. f"Failed to retrieve SwitchBot Account user details: {err}"
  175. ) from err
  176. @classmethod
  177. async def _get_auth_result(
  178. cls,
  179. session: aiohttp.ClientSession,
  180. username: str,
  181. password: str,
  182. ) -> dict[str, Any]:
  183. """Authenticate with SwitchBot API."""
  184. try:
  185. return await cls.api_request(
  186. session,
  187. "account",
  188. "account/api/v1/user/login",
  189. {
  190. "clientId": SWITCHBOT_APP_CLIENT_ID,
  191. "username": username,
  192. "password": password,
  193. "grantType": "password",
  194. "verifyCode": "",
  195. },
  196. )
  197. except Exception as err:
  198. raise SwitchbotAuthenticationError(f"Authentication failed: {err}") from err
  199. @classmethod
  200. async def get_devices(
  201. cls,
  202. session: aiohttp.ClientSession,
  203. username: str,
  204. password: str,
  205. ) -> dict[str, SwitchbotModel]:
  206. """Get devices from SwitchBot API and return formatted MAC to model mapping."""
  207. try:
  208. auth_result = await cls._get_auth_result(session, username, password)
  209. auth_headers = {"authorization": auth_result["access_token"]}
  210. except Exception as err:
  211. raise SwitchbotAuthenticationError(f"Authentication failed: {err}") from err
  212. userinfo = await cls._async_get_user_info(session, auth_headers)
  213. region = _extract_region(userinfo)
  214. try:
  215. device_info = await cls.api_request(
  216. session,
  217. f"wonderlabs.{region}",
  218. "wonder/device/v3/getdevice",
  219. {
  220. "required_type": "All",
  221. },
  222. auth_headers,
  223. )
  224. except Exception as err:
  225. raise SwitchbotAccountConnectionError(
  226. f"Failed to retrieve devices from SwitchBot Account: {err}"
  227. ) from err
  228. items: list[dict[str, Any]] = device_info["Items"]
  229. mac_to_model: dict[str, SwitchbotModel] = {}
  230. for item in items:
  231. if "device_mac" not in item:
  232. continue
  233. if (
  234. "device_detail" not in item
  235. or "device_type" not in item["device_detail"]
  236. ):
  237. continue
  238. mac = item["device_mac"]
  239. model_name = item["device_detail"]["device_type"]
  240. # Format MAC to uppercase with colons
  241. formatted_mac = format_mac_upper(mac)
  242. # Map API model name to SwitchbotModel enum if possible
  243. if model_name in API_MODEL_TO_ENUM:
  244. model = API_MODEL_TO_ENUM[model_name]
  245. mac_to_model[formatted_mac] = model
  246. # Populate the cache
  247. populate_model_to_mac_cache(formatted_mac, model)
  248. else:
  249. # Log the full item payload for unknown models
  250. _LOGGER.debug(
  251. "Unknown model %s for device %s, full item: %s",
  252. model_name,
  253. formatted_mac,
  254. item,
  255. )
  256. return mac_to_model
  257. @classmethod
  258. async def api_request(
  259. cls,
  260. session: aiohttp.ClientSession,
  261. subdomain: str,
  262. path: str,
  263. data: dict | None = None,
  264. headers: dict | None = None,
  265. ) -> dict:
  266. url = f"https://{subdomain}.{SWITCHBOT_APP_API_BASE_URL}/{path}"
  267. async with session.post(
  268. url,
  269. json=data,
  270. headers=headers,
  271. timeout=aiohttp.ClientTimeout(total=10),
  272. ) as result:
  273. if result.status > 299:
  274. raise SwitchbotApiError(
  275. f"Unexpected status code returned by SwitchBot API: {result.status}"
  276. )
  277. response = await result.json()
  278. if response["statusCode"] != 100:
  279. raise SwitchbotApiError(
  280. f"{response['message']}, status code: {response['statusCode']}"
  281. )
  282. return response["body"]
  283. def advertisement_changed(self, advertisement: SwitchBotAdvertisement) -> bool:
  284. """Check if the advertisement has changed."""
  285. return bool(
  286. not self._sb_adv_data
  287. or ble_device_has_changed(self._sb_adv_data.device, advertisement.device)
  288. or advertisement.data != self._sb_adv_data.data
  289. )
  290. def _commandkey(self, key: str) -> str:
  291. """Add password to key if set."""
  292. if self._password_encoded is None:
  293. return key
  294. key_action = key[3]
  295. key_suffix = key[4:]
  296. return KEY_PASSWORD_PREFIX + key_action + self._password_encoded + key_suffix
  297. async def _send_command_locked_with_retry(
  298. self, key: str, command: bytes, retry: int, max_attempts: int
  299. ) -> bytes | None:
  300. for attempt in range(max_attempts):
  301. try:
  302. return await self._send_command_locked(key, command)
  303. except BleakNotFoundError:
  304. _LOGGER.error(
  305. "%s: device not found, no longer in range, or poor RSSI: %s",
  306. self.name,
  307. self.rssi,
  308. exc_info=True,
  309. )
  310. raise
  311. except CharacteristicMissingError as ex:
  312. if attempt == retry:
  313. _LOGGER.error(
  314. "%s: characteristic missing: %s; Stopping trying; RSSI: %s",
  315. self.name,
  316. ex,
  317. self.rssi,
  318. exc_info=True,
  319. )
  320. raise
  321. _LOGGER.debug(
  322. "%s: characteristic missing: %s; RSSI: %s",
  323. self.name,
  324. ex,
  325. self.rssi,
  326. exc_info=True,
  327. )
  328. except BLEAK_RETRY_EXCEPTIONS:
  329. if attempt == retry:
  330. _LOGGER.error(
  331. "%s: communication failed; Stopping trying; RSSI: %s",
  332. self.name,
  333. self.rssi,
  334. exc_info=True,
  335. )
  336. raise
  337. _LOGGER.debug(
  338. "%s: communication failed with:", self.name, exc_info=True
  339. )
  340. raise RuntimeError("Unreachable")
  341. async def _send_command(self, key: str, retry: int | None = None) -> bytes | None:
  342. """Send command to device and read response."""
  343. if retry is None:
  344. retry = self._retry_count
  345. command = bytearray.fromhex(self._commandkey(key))
  346. _LOGGER.debug("%s: Scheduling command %s", self.name, command.hex())
  347. max_attempts = retry + 1
  348. if self._operation_lock.locked():
  349. _LOGGER.debug(
  350. "%s: Operation already in progress, waiting for it to complete; RSSI: %s",
  351. self.name,
  352. self.rssi,
  353. )
  354. async with self._operation_lock:
  355. return await self._send_command_locked_with_retry(
  356. key, command, retry, max_attempts
  357. )
  358. @property
  359. def name(self) -> str:
  360. """Return device name."""
  361. return f"{self._device.name} ({self._device.address})"
  362. @property
  363. def data(self) -> dict[str, Any]:
  364. """Return device data."""
  365. if self._sb_adv_data:
  366. return self._sb_adv_data.data
  367. return {}
  368. @property
  369. def parsed_data(self) -> dict[str, Any]:
  370. """Return parsed device data."""
  371. return self.data.get("data") or {}
  372. @property
  373. def rssi(self) -> int:
  374. """Return RSSI of device."""
  375. if self._sb_adv_data:
  376. return self._sb_adv_data.rssi
  377. return -127
  378. async def _ensure_connected(self):
  379. """Ensure connection to device is established."""
  380. if self._connect_lock.locked():
  381. _LOGGER.debug(
  382. "%s: Connection already in progress, waiting for it to complete; RSSI: %s",
  383. self.name,
  384. self.rssi,
  385. )
  386. if self._client and self._client.is_connected:
  387. _LOGGER.debug(
  388. "%s: Already connected before obtaining lock, resetting timer; RSSI: %s",
  389. self.name,
  390. self.rssi,
  391. )
  392. self._reset_disconnect_timer()
  393. return
  394. async with self._connect_lock:
  395. # Check again while holding the lock
  396. if self._client and self._client.is_connected:
  397. _LOGGER.debug(
  398. "%s: Already connected after obtaining lock, resetting timer; RSSI: %s",
  399. self.name,
  400. self.rssi,
  401. )
  402. self._reset_disconnect_timer()
  403. return
  404. _LOGGER.debug("%s: Connecting; RSSI: %s", self.name, self.rssi)
  405. client: BleakClientWithServiceCache = await establish_connection(
  406. BleakClientWithServiceCache,
  407. self._device,
  408. self.name,
  409. self._disconnected,
  410. use_services_cache=True,
  411. ble_device_callback=lambda: self._device,
  412. )
  413. _LOGGER.debug("%s: Connected; RSSI: %s", self.name, self.rssi)
  414. self._client = client
  415. try:
  416. self._resolve_characteristics(client.services)
  417. except CharacteristicMissingError as ex:
  418. _LOGGER.debug(
  419. "%s: characteristic missing, clearing cache: %s; RSSI: %s",
  420. self.name,
  421. ex,
  422. self.rssi,
  423. exc_info=True,
  424. )
  425. await client.clear_cache()
  426. self._cancel_disconnect_timer()
  427. await self._execute_disconnect_with_lock()
  428. raise
  429. _LOGGER.debug(
  430. "%s: Starting notify and disconnect timer; RSSI: %s",
  431. self.name,
  432. self.rssi,
  433. )
  434. self._reset_disconnect_timer()
  435. await self._start_notify()
  436. def _resolve_characteristics(self, services: BleakGATTServiceCollection) -> None:
  437. """Resolve characteristics."""
  438. self._read_char = services.get_characteristic(READ_CHAR_UUID)
  439. if not self._read_char:
  440. raise CharacteristicMissingError(READ_CHAR_UUID)
  441. self._write_char = services.get_characteristic(WRITE_CHAR_UUID)
  442. if not self._write_char:
  443. raise CharacteristicMissingError(WRITE_CHAR_UUID)
  444. def _reset_disconnect_timer(self):
  445. """Reset disconnect timer."""
  446. self._cancel_disconnect_timer()
  447. self._expected_disconnect = False
  448. self._disconnect_timer = self.loop.call_later(
  449. DISCONNECT_DELAY, self._disconnect_from_timer
  450. )
  451. def _disconnected(self, client: BleakClientWithServiceCache) -> None:
  452. """Disconnected callback."""
  453. if self._expected_disconnect:
  454. _LOGGER.debug(
  455. "%s: Disconnected from device; RSSI: %s", self.name, self.rssi
  456. )
  457. return
  458. _LOGGER.warning(
  459. "%s: Device unexpectedly disconnected; RSSI: %s",
  460. self.name,
  461. self.rssi,
  462. )
  463. self._cancel_disconnect_timer()
  464. def _disconnect_from_timer(self):
  465. """Disconnect from device."""
  466. if self._operation_lock.locked() and self._client.is_connected:
  467. _LOGGER.debug(
  468. "%s: Operation in progress, resetting disconnect timer; RSSI: %s",
  469. self.name,
  470. self.rssi,
  471. )
  472. self._reset_disconnect_timer()
  473. return
  474. self._cancel_disconnect_timer()
  475. self._timed_disconnect_task = asyncio.create_task(
  476. self._execute_timed_disconnect()
  477. )
  478. def _cancel_disconnect_timer(self):
  479. """Cancel disconnect timer."""
  480. if self._disconnect_timer:
  481. self._disconnect_timer.cancel()
  482. self._disconnect_timer = None
  483. async def _execute_forced_disconnect(self) -> None:
  484. """Execute forced disconnection."""
  485. self._cancel_disconnect_timer()
  486. _LOGGER.debug(
  487. "%s: Executing forced disconnect",
  488. self.name,
  489. )
  490. await self._execute_disconnect()
  491. async def _execute_timed_disconnect(self) -> None:
  492. """Execute timed disconnection."""
  493. _LOGGER.debug(
  494. "%s: Executing timed disconnect after timeout of %s",
  495. self.name,
  496. DISCONNECT_DELAY,
  497. )
  498. await self._execute_disconnect()
  499. async def _execute_disconnect(self) -> None:
  500. """Execute disconnection."""
  501. _LOGGER.debug("%s: Executing disconnect", self.name)
  502. async with self._connect_lock:
  503. await self._execute_disconnect_with_lock()
  504. async def _execute_disconnect_with_lock(self) -> None:
  505. """Execute disconnection while holding the lock."""
  506. assert self._connect_lock.locked(), "Lock not held"
  507. _LOGGER.debug("%s: Executing disconnect with lock", self.name)
  508. if self._disconnect_timer: # If the timer was reset, don't disconnect
  509. _LOGGER.debug("%s: Skipping disconnect as timer reset", self.name)
  510. return
  511. client = self._client
  512. self._expected_disconnect = True
  513. self._client = None
  514. self._read_char = None
  515. self._write_char = None
  516. if not client:
  517. _LOGGER.debug("%s: Already disconnected", self.name)
  518. return
  519. _LOGGER.debug("%s: Disconnecting", self.name)
  520. try:
  521. await client.disconnect()
  522. except BLEAK_RETRY_EXCEPTIONS as ex:
  523. _LOGGER.warning(
  524. "%s: Error disconnecting: %s; RSSI: %s",
  525. self.name,
  526. ex,
  527. self.rssi,
  528. )
  529. else:
  530. _LOGGER.debug("%s: Disconnect completed successfully", self.name)
  531. async def _send_command_locked(self, key: str, command: bytes) -> bytes:
  532. """Send command to device and read response."""
  533. await self._ensure_connected()
  534. try:
  535. return await self._execute_command_locked(key, command)
  536. except BleakDBusError as ex:
  537. # Disconnect so we can reset state and try again
  538. await asyncio.sleep(DBUS_ERROR_BACKOFF_TIME)
  539. _LOGGER.debug(
  540. "%s: RSSI: %s; Backing off %ss; Disconnecting due to error: %s",
  541. self.name,
  542. self.rssi,
  543. DBUS_ERROR_BACKOFF_TIME,
  544. ex,
  545. )
  546. await self._execute_forced_disconnect()
  547. raise
  548. except BLEAK_RETRY_EXCEPTIONS as ex:
  549. # Disconnect so we can reset state and try again
  550. _LOGGER.debug(
  551. "%s: RSSI: %s; Disconnecting due to error: %s", self.name, self.rssi, ex
  552. )
  553. await self._execute_forced_disconnect()
  554. raise
  555. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  556. """Handle notification responses."""
  557. if self._notify_future and not self._notify_future.done():
  558. self._notify_future.set_result(data)
  559. return
  560. _LOGGER.debug("%s: Received unsolicited notification: %s", self.name, data)
  561. async def _start_notify(self) -> None:
  562. """Start notification."""
  563. _LOGGER.debug("%s: Subscribe to notifications; RSSI: %s", self.name, self.rssi)
  564. await self._client.start_notify(self._read_char, self._notification_handler)
  565. async def _execute_command_locked(self, key: str, command: bytes) -> bytes:
  566. """Execute command and read response."""
  567. assert self._client is not None
  568. assert self._read_char is not None
  569. assert self._write_char is not None
  570. self._notify_future = self.loop.create_future()
  571. client = self._client
  572. _LOGGER.debug("%s: Sending command: %s", self.name, key)
  573. await client.write_gatt_char(self._write_char, command, False)
  574. timeout = 5
  575. timeout_handle = self.loop.call_at(
  576. self.loop.time() + timeout, _handle_timeout, self._notify_future
  577. )
  578. timeout_expired = False
  579. try:
  580. notify_msg = await self._notify_future
  581. except TimeoutError:
  582. timeout_expired = True
  583. raise
  584. finally:
  585. if not timeout_expired:
  586. timeout_handle.cancel()
  587. self._notify_future = None
  588. _LOGGER.debug("%s: Notification received: %s", self.name, notify_msg.hex())
  589. if notify_msg == b"\x07":
  590. _LOGGER.error("Password required")
  591. elif notify_msg == b"\t":
  592. _LOGGER.error("Password incorrect")
  593. return notify_msg
  594. def get_address(self) -> str:
  595. """Return address of device."""
  596. return self._device.address
  597. def _override_state(self, state: dict[str, Any]) -> None:
  598. """Override device state."""
  599. if self._override_adv_data is None:
  600. self._override_adv_data = {}
  601. self._override_adv_data.update(state)
  602. self._update_parsed_data(state)
  603. def _get_adv_value(self, key: str, channel: int | None = None) -> Any:
  604. """Return value from advertisement data."""
  605. if self._override_adv_data and key in self._override_adv_data:
  606. _LOGGER.debug(
  607. "%s: Using override value for %s: %s",
  608. self.name,
  609. key,
  610. self._override_adv_data[key],
  611. )
  612. return self._override_adv_data[key]
  613. if not self._sb_adv_data:
  614. return None
  615. if channel is not None:
  616. return self._sb_adv_data.data["data"].get(channel, {}).get(key)
  617. return self._sb_adv_data.data["data"].get(key)
  618. def get_battery_percent(self) -> Any:
  619. """Return device battery level in percent."""
  620. return self._get_adv_value("battery")
  621. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  622. """Update device data from advertisement."""
  623. # Only accept advertisements if the data is not missing
  624. # if we already have an advertisement with data
  625. self._device = advertisement.device
  626. async def get_device_data(
  627. self, retry: int | None = None, interface: int | None = None
  628. ) -> SwitchBotAdvertisement | None:
  629. """Find switchbot devices and their advertisement data."""
  630. if retry is None:
  631. retry = self._retry_count
  632. if interface:
  633. _interface: int = interface
  634. else:
  635. _interface = int(self._interface.replace("hci", ""))
  636. _data = await GetSwitchbotDevices(interface=_interface).discover(
  637. retry=retry, scan_timeout=self._scan_timeout
  638. )
  639. if self._device.address in _data:
  640. self._sb_adv_data = _data[self._device.address]
  641. return self._sb_adv_data
  642. async def _get_basic_info(
  643. self, cmd: str = DEVICE_GET_BASIC_SETTINGS_KEY
  644. ) -> bytes | None:
  645. """Return basic info of device."""
  646. _data = await self._send_command(key=cmd, retry=self._retry_count)
  647. if _data in (b"\x07", b"\x00"):
  648. _LOGGER.error("Unsuccessful, please try again")
  649. return None
  650. return _data
  651. def _fire_callbacks(self) -> None:
  652. """Fire callbacks."""
  653. _LOGGER.debug("%s: Fire callbacks", self.name)
  654. for callback in self._callbacks:
  655. callback()
  656. def subscribe(self, callback: Callable[[], None]) -> Callable[[], None]:
  657. """Subscribe to device notifications."""
  658. self._callbacks.append(callback)
  659. def _unsub() -> None:
  660. """Unsubscribe from device notifications."""
  661. self._callbacks.remove(callback)
  662. return _unsub
  663. async def update(self, interface: int | None = None) -> None:
  664. """Update position, battery percent and light level of device."""
  665. if info := await self.get_basic_info():
  666. self._last_full_update = time.monotonic()
  667. self._update_parsed_data(info)
  668. self._fire_callbacks()
  669. async def get_basic_info(self) -> dict[str, Any] | None:
  670. """Get device basic settings."""
  671. if not (_data := await self._get_basic_info()):
  672. return None
  673. return {
  674. "battery": _data[1],
  675. "firmware": _data[2] / 10.0,
  676. }
  677. def _check_command_result(
  678. self, result: bytes | None, index: int, values: set[int]
  679. ) -> bool:
  680. """Check command result."""
  681. if not result or len(result) - 1 < index:
  682. result_hex = result.hex() if result else "None"
  683. raise SwitchbotOperationError(
  684. f"{self.name}: Sending command failed (result={result_hex} index={index} expected={values} rssi={self.rssi})"
  685. )
  686. return result[index] in values
  687. def _update_parsed_data(self, new_data: dict[str, Any]) -> bool:
  688. """
  689. Update data.
  690. Returns true if data has changed and False if not.
  691. """
  692. if not self._sb_adv_data:
  693. _LOGGER.exception("No advertisement data to update")
  694. return None
  695. old_data = self._sb_adv_data.data.get("data") or {}
  696. merged_data = _merge_data(old_data, new_data)
  697. if merged_data == old_data:
  698. return False
  699. self._set_parsed_data(self._sb_adv_data, merged_data)
  700. return True
  701. def _set_parsed_data(
  702. self, advertisement: SwitchBotAdvertisement, data: dict[str, Any]
  703. ) -> None:
  704. """Set data."""
  705. self._sb_adv_data = replace(
  706. advertisement, data=self._sb_adv_data.data | {"data": data}
  707. )
  708. def _set_advertisement_data(self, advertisement: SwitchBotAdvertisement) -> None:
  709. """Set advertisement data."""
  710. new_data = advertisement.data.get("data") or {}
  711. if advertisement.active:
  712. # If we are getting active data, we can assume we are
  713. # getting active scans and we do not need to poll
  714. self._last_full_update = time.monotonic()
  715. if not self._sb_adv_data:
  716. self._sb_adv_data = advertisement
  717. elif new_data:
  718. self._update_parsed_data(new_data)
  719. self._override_adv_data = None
  720. def switch_mode(self) -> bool | None:
  721. """Return true or false from cache."""
  722. # To get actual position call update() first.
  723. return self._get_adv_value("switchMode")
  724. def poll_needed(self, seconds_since_last_poll: float | None) -> bool:
  725. """Return if device needs polling."""
  726. if (
  727. seconds_since_last_poll is not None
  728. and seconds_since_last_poll < PASSIVE_POLL_INTERVAL
  729. ):
  730. return False
  731. time_since_last_full_update = time.monotonic() - self._last_full_update
  732. return not time_since_last_full_update < PASSIVE_POLL_INTERVAL
  733. def _check_function_support(self, cmd: str | None = None) -> None:
  734. """Check if the command is supported by the device model."""
  735. if not cmd:
  736. raise SwitchbotOperationError(
  737. f"Current device {self._device.address} does not support this functionality"
  738. )
  739. @update_after_operation
  740. async def turn_on(self) -> bool:
  741. """Turn device on."""
  742. self._check_function_support(self._turn_on_command)
  743. result = await self._send_command(self._turn_on_command)
  744. return self._check_command_result(result, 0, {1})
  745. @update_after_operation
  746. async def turn_off(self) -> bool:
  747. """Turn device off."""
  748. self._check_function_support(self._turn_off_command)
  749. result = await self._send_command(self._turn_off_command)
  750. return self._check_command_result(result, 0, {1})
  751. @update_after_operation
  752. async def open(self) -> bool:
  753. """Open the device."""
  754. self._check_function_support(self._open_command)
  755. result = await self._send_command(self._open_command)
  756. return self._check_command_result(result, 0, {1})
  757. @update_after_operation
  758. async def close(self) -> bool:
  759. """Close the device."""
  760. self._check_function_support(self._close_command)
  761. result = await self._send_command(self._close_command)
  762. return self._check_command_result(result, 0, {1})
  763. @update_after_operation
  764. async def press(self) -> bool:
  765. """Press the device."""
  766. self._check_function_support(self._press_command)
  767. result = await self._send_command(self._press_command)
  768. return self._check_command_result(result, 0, {1})
  769. class SwitchbotDevice(SwitchbotBaseDevice):
  770. """
  771. Base Representation of a Switchbot Device.
  772. This base class consumes the advertisement data during connection. If the device
  773. sends stale advertisement data while connected, use
  774. SwitchbotDeviceOverrideStateDuringConnection instead.
  775. """
  776. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  777. """Update device data from advertisement."""
  778. super().update_from_advertisement(advertisement)
  779. self._set_advertisement_data(advertisement)
  780. class SwitchbotEncryptedDevice(SwitchbotDevice):
  781. """A Switchbot device that uses encryption."""
  782. def __init__(
  783. self,
  784. device: BLEDevice,
  785. key_id: str,
  786. encryption_key: str,
  787. model: SwitchbotModel,
  788. interface: int = 0,
  789. **kwargs: Any,
  790. ) -> None:
  791. """Switchbot base class constructor for encrypted devices."""
  792. if len(key_id) == 0:
  793. raise ValueError("key_id is missing")
  794. if len(key_id) != 2:
  795. raise ValueError("key_id is invalid")
  796. if len(encryption_key) == 0:
  797. raise ValueError("encryption_key is missing")
  798. if len(encryption_key) != 32:
  799. raise ValueError("encryption_key is invalid")
  800. self._key_id = key_id
  801. self._encryption_key = bytearray.fromhex(encryption_key)
  802. self._iv: bytes | None = None
  803. self._cipher: bytes | None = None
  804. super().__init__(device, None, interface, **kwargs)
  805. self._model = model
  806. # Old non-async method preserved for backwards compatibility
  807. @classmethod
  808. def retrieve_encryption_key(cls, device_mac: str, username: str, password: str):
  809. async def async_fn():
  810. async with aiohttp.ClientSession() as session:
  811. return await cls.async_retrieve_encryption_key(
  812. session, device_mac, username, password
  813. )
  814. return asyncio.run(async_fn())
  815. @classmethod
  816. async def async_retrieve_encryption_key(
  817. cls,
  818. session: aiohttp.ClientSession,
  819. device_mac: str,
  820. username: str,
  821. password: str,
  822. ) -> dict:
  823. """Retrieve lock key from internal SwitchBot API."""
  824. device_mac = device_mac.replace(":", "").replace("-", "").upper()
  825. try:
  826. auth_result = await cls._get_auth_result(session, username, password)
  827. auth_headers = {"authorization": auth_result["access_token"]}
  828. except Exception as err:
  829. raise SwitchbotAuthenticationError(f"Authentication failed: {err}") from err
  830. userinfo = await cls._async_get_user_info(session, auth_headers)
  831. region = _extract_region(userinfo)
  832. try:
  833. device_info = await cls.api_request(
  834. session,
  835. f"wonderlabs.{region}",
  836. "wonder/keys/v1/communicate",
  837. {
  838. "device_mac": device_mac,
  839. "keyType": "user",
  840. },
  841. auth_headers,
  842. )
  843. return {
  844. "key_id": device_info["communicationKey"]["keyId"],
  845. "encryption_key": device_info["communicationKey"]["key"],
  846. }
  847. except Exception as err:
  848. raise SwitchbotAccountConnectionError(
  849. f"Failed to retrieve encryption key from SwitchBot Account: {err}"
  850. ) from err
  851. @classmethod
  852. async def verify_encryption_key(
  853. cls,
  854. device: BLEDevice,
  855. key_id: str,
  856. encryption_key: str,
  857. model: SwitchbotModel,
  858. **kwargs: Any,
  859. ) -> bool:
  860. try:
  861. switchbot_device = cls(
  862. device, key_id=key_id, encryption_key=encryption_key, model=model
  863. )
  864. except ValueError:
  865. return False
  866. try:
  867. info = await switchbot_device.get_basic_info()
  868. except SwitchbotOperationError:
  869. return False
  870. return info is not None
  871. async def _send_command(
  872. self, key: str, retry: int | None = None, encrypt: bool = True
  873. ) -> bytes | None:
  874. if not encrypt:
  875. return await super()._send_command(key[:2] + "000000" + key[2:], retry)
  876. if retry is None:
  877. retry = self._retry_count
  878. if self._operation_lock.locked():
  879. _LOGGER.debug(
  880. "%s: Operation already in progress, waiting for it to complete; RSSI: %s",
  881. self.name,
  882. self.rssi,
  883. )
  884. async with self._operation_lock:
  885. if not (result := await self._ensure_encryption_initialized()):
  886. _LOGGER.error("Failed to initialize encryption")
  887. return None
  888. encrypted = (
  889. key[:2] + self._key_id + self._iv[0:2].hex() + self._encrypt(key[2:])
  890. )
  891. command = bytearray.fromhex(self._commandkey(encrypted))
  892. _LOGGER.debug("%s: Scheduling command %s", self.name, command.hex())
  893. max_attempts = retry + 1
  894. result = await self._send_command_locked_with_retry(
  895. encrypted, command, retry, max_attempts
  896. )
  897. if result is None:
  898. return None
  899. return result[:1] + self._decrypt(result[4:])
  900. async def _ensure_encryption_initialized(self) -> bool:
  901. """Ensure encryption is initialized, must be called with operation lock held."""
  902. assert self._operation_lock.locked(), "Operation lock must be held"
  903. if self._iv is not None:
  904. return True
  905. _LOGGER.debug("%s: Initializing encryption", self.name)
  906. # Call parent's _send_command_locked_with_retry directly since we already hold the lock
  907. key = COMMAND_GET_CK_IV + self._key_id
  908. command = bytearray.fromhex(self._commandkey(key[:2] + "000000" + key[2:]))
  909. result = await self._send_command_locked_with_retry(
  910. key[:2] + "000000" + key[2:],
  911. command,
  912. self._retry_count,
  913. self._retry_count + 1,
  914. )
  915. if result is None:
  916. return False
  917. if ok := self._check_command_result(result, 0, {1}):
  918. self._iv = result[4:]
  919. self._cipher = None # Reset cipher when IV changes
  920. _LOGGER.debug("%s: Encryption initialized successfully", self.name)
  921. return ok
  922. async def _execute_disconnect(self) -> None:
  923. async with self._connect_lock:
  924. self._iv = None
  925. self._cipher = None
  926. await self._execute_disconnect_with_lock()
  927. def _get_cipher(self) -> Cipher:
  928. if self._cipher is None:
  929. if self._iv is None:
  930. raise RuntimeError("Cannot create cipher: IV is None")
  931. self._cipher = Cipher(
  932. algorithms.AES128(self._encryption_key), modes.CTR(self._iv)
  933. )
  934. return self._cipher
  935. def _encrypt(self, data: str) -> str:
  936. if len(data) == 0:
  937. return ""
  938. if self._iv is None:
  939. raise RuntimeError("Cannot encrypt: IV is None")
  940. encryptor = self._get_cipher().encryptor()
  941. return (encryptor.update(bytearray.fromhex(data)) + encryptor.finalize()).hex()
  942. def _decrypt(self, data: bytearray) -> bytes:
  943. if len(data) == 0:
  944. return b""
  945. if self._iv is None:
  946. if self._expected_disconnect:
  947. _LOGGER.debug(
  948. "%s: Cannot decrypt, IV is None during expected disconnect",
  949. self.name,
  950. )
  951. return b""
  952. raise RuntimeError("Cannot decrypt: IV is None")
  953. decryptor = self._get_cipher().decryptor()
  954. return decryptor.update(data) + decryptor.finalize()
  955. class SwitchbotDeviceOverrideStateDuringConnection(SwitchbotBaseDevice):
  956. """
  957. Base Representation of a Switchbot Device.
  958. This base class ignores the advertisement data during connection and uses the
  959. data from the device instead.
  960. """
  961. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  962. super().update_from_advertisement(advertisement)
  963. if self._client and self._client.is_connected:
  964. # We do not consume the advertisement data if we are connected
  965. # to the device. This is because the advertisement data is not
  966. # updated when the device is connected for some devices.
  967. _LOGGER.debug("%s: Ignore advertisement data during connection", self.name)
  968. return
  969. self._set_advertisement_data(advertisement)
  970. class SwitchbotSequenceDevice(SwitchbotDevice):
  971. """
  972. A Switchbot sequence device.
  973. This class must not use SwitchbotDeviceOverrideStateDuringConnection because
  974. it needs to know when the sequence_number has changed.
  975. """
  976. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  977. """Update device data from advertisement."""
  978. current_state = self._get_adv_value("sequence_number")
  979. super().update_from_advertisement(advertisement)
  980. new_state = self._get_adv_value("sequence_number")
  981. _LOGGER.debug(
  982. "%s: update advertisement: %s (seq before: %s) (seq after: %s)",
  983. self.name,
  984. advertisement,
  985. current_state,
  986. new_state,
  987. )
  988. if current_state != new_state:
  989. create_background_task(self.update())
  990. async def fetch_cloud_devices(
  991. session: aiohttp.ClientSession,
  992. username: str,
  993. password: str,
  994. ) -> dict[str, SwitchbotModel]:
  995. """Fetch devices from SwitchBot API and return MAC to model mapping."""
  996. # Get devices from the API (which also populates the cache)
  997. return await SwitchbotBaseDevice.get_devices(session, username, password)