device.py 55 KB

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