lock.py 21 KB

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