lock.py 8.5 KB

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