lock.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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}0f4f8104",
  15. SwitchbotModel.LOCK_ULTRA: f"{COMMAND_HEADER}0f4f8107",
  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. _LOGGER.debug(
  125. "lock_raw_data: %s, address: %s", lock_raw_data.hex(), self._device.address
  126. )
  127. basic_data = await self._get_basic_info()
  128. if not basic_data:
  129. return None
  130. _LOGGER.debug(
  131. "basic_data: %s, address: %s", basic_data.hex(), self._device.address
  132. )
  133. return self._parse_lock_data(
  134. lock_raw_data[1:], self._model
  135. ) | self._parse_basic_data(basic_data)
  136. def is_calibrated(self) -> Any:
  137. """Return True if lock is calibrated."""
  138. return self._get_adv_value("calibration")
  139. def get_lock_status(self) -> LockStatus:
  140. """Return lock status."""
  141. return self._get_adv_value("status")
  142. def is_door_open(self) -> bool:
  143. """Return True if door is open."""
  144. return self._get_adv_value("door_open")
  145. def is_unclosed_alarm_on(self) -> bool:
  146. """Return True if unclosed door alarm is on."""
  147. return self._get_adv_value("unclosed_alarm")
  148. def is_unlocked_alarm_on(self) -> bool:
  149. """Return True if lock unlocked alarm is on."""
  150. return self._get_adv_value("unlocked_alarm")
  151. def is_auto_lock_paused(self) -> bool:
  152. """Return True if auto lock is paused."""
  153. return self._get_adv_value("auto_lock_paused")
  154. def is_night_latch_enabled(self) -> bool:
  155. """Return True if Night Latch is enabled on EU firmware."""
  156. return self._get_adv_value("night_latch")
  157. async def _get_lock_info(self) -> bytes | None:
  158. """Return lock info of device."""
  159. _data = await self._send_command(
  160. key=COMMAND_LOCK_INFO[self._model], retry=self._retry_count
  161. )
  162. if not self._check_command_result(_data, 0, COMMAND_RESULT_EXPECTED_VALUES):
  163. _LOGGER.error("Unsuccessful, please try again")
  164. return None
  165. return _data
  166. async def _enable_notifications(self) -> bool:
  167. if self._notifications_enabled:
  168. return True
  169. result = await self._send_command(COMMAND_ENABLE_NOTIFICATIONS)
  170. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  171. self._notifications_enabled = True
  172. return self._notifications_enabled
  173. async def _disable_notifications(self) -> bool:
  174. if not self._notifications_enabled:
  175. return True
  176. result = await self._send_command(COMMAND_DISABLE_NOTIFICATIONS)
  177. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  178. self._notifications_enabled = False
  179. return not self._notifications_enabled
  180. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  181. if self._notifications_enabled and self._check_command_result(data, 0, {0xF}):
  182. self._update_lock_status(data)
  183. else:
  184. super()._notification_handler(_sender, data)
  185. def _update_lock_status(self, data: bytearray) -> None:
  186. lock_data = self._parse_lock_data(self._decrypt(data[4:]), self._model)
  187. if self._update_parsed_data(lock_data):
  188. # We leave notifications enabled in case
  189. # the lock is operated manually before we
  190. # disconnect.
  191. self._reset_disconnect_timer()
  192. self._fire_callbacks()
  193. @staticmethod
  194. def _parse_lock_data(data: bytes, model: SwitchbotModel) -> dict[str, Any]:
  195. if model == SwitchbotModel.LOCK:
  196. return {
  197. "calibration": bool(data[0] & 0b10000000),
  198. "status": LockStatus((data[0] & 0b01110000) >> 4),
  199. "door_open": bool(data[0] & 0b00000100),
  200. "unclosed_alarm": bool(data[1] & 0b00100000),
  201. "unlocked_alarm": bool(data[1] & 0b00010000),
  202. }
  203. if model == SwitchbotModel.LOCK_LITE:
  204. return {
  205. "calibration": bool(data[0] & 0b10000000),
  206. "status": LockStatus((data[0] & 0b01110000) >> 4),
  207. "unlocked_alarm": bool(data[1] & 0b00010000),
  208. }
  209. return {
  210. "calibration": bool(data[0] & 0b10000000),
  211. "status": LockStatus((data[0] & 0b01111000) >> 3),
  212. "door_open": bool(data[1] & 0b00010000),
  213. "unclosed_alarm": bool(data[5] & 0b10000000),
  214. "unlocked_alarm": bool(data[5] & 0b01000000),
  215. }