device.py 47 KB

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