lock.py 20 KB

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