lock.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 LockStatus, SwitchbotModel
  8. from .device import SwitchbotEncryptedDevice
  9. COMMAND_HEADER = "57"
  10. COMMAND_LOCK_INFO = {
  11. SwitchbotModel.LOCK: f"{COMMAND_HEADER}0f4f8101",
  12. SwitchbotModel.LOCK_PRO: f"{COMMAND_HEADER}0f4f8102",
  13. }
  14. COMMAND_UNLOCK = {
  15. SwitchbotModel.LOCK: f"{COMMAND_HEADER}0f4e01011080",
  16. SwitchbotModel.LOCK_PRO: f"{COMMAND_HEADER}0f4e0101000080",
  17. }
  18. COMMAND_UNLOCK_WITHOUT_UNLATCH = {
  19. SwitchbotModel.LOCK: f"{COMMAND_HEADER}0f4e010110a0",
  20. SwitchbotModel.LOCK_PRO: f"{COMMAND_HEADER}0f4e01010000a0",
  21. }
  22. COMMAND_LOCK = {
  23. SwitchbotModel.LOCK: f"{COMMAND_HEADER}0f4e01011000",
  24. SwitchbotModel.LOCK_PRO: f"{COMMAND_HEADER}0f4e0101000000",
  25. }
  26. COMMAND_ENABLE_NOTIFICATIONS = f"{COMMAND_HEADER}0e01001e00008101"
  27. COMMAND_DISABLE_NOTIFICATIONS = f"{COMMAND_HEADER}0e00"
  28. MOVING_STATUSES = {LockStatus.LOCKING, LockStatus.UNLOCKING}
  29. BLOCKED_STATUSES = {LockStatus.LOCKING_STOP, LockStatus.UNLOCKING_STOP}
  30. REST_STATUSES = {LockStatus.LOCKED, LockStatus.UNLOCKED, LockStatus.NOT_FULLY_LOCKED}
  31. _LOGGER = logging.getLogger(__name__)
  32. COMMAND_RESULT_EXPECTED_VALUES = {1, 6}
  33. # The return value of the command is 1 when the command is successful.
  34. # The return value of the command is 6 when the command is successful but the battery is low.
  35. class SwitchbotLock(SwitchbotEncryptedDevice):
  36. """Representation of a Switchbot Lock."""
  37. def __init__(
  38. self,
  39. device: BLEDevice,
  40. key_id: str,
  41. encryption_key: str,
  42. interface: int = 0,
  43. model: SwitchbotModel = SwitchbotModel.LOCK,
  44. **kwargs: Any,
  45. ) -> None:
  46. if model not in (SwitchbotModel.LOCK, SwitchbotModel.LOCK_PRO):
  47. raise ValueError("initializing SwitchbotLock with a non-lock model")
  48. self._notifications_enabled: bool = False
  49. super().__init__(device, key_id, encryption_key, model, interface, **kwargs)
  50. @classmethod
  51. async def verify_encryption_key(
  52. cls,
  53. device: BLEDevice,
  54. key_id: str,
  55. encryption_key: str,
  56. model: SwitchbotModel = SwitchbotModel.LOCK,
  57. **kwargs: Any,
  58. ) -> bool:
  59. return await super().verify_encryption_key(
  60. device, key_id, encryption_key, model, **kwargs
  61. )
  62. async def lock(self) -> bool:
  63. """Send lock command."""
  64. return await self._lock_unlock(
  65. COMMAND_LOCK[self._model], {LockStatus.LOCKED, LockStatus.LOCKING}
  66. )
  67. async def unlock(self) -> bool:
  68. """Send unlock command. If unlatch feature is enabled in EU firmware, also unlatches door"""
  69. return await self._lock_unlock(
  70. COMMAND_UNLOCK[self._model], {LockStatus.UNLOCKED, LockStatus.UNLOCKING}
  71. )
  72. async def unlock_without_unlatch(self) -> bool:
  73. """Send unlock command. This command will not unlatch the door."""
  74. return await self._lock_unlock(
  75. COMMAND_UNLOCK_WITHOUT_UNLATCH[self._model],
  76. {LockStatus.UNLOCKED, LockStatus.UNLOCKING, LockStatus.NOT_FULLY_LOCKED},
  77. )
  78. def _parse_basic_data(self, basic_data: bytes) -> dict[str, Any]:
  79. """Parse basic data from lock."""
  80. return {
  81. "battery": basic_data[1],
  82. "firmware": basic_data[2] / 10.0,
  83. }
  84. async def _lock_unlock(
  85. self, command: str, ignore_statuses: set[LockStatus]
  86. ) -> bool:
  87. status = self.get_lock_status()
  88. if status is None:
  89. await self.update()
  90. status = self.get_lock_status()
  91. if status in ignore_statuses:
  92. return True
  93. await self._enable_notifications()
  94. result = await self._send_command(command)
  95. status = self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES)
  96. # Also update the battery and firmware version
  97. if basic_data := await self._get_basic_info():
  98. self._last_full_update = time.monotonic()
  99. if len(basic_data) >= 3:
  100. self._update_parsed_data(self._parse_basic_data(basic_data))
  101. else:
  102. _LOGGER.warning("Invalid basic data received: %s", basic_data)
  103. self._fire_callbacks()
  104. return status
  105. async def get_basic_info(self) -> dict[str, Any] | None:
  106. """Get device basic status."""
  107. lock_raw_data = await self._get_lock_info()
  108. if not lock_raw_data:
  109. return None
  110. basic_data = await self._get_basic_info()
  111. if not basic_data:
  112. return None
  113. return self._parse_lock_data(lock_raw_data[1:]) | self._parse_basic_data(
  114. basic_data
  115. )
  116. def is_calibrated(self) -> Any:
  117. """Return True if lock is calibrated."""
  118. return self._get_adv_value("calibration")
  119. def get_lock_status(self) -> LockStatus:
  120. """Return lock status."""
  121. return self._get_adv_value("status")
  122. def is_door_open(self) -> bool:
  123. """Return True if door is open."""
  124. return self._get_adv_value("door_open")
  125. def is_unclosed_alarm_on(self) -> bool:
  126. """Return True if unclosed door alarm is on."""
  127. return self._get_adv_value("unclosed_alarm")
  128. def is_unlocked_alarm_on(self) -> bool:
  129. """Return True if lock unlocked alarm is on."""
  130. return self._get_adv_value("unlocked_alarm")
  131. def is_auto_lock_paused(self) -> bool:
  132. """Return True if auto lock is paused."""
  133. return self._get_adv_value("auto_lock_paused")
  134. def is_night_latch_enabled(self) -> bool:
  135. """Return True if Night Latch is enabled on EU firmware."""
  136. return self._get_adv_value("night_latch")
  137. async def _get_lock_info(self) -> bytes | None:
  138. """Return lock info of device."""
  139. _data = await self._send_command(
  140. key=COMMAND_LOCK_INFO[self._model], retry=self._retry_count
  141. )
  142. if not self._check_command_result(_data, 0, COMMAND_RESULT_EXPECTED_VALUES):
  143. _LOGGER.error("Unsuccessful, please try again")
  144. return None
  145. return _data
  146. async def _enable_notifications(self) -> bool:
  147. if self._notifications_enabled:
  148. return True
  149. result = await self._send_command(COMMAND_ENABLE_NOTIFICATIONS)
  150. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  151. self._notifications_enabled = True
  152. return self._notifications_enabled
  153. async def _disable_notifications(self) -> bool:
  154. if not self._notifications_enabled:
  155. return True
  156. result = await self._send_command(COMMAND_DISABLE_NOTIFICATIONS)
  157. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  158. self._notifications_enabled = False
  159. return not self._notifications_enabled
  160. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  161. if self._notifications_enabled and self._check_command_result(data, 0, {0xF}):
  162. self._update_lock_status(data)
  163. else:
  164. super()._notification_handler(_sender, data)
  165. def _update_lock_status(self, data: bytearray) -> None:
  166. lock_data = self._parse_lock_data(self._decrypt(data[4:]))
  167. if self._update_parsed_data(lock_data):
  168. # We leave notifications enabled in case
  169. # the lock is operated manually before we
  170. # disconnect.
  171. self._reset_disconnect_timer()
  172. self._fire_callbacks()
  173. @staticmethod
  174. def _parse_lock_data(data: bytes) -> dict[str, Any]:
  175. return {
  176. "calibration": bool(data[0] & 0b10000000),
  177. "status": LockStatus((data[0] & 0b01110000) >> 4),
  178. "door_open": bool(data[0] & 0b00000100),
  179. "unclosed_alarm": bool(data[1] & 0b00100000),
  180. "unlocked_alarm": bool(data[1] & 0b00010000),
  181. }