lock.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  7. from ..const import LockStatus
  8. from ..models import SwitchBotAdvertisement
  9. from .device import SwitchbotDevice
  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. advertisement: SwitchBotAdvertisement,
  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__(advertisement.device, None, interface, **kwargs)
  45. self.update_from_advertisement(advertisement)
  46. async def lock(self) -> bool:
  47. """Send lock command."""
  48. return await self._lock_unlock(
  49. COMMAND_LOCK, {LockStatus.LOCKED, LockStatus.LOCKING}
  50. )
  51. async def unlock(self) -> bool:
  52. """Send unlock command."""
  53. return await self._lock_unlock(
  54. COMMAND_UNLOCK, {LockStatus.UNLOCKED, LockStatus.UNLOCKING}
  55. )
  56. async def _lock_unlock(
  57. self, command: str, ignore_statuses: set[LockStatus]
  58. ) -> bool:
  59. status = self.get_lock_status()
  60. if status is None:
  61. await self.update()
  62. status = self.get_lock_status()
  63. if status in ignore_statuses:
  64. return True
  65. await self._enable_notifications()
  66. result = await self._send_command(command)
  67. if not self._check_command_result(result, 0, {1}):
  68. return False
  69. return True
  70. async def get_basic_info(self) -> dict[str, Any] | None:
  71. """Get device basic status."""
  72. lock_raw_data = await self._get_lock_info()
  73. if not lock_raw_data:
  74. return None
  75. basic_data = await self._get_basic_info()
  76. if not basic_data:
  77. return None
  78. lock_data = self._parse_lock_data(lock_raw_data[1:])
  79. lock_data.update(battery=basic_data[1], firmware=basic_data[2] / 10.0)
  80. return lock_data
  81. def is_calibrated(self) -> Any:
  82. """Return True if lock is calibrated."""
  83. return self._get_adv_value("calibration")
  84. def get_lock_status(self) -> LockStatus:
  85. """Return lock status."""
  86. return self._get_adv_value("status")
  87. def is_door_open(self) -> bool:
  88. """Return True if door is open."""
  89. return self._get_adv_value("door_open")
  90. def is_unclosed_alarm_on(self) -> bool:
  91. """Return True if unclosed door alarm is on."""
  92. return self._get_adv_value("unclosed_alarm")
  93. def is_unlocked_alarm_on(self) -> bool:
  94. """Return True if lock unlocked alarm is on."""
  95. return self._get_adv_value("unlocked_alarm")
  96. def is_auto_lock_paused(self) -> bool:
  97. """Return True if auto lock is paused."""
  98. return self._get_adv_value("auto_lock_paused")
  99. async def _get_lock_info(self) -> bytes | None:
  100. """Return lock info of device."""
  101. _data = await self._send_command(key=COMMAND_LOCK_INFO, retry=self._retry_count)
  102. if not self._check_command_result(_data, 0, {1}):
  103. _LOGGER.error("Unsuccessful, please try again")
  104. return None
  105. return _data
  106. async def _enable_notifications(self) -> bool:
  107. if self._notifications_enabled:
  108. return True
  109. result = await self._send_command(COMMAND_ENABLE_NOTIFICATIONS)
  110. if self._check_command_result(result, 0, {1}):
  111. self._notifications_enabled = True
  112. return self._notifications_enabled
  113. async def _disable_notifications(self) -> bool:
  114. if not self._notifications_enabled:
  115. return True
  116. result = await self._send_command(COMMAND_DISABLE_NOTIFICATIONS)
  117. if self._check_command_result(result, 0, {1}):
  118. self._notifications_enabled = False
  119. return not self._notifications_enabled
  120. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  121. if self._notifications_enabled and self._check_command_result(data, 0, {0xF}):
  122. self._update_lock_status(data)
  123. else:
  124. super()._notification_handler(_sender, data)
  125. def _update_lock_status(self, data: bytearray) -> None:
  126. data = self._decrypt(data[4:])
  127. lock_data = self._parse_lock_data(data)
  128. current_status = self.get_lock_status()
  129. if (
  130. lock_data["status"] != current_status or current_status not in REST_STATUSES
  131. ) and (
  132. lock_data["status"] in REST_STATUSES
  133. or lock_data["status"] in BLOCKED_STATUSES
  134. ):
  135. asyncio.create_task(self._disable_notifications())
  136. self._update_parsed_data(lock_data)
  137. @staticmethod
  138. def _parse_lock_data(data: bytes) -> dict[str, Any]:
  139. return {
  140. "calibration": bool(data[0] & 0b10000000),
  141. "status": LockStatus((data[0] & 0b01110000) >> 4),
  142. "door_open": bool(data[0] & 0b00000100),
  143. "unclosed_alarm": bool(data[1] & 0b00100000),
  144. "unlocked_alarm": bool(data[1] & 0b00010000),
  145. }
  146. async def _send_command(
  147. self, key: str, retry: int | None = None, encrypt: bool = True
  148. ) -> bytes | None:
  149. if not encrypt:
  150. return await super()._send_command(key[:2] + "000000" + key[2:], retry)
  151. result = await self._ensure_encryption_initialized()
  152. if not result:
  153. _LOGGER.error("Failed to initialize encryption")
  154. return None
  155. encrypted = (
  156. key[:2] + self._key_id + self._iv[0:2].hex() + self._encrypt(key[2:])
  157. )
  158. result = await super()._send_command(encrypted, retry)
  159. return result[:1] + self._decrypt(result[4:])
  160. async def _ensure_encryption_initialized(self) -> bool:
  161. if self._iv is not None:
  162. return True
  163. result = await self._send_command(
  164. COMMAND_GET_CK_IV + self._key_id, encrypt=False
  165. )
  166. ok = self._check_command_result(result, 0, {0x01})
  167. if ok:
  168. self._iv = result[4:]
  169. return ok
  170. async def _execute_disconnect(self) -> None:
  171. await super()._execute_disconnect()
  172. self._iv = None
  173. self._cipher = None
  174. self._notifications_enabled = False
  175. def _get_cipher(self) -> Cipher:
  176. if self._cipher is None:
  177. self._cipher = Cipher(
  178. algorithms.AES128(self._encryption_key), modes.CTR(self._iv)
  179. )
  180. return self._cipher
  181. def _encrypt(self, data: str) -> str:
  182. if len(data) == 0:
  183. return ""
  184. encryptor = self._get_cipher().encryptor()
  185. return (encryptor.update(bytearray.fromhex(data)) + encryptor.finalize()).hex()
  186. def _decrypt(self, data: bytearray) -> bytes:
  187. if len(data) == 0:
  188. return b""
  189. decryptor = self._get_cipher().decryptor()
  190. return decryptor.update(data) + decryptor.finalize()