lock.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. """Library to handle connection with Switchbot Lock."""
  2. from __future__ import annotations
  3. import logging
  4. import time
  5. from typing import Any
  6. from bleak.backends.device import BLEDevice
  7. from ..const import SwitchbotModel
  8. from ..const.lock import LockStatus, QuickKeyFunction
  9. from .device import (
  10. SwitchbotEncryptedDevice,
  11. SwitchbotOperationError,
  12. SwitchbotSequenceDevice,
  13. )
  14. COMMAND_HEADER = "57"
  15. COMMAND_LOCK_INFO = {
  16. SwitchbotModel.LOCK: f"{COMMAND_HEADER}0f4f8101",
  17. SwitchbotModel.LOCK_LITE: f"{COMMAND_HEADER}0f4f8101",
  18. SwitchbotModel.LOCK_PRO: f"{COMMAND_HEADER}0f4f8104",
  19. SwitchbotModel.LOCK_ULTRA: f"{COMMAND_HEADER}0f4f8107",
  20. SwitchbotModel.LOCK_ULTRA_MAX: f"{COMMAND_HEADER}0f4f8107",
  21. SwitchbotModel.UWB_LOCK: f"{COMMAND_HEADER}0f4f8107",
  22. SwitchbotModel.LOCK_NANO: f"{COMMAND_HEADER}0f4f810c",
  23. SwitchbotModel.LOCK_VISION_PRO: f"{COMMAND_HEADER}0f4f8102",
  24. SwitchbotModel.LOCK_VISION: f"{COMMAND_HEADER}0f4f8102",
  25. SwitchbotModel.LOCK_PRO_WIFI: f"{COMMAND_HEADER}0f4f810a",
  26. }
  27. COMMAND_UNLOCK = {
  28. SwitchbotModel.LOCK: f"{COMMAND_HEADER}0f4e01011080",
  29. SwitchbotModel.LOCK_LITE: f"{COMMAND_HEADER}0f4e01011080",
  30. SwitchbotModel.LOCK_PRO: f"{COMMAND_HEADER}0f4e0101000080",
  31. SwitchbotModel.LOCK_ULTRA: f"{COMMAND_HEADER}0f4e0101000080",
  32. SwitchbotModel.LOCK_ULTRA_MAX: f"{COMMAND_HEADER}0f4e0101000080",
  33. SwitchbotModel.UWB_LOCK: f"{COMMAND_HEADER}0f4e0101000080",
  34. SwitchbotModel.LOCK_NANO: f"{COMMAND_HEADER}0f4e0101000080",
  35. SwitchbotModel.LOCK_VISION_PRO: f"{COMMAND_HEADER}0f4e0101000080",
  36. SwitchbotModel.LOCK_VISION: f"{COMMAND_HEADER}0f4e0101000080",
  37. SwitchbotModel.LOCK_PRO_WIFI: f"{COMMAND_HEADER}0f4e0101000080",
  38. }
  39. COMMAND_UNLOCK_WITHOUT_UNLATCH = {
  40. SwitchbotModel.LOCK: f"{COMMAND_HEADER}0f4e010110a0",
  41. SwitchbotModel.LOCK_LITE: f"{COMMAND_HEADER}0f4e010110a0",
  42. SwitchbotModel.LOCK_PRO: f"{COMMAND_HEADER}0f4e01010000a0",
  43. SwitchbotModel.LOCK_ULTRA: f"{COMMAND_HEADER}0f4e01010000a0",
  44. SwitchbotModel.LOCK_ULTRA_MAX: f"{COMMAND_HEADER}0f4e01010000a0",
  45. SwitchbotModel.UWB_LOCK: f"{COMMAND_HEADER}0f4e01010000a0",
  46. SwitchbotModel.LOCK_NANO: f"{COMMAND_HEADER}0f4e01010000a0",
  47. SwitchbotModel.LOCK_VISION_PRO: f"{COMMAND_HEADER}0f4e01010000a0",
  48. SwitchbotModel.LOCK_VISION: f"{COMMAND_HEADER}0f4e01010000a0",
  49. SwitchbotModel.LOCK_PRO_WIFI: f"{COMMAND_HEADER}0f4e01010000a0",
  50. }
  51. COMMAND_LOCK = {
  52. SwitchbotModel.LOCK: f"{COMMAND_HEADER}0f4e01011000",
  53. SwitchbotModel.LOCK_LITE: f"{COMMAND_HEADER}0f4e01011000",
  54. SwitchbotModel.LOCK_PRO: f"{COMMAND_HEADER}0f4e0101000000",
  55. SwitchbotModel.LOCK_ULTRA: f"{COMMAND_HEADER}0f4e0101000000",
  56. SwitchbotModel.LOCK_ULTRA_MAX: f"{COMMAND_HEADER}0f4e0101000000",
  57. SwitchbotModel.UWB_LOCK: f"{COMMAND_HEADER}0f4e0101000000",
  58. SwitchbotModel.LOCK_NANO: f"{COMMAND_HEADER}0f4e0101000000",
  59. SwitchbotModel.LOCK_VISION_PRO: f"{COMMAND_HEADER}0f4e0101000000",
  60. SwitchbotModel.LOCK_VISION: f"{COMMAND_HEADER}0f4e0101000000",
  61. SwitchbotModel.LOCK_PRO_WIFI: f"{COMMAND_HEADER}0f4e0101000000",
  62. }
  63. COMMAND_BATTERY_BAYS = {
  64. SwitchbotModel.LOCK_PRO: f"{COMMAND_HEADER}0f4f0409",
  65. }
  66. COMMAND_HALF_LOCK = {
  67. SwitchbotModel.LOCK_ULTRA: f"{COMMAND_HEADER}0f4e0101000008",
  68. }
  69. COMMAND_GET_QUICK_KEY = {
  70. SwitchbotModel.LOCK_ULTRA: f"{COMMAND_HEADER}0f4f0401",
  71. }
  72. COMMAND_SET_QUICK_KEY_PREFIX = {
  73. SwitchbotModel.LOCK_ULTRA: f"{COMMAND_HEADER}0f4e040100",
  74. }
  75. COMMAND_ENABLE_NOTIFICATIONS = {
  76. SwitchbotModel.LOCK: f"{COMMAND_HEADER}0e01001e00008101",
  77. SwitchbotModel.LOCK_LITE: f"{COMMAND_HEADER}0e01001e00008101",
  78. SwitchbotModel.LOCK_PRO: f"{COMMAND_HEADER}0e01001e00008104",
  79. SwitchbotModel.LOCK_ULTRA: f"{COMMAND_HEADER}0e01001e00008107",
  80. SwitchbotModel.LOCK_ULTRA_MAX: f"{COMMAND_HEADER}0e01001e00008107",
  81. SwitchbotModel.UWB_LOCK: f"{COMMAND_HEADER}0e01001e00008107",
  82. SwitchbotModel.LOCK_NANO: f"{COMMAND_HEADER}0e01001e0000810c",
  83. SwitchbotModel.LOCK_VISION_PRO: f"{COMMAND_HEADER}0e01001e00008102",
  84. SwitchbotModel.LOCK_VISION: f"{COMMAND_HEADER}0e01001e00008102",
  85. SwitchbotModel.LOCK_PRO_WIFI: f"{COMMAND_HEADER}0e01001e0000810a",
  86. }
  87. COMMAND_DISABLE_NOTIFICATIONS = f"{COMMAND_HEADER}0e00"
  88. MOVING_STATUSES = {LockStatus.LOCKING, LockStatus.UNLOCKING}
  89. BLOCKED_STATUSES = {LockStatus.LOCKING_STOP, LockStatus.UNLOCKING_STOP}
  90. REST_STATUSES = {LockStatus.LOCKED, LockStatus.UNLOCKED, LockStatus.NOT_FULLY_LOCKED}
  91. _LOGGER = logging.getLogger(__name__)
  92. COMMAND_RESULT_EXPECTED_VALUES = {1, 6}
  93. # The return value of the command is 1 when the command is successful.
  94. # The return value of the command is 6 when the command is successful but the battery is low.
  95. class SwitchbotLock(SwitchbotSequenceDevice, SwitchbotEncryptedDevice):
  96. """Representation of a Switchbot Lock."""
  97. _model = SwitchbotModel.LOCK
  98. _notifications_enabled: bool = False
  99. def __init__(
  100. self,
  101. device: BLEDevice,
  102. key_id: str,
  103. encryption_key: str,
  104. interface: int = 0,
  105. model: SwitchbotModel | None = None,
  106. **kwargs: Any,
  107. ) -> None:
  108. if model is None:
  109. model = self._model
  110. if model not in (
  111. SwitchbotModel.LOCK,
  112. SwitchbotModel.LOCK_PRO,
  113. SwitchbotModel.LOCK_LITE,
  114. SwitchbotModel.LOCK_ULTRA,
  115. SwitchbotModel.LOCK_ULTRA_MAX,
  116. SwitchbotModel.UWB_LOCK,
  117. SwitchbotModel.LOCK_NANO,
  118. SwitchbotModel.LOCK_VISION_PRO,
  119. SwitchbotModel.LOCK_VISION,
  120. SwitchbotModel.LOCK_PRO_WIFI,
  121. ):
  122. raise ValueError("initializing SwitchbotLock with a non-lock model")
  123. super().__init__(device, key_id, encryption_key, interface, model, **kwargs)
  124. async def lock(self) -> bool:
  125. """Send lock command."""
  126. return await self._lock_unlock(
  127. COMMAND_LOCK[self._model], {LockStatus.LOCKED, LockStatus.LOCKING}
  128. )
  129. async def unlock(self) -> bool:
  130. """Send unlock command. If unlatch feature is enabled in EU firmware, also unlatches door"""
  131. return await self._lock_unlock(
  132. COMMAND_UNLOCK[self._model], {LockStatus.UNLOCKED, LockStatus.UNLOCKING}
  133. )
  134. async def unlock_without_unlatch(self) -> bool:
  135. """Send unlock command. This command will not unlatch the door."""
  136. return await self._lock_unlock(
  137. COMMAND_UNLOCK_WITHOUT_UNLATCH[self._model],
  138. {LockStatus.UNLOCKED, LockStatus.UNLOCKING, LockStatus.NOT_FULLY_LOCKED},
  139. )
  140. async def half_lock(self) -> bool:
  141. """Send half lock command (Lock Ultra EU type only)."""
  142. if self._model not in COMMAND_HALF_LOCK:
  143. raise SwitchbotOperationError(
  144. f"Half lock is not supported on {self._model}"
  145. )
  146. if not self.is_half_lock_calibrated():
  147. raise SwitchbotOperationError("Half lock is not calibrated")
  148. return await self._lock_unlock(
  149. COMMAND_HALF_LOCK[self._model],
  150. {LockStatus.HALF_LOCKED, LockStatus.LOCKING},
  151. )
  152. async def get_quick_key(self) -> dict[str, Any] | None:
  153. """
  154. Read Quick Key and basic property settings from Lock Ultra.
  155. Request: ``57 0f 4f 04 01``.
  156. Response: status, config, secondary config, motor speed, secondary speed,
  157. followed by model-specific data. Only the primary settings are returned.
  158. Config byte (also returned unchanged as ``raw``):
  159. bit7: ``light`` (0 disabled, 1 enabled).
  160. bit6: ``sound`` (0 disabled, 1 enabled).
  161. bit5: reserved, available only through ``raw``.
  162. bit4: ``manual_unlock_linkage`` (0 disabled, 1 enabled).
  163. bit3: ``enabled`` (0 Quick Key disabled, 1 enabled).
  164. bit2: ``double_press`` (0 single press, 1 double press).
  165. bits1-0: ``function`` (00 lock only, 01 unlock only, 10 toggle).
  166. ``motor_speed`` is 0 (high), 1 (normal), or 2 (quiet); it is ``None``
  167. if absent from the response. An unknown ``function`` is ``None``.
  168. Rejected responses or a missing config byte return ``None``.
  169. Unsupported models or absent responses raise ``SwitchbotOperationError``;
  170. transport errors, including ``TimeoutError`` and ``BleakError``, propagate.
  171. """
  172. if self._model not in COMMAND_GET_QUICK_KEY:
  173. raise SwitchbotOperationError(
  174. f"Quick Key is not supported on {self._model}"
  175. )
  176. result = await self._send_command(
  177. key=COMMAND_GET_QUICK_KEY[self._model], retry=self._retry_count
  178. )
  179. if not self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  180. _LOGGER.error("Failed to read Quick Key settings: %s", result)
  181. return None
  182. if len(result) < 2:
  183. _LOGGER.error("Invalid Quick Key response: %s", result)
  184. return None
  185. settings = self._parse_quick_key(result[1])
  186. settings["motor_speed"] = result[3] if len(result) > 3 else None
  187. return settings
  188. @staticmethod
  189. def _parse_quick_key(config: int) -> dict[str, Any]:
  190. """Decode the Quick Key fields of the config byte."""
  191. function_bits = config & 0b11
  192. try:
  193. function = QuickKeyFunction(function_bits)
  194. except ValueError:
  195. _LOGGER.warning(
  196. "Unknown Quick Key function value: %#04x (config byte %#04x)",
  197. function_bits,
  198. config,
  199. )
  200. function = None
  201. return {
  202. "raw": config,
  203. "light": bool(config & (1 << 7)),
  204. "sound": bool(config & (1 << 6)),
  205. "manual_unlock_linkage": bool(config & (1 << 4)),
  206. "enabled": bool(config & (1 << 3)),
  207. "double_press": bool(config & (1 << 2)),
  208. "function": function,
  209. }
  210. async def set_quick_key( # noqa: PLR0913
  211. self,
  212. *,
  213. light: bool | None = None,
  214. sound: bool | None = None,
  215. manual_unlock_linkage: bool | None = None,
  216. enabled: bool | None = None,
  217. double_press: bool | None = None,
  218. function: QuickKeyFunction | None = None,
  219. motor_speed: int = 0xFF,
  220. ) -> bool:
  221. """
  222. Update any combination of Quick Key and basic properties on Lock Ultra.
  223. Command: ``57 0f 4e 04 01 00 <update> <value> <speed>``.
  224. Target 00 uses the default behavior and can affect both grouped locks.
  225. Property arguments default to ``None`` and motor speed to ``0xFF``,
  226. leaving the corresponding settings unchanged.
  227. Update byte (1 selects the corresponding property for writing):
  228. bit7: ``light``.
  229. bit6: ``sound``.
  230. bit5: reserved, always 0.
  231. bit4: ``manual_unlock_linkage``.
  232. bit3: ``enabled`` (Quick Key).
  233. bit2: ``double_press`` (Quick Key trigger).
  234. bit1: ``function`` (selects the complete two-bit function field).
  235. bit0: unused, always 0.
  236. The value byte follows the config layout documented in ``get_quick_key``.
  237. ``False`` clears a boolean property; ``True`` sets it. Function values
  238. occupy bits1-0: 00 lock only, 01 unlock only, 10 toggle.
  239. Speed is 00 high, 01 normal, 02 quiet, or ff to preserve it (the default).
  240. Return whether the status reports success (01 or low-battery 06) and the
  241. config echo matches the requested properties. Failed status, missing
  242. config, and each mismatching property are logged separately and return
  243. ``False``. Speed is acknowledged only by status; no extra read is made.
  244. No properties or invalid speed raises ``ValueError``. Communication
  245. errors propagate.
  246. Example: ``await device.set_quick_key(light=True, sound=False, enabled=True)``.
  247. """
  248. if self._model not in COMMAND_SET_QUICK_KEY_PREFIX:
  249. raise SwitchbotOperationError(
  250. f"Quick Key is not supported on {self._model}"
  251. )
  252. if motor_speed not in (0, 1, 2, 0xFF):
  253. raise ValueError(
  254. "motor_speed must be 0 (high), 1 (normal), 2 (quiet), or 0xFF (keep)"
  255. f" (got {motor_speed!r})"
  256. )
  257. update_fields = 0
  258. value = 0
  259. for setting, bit in (
  260. (light, 7),
  261. (sound, 6),
  262. (manual_unlock_linkage, 4),
  263. (enabled, 3),
  264. (double_press, 2),
  265. ):
  266. if setting is not None:
  267. update_fields |= 1 << bit
  268. value |= int(setting) << bit
  269. if function is not None:
  270. update_fields |= 1 << 1
  271. value |= function.value
  272. if not update_fields and motor_speed == 0xFF:
  273. raise ValueError("set_quick_key requires at least one setting to change")
  274. command = (
  275. f"{COMMAND_SET_QUICK_KEY_PREFIX[self._model]}"
  276. f"{update_fields:02x}{value:02x}{motor_speed:02x}"
  277. )
  278. result = await self._send_command(key=command, retry=self._retry_count)
  279. if not self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  280. _LOGGER.error(
  281. "%s: Quick Key command failed (status=%#04x, response=%s)",
  282. self.name,
  283. result[0],
  284. result.hex(),
  285. )
  286. return False
  287. if len(result) < 2:
  288. _LOGGER.error(
  289. "%s: Quick Key write response is missing config (status=%#04x, response=%s)",
  290. self.name,
  291. result[0],
  292. result.hex(),
  293. )
  294. return False
  295. confirmed = self._parse_quick_key(result[1])
  296. requested = {
  297. "light": light,
  298. "sound": sound,
  299. "manual_unlock_linkage": manual_unlock_linkage,
  300. "enabled": enabled,
  301. "double_press": double_press,
  302. "function": function,
  303. }
  304. mismatches = [
  305. (setting, expected, confirmed[setting])
  306. for setting, expected in requested.items()
  307. if expected is not None and confirmed[setting] != expected
  308. ]
  309. for setting, expected, reported in mismatches:
  310. _LOGGER.error(
  311. "%s: Quick Key %s was not applied (requested=%s, reported=%s, config=%#04x)",
  312. self.name,
  313. setting,
  314. expected,
  315. reported,
  316. result[1],
  317. )
  318. return not mismatches
  319. def _parse_basic_data(self, basic_data: bytes) -> dict[str, Any]:
  320. """Parse basic data from lock."""
  321. if len(basic_data) < 3:
  322. return {}
  323. return {
  324. "battery": basic_data[1],
  325. "firmware": basic_data[2] / 10.0,
  326. }
  327. async def _lock_unlock(
  328. self, command: str, ignore_statuses: set[LockStatus]
  329. ) -> bool:
  330. status = self.get_lock_status()
  331. if status is None:
  332. await self.update()
  333. status = self.get_lock_status()
  334. if status in ignore_statuses:
  335. return True
  336. await self._enable_notifications()
  337. result = await self._send_command(command)
  338. status = self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES)
  339. # Also update the battery and firmware version
  340. if basic_data := await self._get_basic_info():
  341. self._last_full_update = time.monotonic()
  342. if len(basic_data) >= 3:
  343. self._update_parsed_data(self._parse_basic_data(basic_data))
  344. else:
  345. _LOGGER.warning("Invalid basic data received: %s", basic_data)
  346. self._fire_callbacks()
  347. return status
  348. async def get_basic_info(self) -> dict[str, Any] | None:
  349. """Get device basic status."""
  350. lock_raw_data = await self._get_lock_info()
  351. if not lock_raw_data:
  352. return None
  353. _LOGGER.debug(
  354. "lock_raw_data: %s, address: %s", lock_raw_data.hex(), self._device.address
  355. )
  356. basic_data = await self._get_basic_info()
  357. if not basic_data:
  358. return None
  359. _LOGGER.debug(
  360. "basic_data: %s, address: %s", basic_data.hex(), self._device.address
  361. )
  362. lock_data = self._parse_lock_data(lock_raw_data[1:], self._model)
  363. if lock_data is None:
  364. return None
  365. result = lock_data | self._parse_basic_data(basic_data)
  366. if self._model in COMMAND_BATTERY_BAYS and (
  367. bays_data := await self._get_battery_bays()
  368. ):
  369. result |= self._parse_battery_bays(bays_data)
  370. return result
  371. def is_calibrated(self) -> Any:
  372. """Return True if lock is calibrated."""
  373. return self._get_adv_value("calibration")
  374. def get_lock_status(self) -> LockStatus:
  375. """Return lock status."""
  376. return self._get_adv_value("status")
  377. def is_door_open(self) -> bool:
  378. """Return True if door is open."""
  379. return self._get_adv_value("door_open")
  380. def is_unclosed_alarm_on(self) -> bool:
  381. """Return True if unclosed door alarm is on."""
  382. return self._get_adv_value("unclosed_alarm")
  383. def is_unlocked_alarm_on(self) -> bool:
  384. """Return True if lock unlocked alarm is on."""
  385. return self._get_adv_value("unlocked_alarm")
  386. def is_auto_lock_paused(self) -> bool:
  387. """Return True if auto lock is paused."""
  388. return self._get_adv_value("auto_lock_paused")
  389. def is_night_latch_enabled(self) -> bool:
  390. """Return True if Night Latch is enabled on EU firmware."""
  391. return self._get_adv_value("night_latch")
  392. def is_half_lock_calibrated(self) -> bool | None:
  393. """Return True if half lock position is calibrated (Lock Ultra only)."""
  394. return self._get_adv_value("half_lock_calibration")
  395. async def _get_lock_info(self) -> bytes | None:
  396. """Return lock info of device."""
  397. _data = await self._send_command(
  398. key=COMMAND_LOCK_INFO[self._model], retry=self._retry_count
  399. )
  400. if not self._check_command_result(_data, 0, COMMAND_RESULT_EXPECTED_VALUES):
  401. _LOGGER.error("Unsuccessful, please try again")
  402. return None
  403. return _data
  404. async def _get_battery_bays(self) -> bytes | None:
  405. """Return battery bays info of device."""
  406. _data = await self._send_command(
  407. key=COMMAND_BATTERY_BAYS[self._model], retry=self._retry_count
  408. )
  409. if not self._check_command_result(_data, 0, COMMAND_RESULT_EXPECTED_VALUES):
  410. _LOGGER.warning("Unable to read battery bays")
  411. return None
  412. if len(_data) < 3:
  413. _LOGGER.warning("Invalid battery bays data received: %s", _data.hex())
  414. return None
  415. return _data
  416. @staticmethod
  417. def _parse_battery_bays(data: bytes) -> dict[str, int | None]:
  418. """Parse battery bays data, None for an empty bay."""
  419. return {
  420. "left_battery": data[1] & 0b01111111 if data[1] & 0b10000000 else None,
  421. "right_battery": data[2] & 0b01111111 if data[2] & 0b10000000 else None,
  422. }
  423. async def _enable_notifications(self) -> bool:
  424. result = await self._send_command(COMMAND_ENABLE_NOTIFICATIONS[self._model])
  425. return self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES)
  426. async def _disable_notifications(self) -> bool:
  427. if not self._notifications_enabled:
  428. return True
  429. result = await self._send_command(COMMAND_DISABLE_NOTIFICATIONS)
  430. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  431. self._notifications_enabled = False
  432. return not self._notifications_enabled
  433. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  434. if self._check_command_result(data, 0, {0xF}):
  435. if self._expected_disconnect:
  436. _LOGGER.debug(
  437. "%s: Ignoring lock notification during expected disconnect",
  438. self.name,
  439. )
  440. return
  441. self._update_lock_status(data)
  442. else:
  443. super()._notification_handler(_sender, data)
  444. def _update_lock_status(self, data: bytearray) -> None:
  445. lock_data = self._parse_lock_data(self._decrypt(data[4:]), self._model)
  446. if lock_data is None:
  447. _LOGGER.debug("%s: Ignoring lock notification: %s", self.name, data.hex())
  448. return
  449. if self._update_parsed_data(lock_data):
  450. # We leave notifications enabled in case
  451. # the lock is operated manually before we
  452. # disconnect.
  453. self._reset_disconnect_timer()
  454. self._fire_callbacks()
  455. @staticmethod
  456. def _parse_lock_data(data: bytes, model: SwitchbotModel) -> dict[str, Any] | None:
  457. if model in {SwitchbotModel.LOCK, SwitchbotModel.LOCK_VISION_PRO}:
  458. return {
  459. "calibration": bool(data[0] & 0b10000000),
  460. "status": LockStatus((data[0] & 0b01110000) >> 4),
  461. "door_open": bool(data[0] & 0b00000100),
  462. "unclosed_alarm": bool(data[1] & 0b00100000),
  463. "unlocked_alarm": bool(data[1] & 0b00010000),
  464. }
  465. if model in {SwitchbotModel.LOCK_LITE, SwitchbotModel.LOCK_VISION}:
  466. return {
  467. "calibration": bool(data[0] & 0b10000000),
  468. "status": LockStatus((data[0] & 0b01110000) >> 4),
  469. "unlocked_alarm": bool(data[1] & 0b00010000),
  470. }
  471. status_value = (data[0] & 0b01111000) >> 3
  472. try:
  473. status = LockStatus(status_value)
  474. except ValueError:
  475. _LOGGER.warning("Unknown lock status %s for model %s", status_value, model)
  476. _LOGGER.debug("Unrecognized lock data: %s", data.hex())
  477. return None
  478. if model is SwitchbotModel.LOCK_NANO:
  479. return {
  480. "calibration": bool(data[0] & 0b10000000),
  481. "status": status,
  482. "auto_lock_paused": bool(data[1] & 0b00001000),
  483. "unlocked_alarm": bool(data[5] & 0b01000000),
  484. }
  485. result = {
  486. "calibration": bool(data[0] & 0b10000000),
  487. "status": status,
  488. "door_open": bool(data[1] & 0b00010000),
  489. "unclosed_alarm": bool(data[5] & 0b10000000),
  490. "unlocked_alarm": bool(data[5] & 0b01000000),
  491. }
  492. if model is SwitchbotModel.LOCK_ULTRA:
  493. result["half_lock_calibration"] = bool(data[1] & 0b00000001)
  494. return result
  495. class SwitchbotLockUltra(SwitchbotLock):
  496. """SwitchBot locks that use the Lock 2 basic-info format."""
  497. _model = SwitchbotModel.LOCK_ULTRA
  498. def _parse_basic_data(self, basic_data: bytes) -> dict[str, Any]:
  499. """Read the active battery and firmware from a Lock 2 basic-info reply."""
  500. if len(basic_data) < 4:
  501. return {}
  502. # Bit 7 of the main battery byte selects the backup battery.
  503. battery = basic_data[2] if basic_data[1] & 0x80 else basic_data[1]
  504. return {
  505. "battery": battery,
  506. "firmware": basic_data[3] / 10.0,
  507. }