lock.py 7.9 KB

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