lock.py 12 KB

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