lock.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. self._update_parsed_data(self._parse_basic_data(basic_data))
  173. self._fire_callbacks()
  174. return status
  175. async def get_basic_info(self) -> dict[str, Any] | None:
  176. """Get device basic status."""
  177. lock_raw_data = await self._get_lock_info()
  178. if not lock_raw_data:
  179. return None
  180. basic_data = await self._get_basic_info()
  181. if not basic_data:
  182. return None
  183. return self._parse_lock_data(lock_raw_data[1:]) | self._parse_basic_data(
  184. basic_data
  185. )
  186. def is_calibrated(self) -> Any:
  187. """Return True if lock is calibrated."""
  188. return self._get_adv_value("calibration")
  189. def get_lock_status(self) -> LockStatus:
  190. """Return lock status."""
  191. return self._get_adv_value("status")
  192. def is_door_open(self) -> bool:
  193. """Return True if door is open."""
  194. return self._get_adv_value("door_open")
  195. def is_unclosed_alarm_on(self) -> bool:
  196. """Return True if unclosed door alarm is on."""
  197. return self._get_adv_value("unclosed_alarm")
  198. def is_unlocked_alarm_on(self) -> bool:
  199. """Return True if lock unlocked alarm is on."""
  200. return self._get_adv_value("unlocked_alarm")
  201. def is_auto_lock_paused(self) -> bool:
  202. """Return True if auto lock is paused."""
  203. return self._get_adv_value("auto_lock_paused")
  204. async def _get_lock_info(self) -> bytes | None:
  205. """Return lock info of device."""
  206. _data = await self._send_command(key=COMMAND_LOCK_INFO, retry=self._retry_count)
  207. if not self._check_command_result(_data, 0, COMMAND_RESULT_EXPECTED_VALUES):
  208. _LOGGER.error("Unsuccessful, please try again")
  209. return None
  210. return _data
  211. async def _enable_notifications(self) -> bool:
  212. if self._notifications_enabled:
  213. return True
  214. result = await self._send_command(COMMAND_ENABLE_NOTIFICATIONS)
  215. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  216. self._notifications_enabled = True
  217. return self._notifications_enabled
  218. async def _disable_notifications(self) -> bool:
  219. if not self._notifications_enabled:
  220. return True
  221. result = await self._send_command(COMMAND_DISABLE_NOTIFICATIONS)
  222. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  223. self._notifications_enabled = False
  224. return not self._notifications_enabled
  225. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  226. if self._notifications_enabled and self._check_command_result(data, 0, {0xF}):
  227. self._update_lock_status(data)
  228. else:
  229. super()._notification_handler(_sender, data)
  230. def _update_lock_status(self, data: bytearray) -> None:
  231. lock_data = self._parse_lock_data(self._decrypt(data[4:]))
  232. if self._update_parsed_data(lock_data):
  233. # We leave notifications enabled in case
  234. # the lock is operated manually before we
  235. # disconnect.
  236. self._reset_disconnect_timer()
  237. self._fire_callbacks()
  238. @staticmethod
  239. def _parse_lock_data(data: bytes) -> dict[str, Any]:
  240. return {
  241. "calibration": bool(data[0] & 0b10000000),
  242. "status": LockStatus((data[0] & 0b01110000) >> 4),
  243. "door_open": bool(data[0] & 0b00000100),
  244. "unclosed_alarm": bool(data[1] & 0b00100000),
  245. "unlocked_alarm": bool(data[1] & 0b00010000),
  246. }
  247. async def _send_command(
  248. self, key: str, retry: int | None = None, encrypt: bool = True
  249. ) -> bytes | None:
  250. if not encrypt:
  251. return await super()._send_command(key[:2] + "000000" + key[2:], retry)
  252. result = await self._ensure_encryption_initialized()
  253. if not result:
  254. _LOGGER.error("Failed to initialize encryption")
  255. return None
  256. encrypted = (
  257. key[:2] + self._key_id + self._iv[0:2].hex() + self._encrypt(key[2:])
  258. )
  259. result = await super()._send_command(encrypted, retry)
  260. return result[:1] + self._decrypt(result[4:])
  261. async def _ensure_encryption_initialized(self) -> bool:
  262. if self._iv is not None:
  263. return True
  264. result = await self._send_command(
  265. COMMAND_GET_CK_IV + self._key_id, encrypt=False
  266. )
  267. ok = self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES)
  268. if ok:
  269. self._iv = result[4:]
  270. return ok
  271. async def _execute_disconnect(self) -> None:
  272. await super()._execute_disconnect()
  273. self._iv = None
  274. self._cipher = None
  275. self._notifications_enabled = False
  276. def _get_cipher(self) -> Cipher:
  277. if self._cipher is None:
  278. self._cipher = Cipher(
  279. algorithms.AES128(self._encryption_key), modes.CTR(self._iv)
  280. )
  281. return self._cipher
  282. def _encrypt(self, data: str) -> str:
  283. if len(data) == 0:
  284. return ""
  285. encryptor = self._get_cipher().encryptor()
  286. return (encryptor.update(bytearray.fromhex(data)) + encryptor.finalize()).hex()
  287. def _decrypt(self, data: bytearray) -> bytes:
  288. if len(data) == 0:
  289. return b""
  290. decryptor = self._get_cipher().decryptor()
  291. return decryptor.update(data) + decryptor.finalize()