lock.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. """Library to handle connection with Switchbot Lock."""
  2. from __future__ import annotations
  3. import asyncio
  4. import logging
  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
  9. from .device import SwitchbotDevice, SwitchbotOperationError
  10. COMMAND_HEADER = "57"
  11. COMMAND_GET_CK_IV = f"{COMMAND_HEADER}0f2103"
  12. COMMAND_LOCK_INFO = f"{COMMAND_HEADER}0f4f8101"
  13. COMMAND_UNLOCK = f"{COMMAND_HEADER}0f4e01011080"
  14. COMMAND_LOCK = f"{COMMAND_HEADER}0f4e01011000"
  15. COMMAND_ENABLE_NOTIFICATIONS = f"{COMMAND_HEADER}0e01001e00008101"
  16. COMMAND_DISABLE_NOTIFICATIONS = f"{COMMAND_HEADER}0e00"
  17. MOVING_STATUSES = {LockStatus.LOCKING, LockStatus.UNLOCKING}
  18. BLOCKED_STATUSES = {LockStatus.LOCKING_STOP, LockStatus.UNLOCKING_STOP}
  19. REST_STATUSES = {LockStatus.LOCKED, LockStatus.UNLOCKED, LockStatus.NOT_FULLY_LOCKED}
  20. _LOGGER = logging.getLogger(__name__)
  21. class SwitchbotLock(SwitchbotDevice):
  22. """Representation of a Switchbot Lock."""
  23. def __init__(
  24. self,
  25. device: BLEDevice,
  26. key_id: str,
  27. encryption_key: str,
  28. interface: int = 0,
  29. **kwargs: Any,
  30. ) -> None:
  31. if len(key_id) == 0:
  32. raise ValueError("key_id is missing")
  33. elif len(key_id) != 2:
  34. raise ValueError("key_id is invalid")
  35. if len(encryption_key) == 0:
  36. raise ValueError("encryption_key is missing")
  37. elif len(encryption_key) != 32:
  38. raise ValueError("encryption_key is invalid")
  39. self._iv = None
  40. self._cipher = None
  41. self._key_id = key_id
  42. self._encryption_key = bytearray.fromhex(encryption_key)
  43. self._notifications_enabled: bool = False
  44. super().__init__(device, None, interface, **kwargs)
  45. @staticmethod
  46. async def verify_encryption_key(
  47. device: BLEDevice, key_id: str, encryption_key: str
  48. ) -> bool:
  49. try:
  50. lock = SwitchbotLock(
  51. device=device, key_id=key_id, encryption_key=encryption_key
  52. )
  53. except ValueError:
  54. return False
  55. try:
  56. lock_info = await lock.get_basic_info()
  57. except SwitchbotOperationError:
  58. return False
  59. return lock_info is not None
  60. async def lock(self) -> bool:
  61. """Send lock command."""
  62. return await self._lock_unlock(
  63. COMMAND_LOCK, {LockStatus.LOCKED, LockStatus.LOCKING}
  64. )
  65. async def unlock(self) -> bool:
  66. """Send unlock command."""
  67. return await self._lock_unlock(
  68. COMMAND_UNLOCK, {LockStatus.UNLOCKED, LockStatus.UNLOCKING}
  69. )
  70. async def _lock_unlock(
  71. self, command: str, ignore_statuses: set[LockStatus]
  72. ) -> bool:
  73. status = self.get_lock_status()
  74. if status is None:
  75. await self.update()
  76. status = self.get_lock_status()
  77. if status in ignore_statuses:
  78. return True
  79. await self._enable_notifications()
  80. result = await self._send_command(command)
  81. if not self._check_command_result(result, 0, {1}):
  82. return False
  83. return True
  84. async def get_basic_info(self) -> dict[str, Any] | None:
  85. """Get device basic status."""
  86. lock_raw_data = await self._get_lock_info()
  87. if not lock_raw_data:
  88. return None
  89. basic_data = await self._get_basic_info()
  90. if not basic_data:
  91. return None
  92. lock_data = self._parse_lock_data(lock_raw_data[1:])
  93. lock_data.update(battery=basic_data[1], firmware=basic_data[2] / 10.0)
  94. return lock_data
  95. def is_calibrated(self) -> Any:
  96. """Return True if lock is calibrated."""
  97. return self._get_adv_value("calibration")
  98. def get_lock_status(self) -> LockStatus:
  99. """Return lock status."""
  100. return self._get_adv_value("status")
  101. def is_door_open(self) -> bool:
  102. """Return True if door is open."""
  103. return self._get_adv_value("door_open")
  104. def is_unclosed_alarm_on(self) -> bool:
  105. """Return True if unclosed door alarm is on."""
  106. return self._get_adv_value("unclosed_alarm")
  107. def is_unlocked_alarm_on(self) -> bool:
  108. """Return True if lock unlocked alarm is on."""
  109. return self._get_adv_value("unlocked_alarm")
  110. def is_auto_lock_paused(self) -> bool:
  111. """Return True if auto lock is paused."""
  112. return self._get_adv_value("auto_lock_paused")
  113. async def _get_lock_info(self) -> bytes | None:
  114. """Return lock info of device."""
  115. _data = await self._send_command(key=COMMAND_LOCK_INFO, retry=self._retry_count)
  116. if not self._check_command_result(_data, 0, {1}):
  117. _LOGGER.error("Unsuccessful, please try again")
  118. return None
  119. return _data
  120. async def _enable_notifications(self) -> bool:
  121. if self._notifications_enabled:
  122. return True
  123. result = await self._send_command(COMMAND_ENABLE_NOTIFICATIONS)
  124. if self._check_command_result(result, 0, {1}):
  125. self._notifications_enabled = True
  126. return self._notifications_enabled
  127. async def _disable_notifications(self) -> bool:
  128. if not self._notifications_enabled:
  129. return True
  130. result = await self._send_command(COMMAND_DISABLE_NOTIFICATIONS)
  131. if self._check_command_result(result, 0, {1}):
  132. self._notifications_enabled = False
  133. return not self._notifications_enabled
  134. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  135. if self._notifications_enabled and self._check_command_result(data, 0, {0xF}):
  136. self._update_lock_status(data)
  137. else:
  138. super()._notification_handler(_sender, data)
  139. def _update_lock_status(self, data: bytearray) -> None:
  140. data = self._decrypt(data[4:])
  141. lock_data = self._parse_lock_data(data)
  142. current_status = self.get_lock_status()
  143. if (
  144. lock_data["status"] != current_status or current_status not in REST_STATUSES
  145. ) and (
  146. lock_data["status"] in REST_STATUSES
  147. or lock_data["status"] in BLOCKED_STATUSES
  148. ):
  149. asyncio.create_task(self._disable_notifications())
  150. self._update_parsed_data(lock_data)
  151. self._fire_callbacks()
  152. @staticmethod
  153. def _parse_lock_data(data: bytes) -> dict[str, Any]:
  154. return {
  155. "calibration": bool(data[0] & 0b10000000),
  156. "status": LockStatus((data[0] & 0b01110000) >> 4),
  157. "door_open": bool(data[0] & 0b00000100),
  158. "unclosed_alarm": bool(data[1] & 0b00100000),
  159. "unlocked_alarm": bool(data[1] & 0b00010000),
  160. }
  161. async def _send_command(
  162. self, key: str, retry: int | None = None, encrypt: bool = True
  163. ) -> bytes | None:
  164. if not encrypt:
  165. return await super()._send_command(key[:2] + "000000" + key[2:], retry)
  166. result = await self._ensure_encryption_initialized()
  167. if not result:
  168. _LOGGER.error("Failed to initialize encryption")
  169. return None
  170. encrypted = (
  171. key[:2] + self._key_id + self._iv[0:2].hex() + self._encrypt(key[2:])
  172. )
  173. result = await super()._send_command(encrypted, retry)
  174. return result[:1] + self._decrypt(result[4:])
  175. async def _ensure_encryption_initialized(self) -> bool:
  176. if self._iv is not None:
  177. return True
  178. result = await self._send_command(
  179. COMMAND_GET_CK_IV + self._key_id, encrypt=False
  180. )
  181. ok = self._check_command_result(result, 0, {0x01})
  182. if ok:
  183. self._iv = result[4:]
  184. return ok
  185. async def _execute_disconnect(self) -> None:
  186. await super()._execute_disconnect()
  187. self._iv = None
  188. self._cipher = None
  189. self._notifications_enabled = False
  190. def _get_cipher(self) -> Cipher:
  191. if self._cipher is None:
  192. self._cipher = Cipher(
  193. algorithms.AES128(self._encryption_key), modes.CTR(self._iv)
  194. )
  195. return self._cipher
  196. def _encrypt(self, data: str) -> str:
  197. if len(data) == 0:
  198. return ""
  199. encryptor = self._get_cipher().encryptor()
  200. return (encryptor.update(bytearray.fromhex(data)) + encryptor.finalize()).hex()
  201. def _decrypt(self, data: bytearray) -> bytes:
  202. if len(data) == 0:
  203. return b""
  204. decryptor = self._get_cipher().decryptor()
  205. return decryptor.update(data) + decryptor.finalize()