1
0

device.py 55 KB

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