device.py 55 KB

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