lock.py 11 KB

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