1
0

device.py 48 KB

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