lock.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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("Failed to authenticate") from err
  98. except Exception as err:
  99. raise SwitchbotAuthenticationError(
  100. "Unexpected error during authentication"
  101. ) from err
  102. if (
  103. auth_response is None
  104. or "AuthenticationResult" not in auth_response
  105. or "AccessToken" not in auth_response["AuthenticationResult"]
  106. ):
  107. raise SwitchbotAuthenticationError("Unexpected authentication response")
  108. access_token = auth_response["AuthenticationResult"]["AccessToken"]
  109. try:
  110. key_response = requests.post(
  111. url=SWITCHBOT_APP_API_BASE_URL + "/developStage/keys/v1/communicate",
  112. headers={"authorization": access_token},
  113. json={
  114. "device_mac": device_mac,
  115. "keyType": "user",
  116. },
  117. timeout=10,
  118. )
  119. except requests.exceptions.RequestException as err:
  120. raise SwitchbotAccountConnectionError(
  121. f"Failed to retrieve encryption key from SwitchBot Account: {err}"
  122. ) from err
  123. if key_response.status_code > 299:
  124. raise SwitchbotAuthenticationError(
  125. f"Unexpected status code returned by SwitchBot Account API: {key_response.status_code}"
  126. )
  127. key_response_content = json.loads(key_response.content)
  128. if key_response_content["statusCode"] != 100:
  129. raise SwitchbotAuthenticationError(
  130. f"Unexpected status code returned by SwitchBot API: {key_response_content['statusCode']}"
  131. )
  132. return {
  133. "key_id": key_response_content["body"]["communicationKey"]["keyId"],
  134. "encryption_key": key_response_content["body"]["communicationKey"]["key"],
  135. }
  136. async def lock(self) -> bool:
  137. """Send lock command."""
  138. return await self._lock_unlock(
  139. COMMAND_LOCK, {LockStatus.LOCKED, LockStatus.LOCKING}
  140. )
  141. async def unlock(self) -> bool:
  142. """Send unlock command."""
  143. return await self._lock_unlock(
  144. COMMAND_UNLOCK, {LockStatus.UNLOCKED, LockStatus.UNLOCKING}
  145. )
  146. def _parse_basic_data(self, basic_data: bytes) -> dict[str, Any]:
  147. """Parse basic data from lock."""
  148. return {
  149. "battery": basic_data[1],
  150. "firmware": basic_data[2] / 10.0,
  151. }
  152. async def _lock_unlock(
  153. self, command: str, ignore_statuses: set[LockStatus]
  154. ) -> bool:
  155. status = self.get_lock_status()
  156. if status is None:
  157. await self.update()
  158. status = self.get_lock_status()
  159. if status in ignore_statuses:
  160. return True
  161. await self._enable_notifications()
  162. result = await self._send_command(command)
  163. status = self._check_command_result(result, 0, {1})
  164. # Also update the battery and firmware version
  165. if basic_data := await self._get_basic_info():
  166. self._last_full_update = time.monotonic()
  167. self._update_parsed_data(self._parse_basic_data(basic_data))
  168. self._fire_callbacks()
  169. return status
  170. async def get_basic_info(self) -> dict[str, Any] | None:
  171. """Get device basic status."""
  172. lock_raw_data = await self._get_lock_info()
  173. if not lock_raw_data:
  174. return None
  175. basic_data = await self._get_basic_info()
  176. if not basic_data:
  177. return None
  178. return self._parse_lock_data(lock_raw_data[1:]) | self._parse_basic_data(
  179. basic_data
  180. )
  181. def is_calibrated(self) -> Any:
  182. """Return True if lock is calibrated."""
  183. return self._get_adv_value("calibration")
  184. def get_lock_status(self) -> LockStatus:
  185. """Return lock status."""
  186. return self._get_adv_value("status")
  187. def is_door_open(self) -> bool:
  188. """Return True if door is open."""
  189. return self._get_adv_value("door_open")
  190. def is_unclosed_alarm_on(self) -> bool:
  191. """Return True if unclosed door alarm is on."""
  192. return self._get_adv_value("unclosed_alarm")
  193. def is_unlocked_alarm_on(self) -> bool:
  194. """Return True if lock unlocked alarm is on."""
  195. return self._get_adv_value("unlocked_alarm")
  196. def is_auto_lock_paused(self) -> bool:
  197. """Return True if auto lock is paused."""
  198. return self._get_adv_value("auto_lock_paused")
  199. async def _get_lock_info(self) -> bytes | None:
  200. """Return lock info of device."""
  201. _data = await self._send_command(key=COMMAND_LOCK_INFO, retry=self._retry_count)
  202. if not self._check_command_result(_data, 0, {1}):
  203. _LOGGER.error("Unsuccessful, please try again")
  204. return None
  205. return _data
  206. async def _enable_notifications(self) -> bool:
  207. if self._notifications_enabled:
  208. return True
  209. result = await self._send_command(COMMAND_ENABLE_NOTIFICATIONS)
  210. if self._check_command_result(result, 0, {1}):
  211. self._notifications_enabled = True
  212. return self._notifications_enabled
  213. async def _disable_notifications(self) -> bool:
  214. if not self._notifications_enabled:
  215. return True
  216. result = await self._send_command(COMMAND_DISABLE_NOTIFICATIONS)
  217. if self._check_command_result(result, 0, {1}):
  218. self._notifications_enabled = False
  219. return not self._notifications_enabled
  220. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  221. if self._notifications_enabled and self._check_command_result(data, 0, {0xF}):
  222. self._update_lock_status(data)
  223. else:
  224. super()._notification_handler(_sender, data)
  225. def _update_lock_status(self, data: bytearray) -> None:
  226. lock_data = self._parse_lock_data(self._decrypt(data[4:]))
  227. if self._update_parsed_data(lock_data):
  228. # We leave notifications enabled in case
  229. # the lock is operated manually before we
  230. # disconnect.
  231. self._reset_disconnect_timer()
  232. self._fire_callbacks()
  233. @staticmethod
  234. def _parse_lock_data(data: bytes) -> dict[str, Any]:
  235. return {
  236. "calibration": bool(data[0] & 0b10000000),
  237. "status": LockStatus((data[0] & 0b01110000) >> 4),
  238. "door_open": bool(data[0] & 0b00000100),
  239. "unclosed_alarm": bool(data[1] & 0b00100000),
  240. "unlocked_alarm": bool(data[1] & 0b00010000),
  241. }
  242. async def _send_command(
  243. self, key: str, retry: int | None = None, encrypt: bool = True
  244. ) -> bytes | None:
  245. if not encrypt:
  246. return await super()._send_command(key[:2] + "000000" + key[2:], retry)
  247. result = await self._ensure_encryption_initialized()
  248. if not result:
  249. _LOGGER.error("Failed to initialize encryption")
  250. return None
  251. encrypted = (
  252. key[:2] + self._key_id + self._iv[0:2].hex() + self._encrypt(key[2:])
  253. )
  254. result = await super()._send_command(encrypted, retry)
  255. return result[:1] + self._decrypt(result[4:])
  256. async def _ensure_encryption_initialized(self) -> bool:
  257. if self._iv is not None:
  258. return True
  259. result = await self._send_command(
  260. COMMAND_GET_CK_IV + self._key_id, encrypt=False
  261. )
  262. ok = self._check_command_result(result, 0, {0x01})
  263. if ok:
  264. self._iv = result[4:]
  265. return ok
  266. async def _execute_disconnect(self) -> None:
  267. await super()._execute_disconnect()
  268. self._iv = None
  269. self._cipher = None
  270. self._notifications_enabled = False
  271. def _get_cipher(self) -> Cipher:
  272. if self._cipher is None:
  273. self._cipher = Cipher(
  274. algorithms.AES128(self._encryption_key), modes.CTR(self._iv)
  275. )
  276. return self._cipher
  277. def _encrypt(self, data: str) -> str:
  278. if len(data) == 0:
  279. return ""
  280. encryptor = self._get_cipher().encryptor()
  281. return (encryptor.update(bytearray.fromhex(data)) + encryptor.finalize()).hex()
  282. def _decrypt(self, data: bytearray) -> bytes:
  283. if len(data) == 0:
  284. return b""
  285. decryptor = self._get_cipher().decryptor()
  286. return decryptor.update(data) + decryptor.finalize()