device.py 48 KB

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