lock.py 12 KB

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