1
0

lock.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. """Library to handle connection with Switchbot Lock."""
  2. from __future__ import annotations
  3. import asyncio
  4. import logging
  5. import time
  6. from typing import Any
  7. import aiohttp
  8. from bleak.backends.device import BLEDevice
  9. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  10. from ..api_config import SWITCHBOT_APP_API_BASE_URL, SWITCHBOT_APP_CLIENT_ID
  11. from ..const import (
  12. LockStatus,
  13. SwitchbotAccountConnectionError,
  14. SwitchbotApiError,
  15. SwitchbotAuthenticationError,
  16. )
  17. from .device import SwitchbotDevice, SwitchbotOperationError
  18. COMMAND_HEADER = "57"
  19. COMMAND_GET_CK_IV = f"{COMMAND_HEADER}0f2103"
  20. COMMAND_LOCK_INFO = f"{COMMAND_HEADER}0f4f8101"
  21. COMMAND_UNLOCK = f"{COMMAND_HEADER}0f4e01011080"
  22. COMMAND_UNLOCK_WITHOUT_UNLATCH = f"{COMMAND_HEADER}0f4e010110a0"
  23. COMMAND_LOCK = f"{COMMAND_HEADER}0f4e01011000"
  24. COMMAND_ENABLE_NOTIFICATIONS = f"{COMMAND_HEADER}0e01001e00008101"
  25. COMMAND_DISABLE_NOTIFICATIONS = f"{COMMAND_HEADER}0e00"
  26. MOVING_STATUSES = {LockStatus.LOCKING, LockStatus.UNLOCKING}
  27. BLOCKED_STATUSES = {LockStatus.LOCKING_STOP, LockStatus.UNLOCKING_STOP}
  28. REST_STATUSES = {LockStatus.LOCKED, LockStatus.UNLOCKED, LockStatus.NOT_FULLY_LOCKED}
  29. _LOGGER = logging.getLogger(__name__)
  30. COMMAND_RESULT_EXPECTED_VALUES = {1, 6}
  31. # The return value of the command is 1 when the command is successful.
  32. # The return value of the command is 6 when the command is successful but the battery is low.
  33. class SwitchbotLock(SwitchbotDevice):
  34. """Representation of a Switchbot Lock."""
  35. def __init__(
  36. self,
  37. device: BLEDevice,
  38. key_id: str,
  39. encryption_key: str,
  40. interface: int = 0,
  41. **kwargs: Any,
  42. ) -> None:
  43. if len(key_id) == 0:
  44. raise ValueError("key_id is missing")
  45. elif len(key_id) != 2:
  46. raise ValueError("key_id is invalid")
  47. if len(encryption_key) == 0:
  48. raise ValueError("encryption_key is missing")
  49. elif len(encryption_key) != 32:
  50. raise ValueError("encryption_key is invalid")
  51. self._iv = None
  52. self._cipher = None
  53. self._key_id = key_id
  54. self._encryption_key = bytearray.fromhex(encryption_key)
  55. self._notifications_enabled: bool = False
  56. super().__init__(device, None, interface, **kwargs)
  57. @staticmethod
  58. async def verify_encryption_key(
  59. device: BLEDevice, key_id: str, encryption_key: str
  60. ) -> bool:
  61. try:
  62. lock = SwitchbotLock(
  63. device=device, key_id=key_id, encryption_key=encryption_key
  64. )
  65. except ValueError:
  66. return False
  67. try:
  68. lock_info = await lock.get_basic_info()
  69. except SwitchbotOperationError:
  70. return False
  71. return lock_info is not None
  72. @staticmethod
  73. async def api_request(
  74. session: aiohttp.ClientSession,
  75. subdomain: str,
  76. path: str,
  77. data: dict = None,
  78. headers: dict = None,
  79. ) -> dict:
  80. url = f"https://{subdomain}.{SWITCHBOT_APP_API_BASE_URL}/{path}"
  81. async with session.post(url, json=data, headers=headers) as result:
  82. if result.status > 299:
  83. raise SwitchbotApiError(
  84. f"Unexpected status code returned by SwitchBot API: {result.status}"
  85. )
  86. response = await result.json()
  87. if response["statusCode"] != 100:
  88. raise SwitchbotApiError(
  89. f"{response['message']}, status code: {response['statusCode']}"
  90. )
  91. return response["body"]
  92. # Old non-async method preserved for backwards compatibility
  93. @staticmethod
  94. def retrieve_encryption_key(device_mac: str, username: str, password: str):
  95. async def async_fn():
  96. async with aiohttp.ClientSession() as session:
  97. return await SwitchbotLock.async_retrieve_encryption_key(
  98. session, device_mac, username, password
  99. )
  100. return asyncio.run(async_fn())
  101. @staticmethod
  102. async def async_retrieve_encryption_key(
  103. session: aiohttp.ClientSession, device_mac: str, username: str, password: str
  104. ) -> dict:
  105. """Retrieve lock key from internal SwitchBot API."""
  106. device_mac = device_mac.replace(":", "").replace("-", "").upper()
  107. try:
  108. auth_result = await SwitchbotLock.api_request(
  109. session,
  110. "account",
  111. "account/api/v1/user/login",
  112. {
  113. "clientId": SWITCHBOT_APP_CLIENT_ID,
  114. "username": username,
  115. "password": password,
  116. "grantType": "password",
  117. "verifyCode": "",
  118. },
  119. )
  120. auth_headers = {"authorization": auth_result["access_token"]}
  121. except Exception as err:
  122. raise SwitchbotAuthenticationError(f"Authentication failed: {err}") from err
  123. try:
  124. userinfo = await SwitchbotLock.api_request(
  125. session, "account", "account/api/v1/user/userinfo", {}, auth_headers
  126. )
  127. if "botRegion" in userinfo and userinfo["botRegion"] != "":
  128. region = userinfo["botRegion"]
  129. else:
  130. region = "us"
  131. except Exception as err:
  132. raise SwitchbotAccountConnectionError(
  133. f"Failed to retrieve SwitchBot Account user details: {err}"
  134. ) from err
  135. try:
  136. device_info = await SwitchbotLock.api_request(
  137. session,
  138. f"wonderlabs.{region}",
  139. "wonder/keys/v1/communicate",
  140. {
  141. "device_mac": device_mac,
  142. "keyType": "user",
  143. },
  144. auth_headers,
  145. )
  146. return {
  147. "key_id": device_info["communicationKey"]["keyId"],
  148. "encryption_key": device_info["communicationKey"]["key"],
  149. }
  150. except Exception as err:
  151. raise SwitchbotAccountConnectionError(
  152. f"Failed to retrieve encryption key from SwitchBot Account: {err}"
  153. ) from err
  154. async def lock(self) -> bool:
  155. """Send lock command."""
  156. return await self._lock_unlock(
  157. COMMAND_LOCK, {LockStatus.LOCKED, LockStatus.LOCKING}
  158. )
  159. async def unlock(self) -> bool:
  160. """Send unlock command. If unlatch feature is enabled in EU firmware, also unlatches door"""
  161. return await self._lock_unlock(
  162. COMMAND_UNLOCK, {LockStatus.UNLOCKED, LockStatus.UNLOCKING}
  163. )
  164. async def unlock_without_unlatch(self) -> bool:
  165. """Send unlock command. This command will not unlatch the door."""
  166. return await self._lock_unlock(
  167. COMMAND_UNLOCK_WITHOUT_UNLATCH,
  168. {LockStatus.UNLOCKED, LockStatus.UNLOCKING, LockStatus.NOT_FULLY_LOCKED},
  169. )
  170. def _parse_basic_data(self, basic_data: bytes) -> dict[str, Any]:
  171. """Parse basic data from lock."""
  172. return {
  173. "battery": basic_data[1],
  174. "firmware": basic_data[2] / 10.0,
  175. }
  176. async def _lock_unlock(
  177. self, command: str, ignore_statuses: set[LockStatus]
  178. ) -> bool:
  179. status = self.get_lock_status()
  180. if status is None:
  181. await self.update()
  182. status = self.get_lock_status()
  183. if status in ignore_statuses:
  184. return True
  185. await self._enable_notifications()
  186. result = await self._send_command(command)
  187. status = self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES)
  188. # Also update the battery and firmware version
  189. if basic_data := await self._get_basic_info():
  190. self._last_full_update = time.monotonic()
  191. if len(basic_data) >= 3:
  192. self._update_parsed_data(self._parse_basic_data(basic_data))
  193. else:
  194. _LOGGER.warning("Invalid basic data received: %s", basic_data)
  195. self._fire_callbacks()
  196. return status
  197. async def get_basic_info(self) -> dict[str, Any] | None:
  198. """Get device basic status."""
  199. lock_raw_data = await self._get_lock_info()
  200. if not lock_raw_data:
  201. return None
  202. basic_data = await self._get_basic_info()
  203. if not basic_data:
  204. return None
  205. return self._parse_lock_data(lock_raw_data[1:]) | self._parse_basic_data(
  206. basic_data
  207. )
  208. def is_calibrated(self) -> Any:
  209. """Return True if lock is calibrated."""
  210. return self._get_adv_value("calibration")
  211. def get_lock_status(self) -> LockStatus:
  212. """Return lock status."""
  213. return self._get_adv_value("status")
  214. def is_door_open(self) -> bool:
  215. """Return True if door is open."""
  216. return self._get_adv_value("door_open")
  217. def is_unclosed_alarm_on(self) -> bool:
  218. """Return True if unclosed door alarm is on."""
  219. return self._get_adv_value("unclosed_alarm")
  220. def is_unlocked_alarm_on(self) -> bool:
  221. """Return True if lock unlocked alarm is on."""
  222. return self._get_adv_value("unlocked_alarm")
  223. def is_auto_lock_paused(self) -> bool:
  224. """Return True if auto lock is paused."""
  225. return self._get_adv_value("auto_lock_paused")
  226. def is_night_latch_enabled(self) -> bool:
  227. """Return True if Night Latch is enabled on EU firmware."""
  228. return self._get_adv_value("night_latch")
  229. async def _get_lock_info(self) -> bytes | None:
  230. """Return lock info of device."""
  231. _data = await self._send_command(key=COMMAND_LOCK_INFO, retry=self._retry_count)
  232. if not self._check_command_result(_data, 0, COMMAND_RESULT_EXPECTED_VALUES):
  233. _LOGGER.error("Unsuccessful, please try again")
  234. return None
  235. return _data
  236. async def _enable_notifications(self) -> bool:
  237. if self._notifications_enabled:
  238. return True
  239. result = await self._send_command(COMMAND_ENABLE_NOTIFICATIONS)
  240. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  241. self._notifications_enabled = True
  242. return self._notifications_enabled
  243. async def _disable_notifications(self) -> bool:
  244. if not self._notifications_enabled:
  245. return True
  246. result = await self._send_command(COMMAND_DISABLE_NOTIFICATIONS)
  247. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  248. self._notifications_enabled = False
  249. return not self._notifications_enabled
  250. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  251. if self._notifications_enabled and self._check_command_result(data, 0, {0xF}):
  252. self._update_lock_status(data)
  253. else:
  254. super()._notification_handler(_sender, data)
  255. def _update_lock_status(self, data: bytearray) -> None:
  256. lock_data = self._parse_lock_data(self._decrypt(data[4:]))
  257. if self._update_parsed_data(lock_data):
  258. # We leave notifications enabled in case
  259. # the lock is operated manually before we
  260. # disconnect.
  261. self._reset_disconnect_timer()
  262. self._fire_callbacks()
  263. @staticmethod
  264. def _parse_lock_data(data: bytes) -> dict[str, Any]:
  265. return {
  266. "calibration": bool(data[0] & 0b10000000),
  267. "status": LockStatus((data[0] & 0b01110000) >> 4),
  268. "door_open": bool(data[0] & 0b00000100),
  269. "unclosed_alarm": bool(data[1] & 0b00100000),
  270. "unlocked_alarm": bool(data[1] & 0b00010000),
  271. }
  272. async def _send_command(
  273. self, key: str, retry: int | None = None, encrypt: bool = True
  274. ) -> bytes | None:
  275. if not encrypt:
  276. return await super()._send_command(key[:2] + "000000" + key[2:], retry)
  277. result = await self._ensure_encryption_initialized()
  278. if not result:
  279. _LOGGER.error("Failed to initialize encryption")
  280. return None
  281. encrypted = (
  282. key[:2] + self._key_id + self._iv[0:2].hex() + self._encrypt(key[2:])
  283. )
  284. result = await super()._send_command(encrypted, retry)
  285. return result[:1] + self._decrypt(result[4:])
  286. async def _ensure_encryption_initialized(self) -> bool:
  287. if self._iv is not None:
  288. return True
  289. result = await self._send_command(
  290. COMMAND_GET_CK_IV + self._key_id, encrypt=False
  291. )
  292. ok = self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES)
  293. if ok:
  294. self._iv = result[4:]
  295. return ok
  296. async def _execute_disconnect(self) -> None:
  297. await super()._execute_disconnect()
  298. self._iv = None
  299. self._cipher = None
  300. self._notifications_enabled = False
  301. def _get_cipher(self) -> Cipher:
  302. if self._cipher is None:
  303. self._cipher = Cipher(
  304. algorithms.AES128(self._encryption_key), modes.CTR(self._iv)
  305. )
  306. return self._cipher
  307. def _encrypt(self, data: str) -> str:
  308. if len(data) == 0:
  309. return ""
  310. encryptor = self._get_cipher().encryptor()
  311. return (encryptor.update(bytearray.fromhex(data)) + encryptor.finalize()).hex()
  312. def _decrypt(self, data: bytearray) -> bytes:
  313. if len(data) == 0:
  314. return b""
  315. decryptor = self._get_cipher().decryptor()
  316. return decryptor.update(data) + decryptor.finalize()