lock.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. """Library to handle connection with Switchbot Lock."""
  2. from __future__ import annotations
  3. import asyncio
  4. import base64
  5. import hashlib
  6. import hmac
  7. import json
  8. import logging
  9. from typing import Any
  10. import boto3
  11. import requests
  12. from bleak.backends.device import BLEDevice
  13. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  14. from ..api_config import SWITCHBOT_APP_API_BASE_URL, SWITCHBOT_APP_COGNITO_POOL
  15. from ..const import LockStatus, SwitchbotAuthenticationError
  16. from .device import SwitchbotDevice, SwitchbotOperationError
  17. COMMAND_HEADER = "57"
  18. COMMAND_GET_CK_IV = f"{COMMAND_HEADER}0f2103"
  19. COMMAND_LOCK_INFO = f"{COMMAND_HEADER}0f4f8101"
  20. COMMAND_UNLOCK = f"{COMMAND_HEADER}0f4e01011080"
  21. COMMAND_LOCK = f"{COMMAND_HEADER}0f4e01011000"
  22. COMMAND_ENABLE_NOTIFICATIONS = f"{COMMAND_HEADER}0e01001e00008101"
  23. COMMAND_DISABLE_NOTIFICATIONS = f"{COMMAND_HEADER}0e00"
  24. MOVING_STATUSES = {LockStatus.LOCKING, LockStatus.UNLOCKING}
  25. BLOCKED_STATUSES = {LockStatus.LOCKING_STOP, LockStatus.UNLOCKING_STOP}
  26. REST_STATUSES = {LockStatus.LOCKED, LockStatus.UNLOCKED, LockStatus.NOT_FULLY_LOCKED}
  27. _LOGGER = logging.getLogger(__name__)
  28. class SwitchbotLock(SwitchbotDevice):
  29. """Representation of a Switchbot Lock."""
  30. def __init__(
  31. self,
  32. device: BLEDevice,
  33. key_id: str,
  34. encryption_key: str,
  35. interface: int = 0,
  36. **kwargs: Any,
  37. ) -> None:
  38. if len(key_id) == 0:
  39. raise ValueError("key_id is missing")
  40. elif len(key_id) != 2:
  41. raise ValueError("key_id is invalid")
  42. if len(encryption_key) == 0:
  43. raise ValueError("encryption_key is missing")
  44. elif len(encryption_key) != 32:
  45. raise ValueError("encryption_key is invalid")
  46. self._iv = None
  47. self._cipher = None
  48. self._key_id = key_id
  49. self._encryption_key = bytearray.fromhex(encryption_key)
  50. self._notifications_enabled: bool = False
  51. super().__init__(device, None, interface, **kwargs)
  52. @staticmethod
  53. async def verify_encryption_key(
  54. device: BLEDevice, key_id: str, encryption_key: str
  55. ) -> bool:
  56. try:
  57. lock = SwitchbotLock(
  58. device=device, key_id=key_id, encryption_key=encryption_key
  59. )
  60. except ValueError:
  61. return False
  62. try:
  63. lock_info = await lock.get_basic_info()
  64. except SwitchbotOperationError:
  65. return False
  66. return lock_info is not None
  67. @staticmethod
  68. def retrieve_encryption_key(device_mac: str, username: str, password: str):
  69. """Retrieve lock key from internal SwitchBot API."""
  70. device_mac = device_mac.replace(":", "").replace("-", "").upper()
  71. msg = bytes(username + SWITCHBOT_APP_COGNITO_POOL["AppClientId"], "utf-8")
  72. secret_hash = base64.b64encode(
  73. hmac.new(
  74. SWITCHBOT_APP_COGNITO_POOL["AppClientSecret"].encode(),
  75. msg,
  76. digestmod=hashlib.sha256,
  77. ).digest()
  78. ).decode()
  79. cognito_idp_client = boto3.client(
  80. "cognito-idp", region_name=SWITCHBOT_APP_COGNITO_POOL["Region"]
  81. )
  82. try:
  83. auth_response = cognito_idp_client.initiate_auth(
  84. ClientId=SWITCHBOT_APP_COGNITO_POOL["AppClientId"],
  85. AuthFlow="USER_PASSWORD_AUTH",
  86. AuthParameters={
  87. "USERNAME": username,
  88. "PASSWORD": password,
  89. "SECRET_HASH": secret_hash,
  90. },
  91. )
  92. except cognito_idp_client.exceptions.NotAuthorizedException as err:
  93. raise SwitchbotAuthenticationError("Failed to authenticate") from err
  94. except BaseException as err:
  95. raise SwitchbotAuthenticationError(
  96. "Unexpected error during authentication"
  97. ) from err
  98. if (
  99. auth_response is None
  100. or "AuthenticationResult" not in auth_response
  101. or "AccessToken" not in auth_response["AuthenticationResult"]
  102. ):
  103. raise SwitchbotAuthenticationError("Unexpected authentication response")
  104. access_token = auth_response["AuthenticationResult"]["AccessToken"]
  105. key_response = requests.post(
  106. url=SWITCHBOT_APP_API_BASE_URL + "/developStage/keys/v1/communicate",
  107. headers={"authorization": access_token},
  108. json={
  109. "device_mac": device_mac,
  110. "keyType": "user",
  111. },
  112. timeout=10,
  113. )
  114. key_response_content = json.loads(key_response.content)
  115. if key_response_content["statusCode"] != 100:
  116. raise SwitchbotAuthenticationError(
  117. f"Unexpected status code returned by SwitchBot API: {key_response_content['statusCode']}"
  118. )
  119. return {
  120. "key_id": key_response_content["body"]["communicationKey"]["keyId"],
  121. "encryption_key": key_response_content["body"]["communicationKey"]["key"],
  122. }
  123. async def lock(self) -> bool:
  124. """Send lock command."""
  125. return await self._lock_unlock(
  126. COMMAND_LOCK, {LockStatus.LOCKED, LockStatus.LOCKING}
  127. )
  128. async def unlock(self) -> bool:
  129. """Send unlock command."""
  130. return await self._lock_unlock(
  131. COMMAND_UNLOCK, {LockStatus.UNLOCKED, LockStatus.UNLOCKING}
  132. )
  133. async def _lock_unlock(
  134. self, command: str, ignore_statuses: set[LockStatus]
  135. ) -> bool:
  136. status = self.get_lock_status()
  137. if status is None:
  138. await self.update()
  139. status = self.get_lock_status()
  140. if status in ignore_statuses:
  141. return True
  142. await self._enable_notifications()
  143. result = await self._send_command(command)
  144. if not self._check_command_result(result, 0, {1}):
  145. return False
  146. return True
  147. async def get_basic_info(self) -> dict[str, Any] | None:
  148. """Get device basic status."""
  149. lock_raw_data = await self._get_lock_info()
  150. if not lock_raw_data:
  151. return None
  152. basic_data = await self._get_basic_info()
  153. if not basic_data:
  154. return None
  155. lock_data = self._parse_lock_data(lock_raw_data[1:])
  156. lock_data.update(battery=basic_data[1], firmware=basic_data[2] / 10.0)
  157. return lock_data
  158. def is_calibrated(self) -> Any:
  159. """Return True if lock is calibrated."""
  160. return self._get_adv_value("calibration")
  161. def get_lock_status(self) -> LockStatus:
  162. """Return lock status."""
  163. return self._get_adv_value("status")
  164. def is_door_open(self) -> bool:
  165. """Return True if door is open."""
  166. return self._get_adv_value("door_open")
  167. def is_unclosed_alarm_on(self) -> bool:
  168. """Return True if unclosed door alarm is on."""
  169. return self._get_adv_value("unclosed_alarm")
  170. def is_unlocked_alarm_on(self) -> bool:
  171. """Return True if lock unlocked alarm is on."""
  172. return self._get_adv_value("unlocked_alarm")
  173. def is_auto_lock_paused(self) -> bool:
  174. """Return True if auto lock is paused."""
  175. return self._get_adv_value("auto_lock_paused")
  176. async def _get_lock_info(self) -> bytes | None:
  177. """Return lock info of device."""
  178. _data = await self._send_command(key=COMMAND_LOCK_INFO, retry=self._retry_count)
  179. if not self._check_command_result(_data, 0, {1}):
  180. _LOGGER.error("Unsuccessful, please try again")
  181. return None
  182. return _data
  183. async def _enable_notifications(self) -> bool:
  184. if self._notifications_enabled:
  185. return True
  186. result = await self._send_command(COMMAND_ENABLE_NOTIFICATIONS)
  187. if self._check_command_result(result, 0, {1}):
  188. self._notifications_enabled = True
  189. return self._notifications_enabled
  190. async def _disable_notifications(self) -> bool:
  191. if not self._notifications_enabled:
  192. return True
  193. result = await self._send_command(COMMAND_DISABLE_NOTIFICATIONS)
  194. if self._check_command_result(result, 0, {1}):
  195. self._notifications_enabled = False
  196. return not self._notifications_enabled
  197. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  198. if self._notifications_enabled and self._check_command_result(data, 0, {0xF}):
  199. self._update_lock_status(data)
  200. else:
  201. super()._notification_handler(_sender, data)
  202. def _update_lock_status(self, data: bytearray) -> None:
  203. lock_data = self._parse_lock_data(self._decrypt(data[4:]))
  204. if self._update_parsed_data(lock_data):
  205. # We leave notifications enabled in case
  206. # the lock is operated manually before we
  207. # disconnect.
  208. self._reset_disconnect_timer()
  209. self._fire_callbacks()
  210. @staticmethod
  211. def _parse_lock_data(data: bytes) -> dict[str, Any]:
  212. return {
  213. "calibration": bool(data[0] & 0b10000000),
  214. "status": LockStatus((data[0] & 0b01110000) >> 4),
  215. "door_open": bool(data[0] & 0b00000100),
  216. "unclosed_alarm": bool(data[1] & 0b00100000),
  217. "unlocked_alarm": bool(data[1] & 0b00010000),
  218. }
  219. async def _send_command(
  220. self, key: str, retry: int | None = None, encrypt: bool = True
  221. ) -> bytes | None:
  222. if not encrypt:
  223. return await super()._send_command(key[:2] + "000000" + key[2:], retry)
  224. result = await self._ensure_encryption_initialized()
  225. if not result:
  226. _LOGGER.error("Failed to initialize encryption")
  227. return None
  228. encrypted = (
  229. key[:2] + self._key_id + self._iv[0:2].hex() + self._encrypt(key[2:])
  230. )
  231. result = await super()._send_command(encrypted, retry)
  232. return result[:1] + self._decrypt(result[4:])
  233. async def _ensure_encryption_initialized(self) -> bool:
  234. if self._iv is not None:
  235. return True
  236. result = await self._send_command(
  237. COMMAND_GET_CK_IV + self._key_id, encrypt=False
  238. )
  239. ok = self._check_command_result(result, 0, {0x01})
  240. if ok:
  241. self._iv = result[4:]
  242. return ok
  243. async def _execute_disconnect(self) -> None:
  244. await super()._execute_disconnect()
  245. self._iv = None
  246. self._cipher = None
  247. self._notifications_enabled = False
  248. def _get_cipher(self) -> Cipher:
  249. if self._cipher is None:
  250. self._cipher = Cipher(
  251. algorithms.AES128(self._encryption_key), modes.CTR(self._iv)
  252. )
  253. return self._cipher
  254. def _encrypt(self, data: str) -> str:
  255. if len(data) == 0:
  256. return ""
  257. encryptor = self._get_cipher().encryptor()
  258. return (encryptor.update(bytearray.fromhex(data)) + encryptor.finalize()).hex()
  259. def _decrypt(self, data: bytearray) -> bytes:
  260. if len(data) == 0:
  261. return b""
  262. decryptor = self._get_cipher().decryptor()
  263. return decryptor.update(data) + decryptor.finalize()