1
0

lock.py 9.8 KB

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