1
0

lock.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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(
  82. url,
  83. json=data,
  84. headers=headers,
  85. timeout=aiohttp.ClientTimeout(total=10),
  86. ) as result:
  87. if result.status > 299:
  88. raise SwitchbotApiError(
  89. f"Unexpected status code returned by SwitchBot API: {result.status}"
  90. )
  91. response = await result.json()
  92. if response["statusCode"] != 100:
  93. raise SwitchbotApiError(
  94. f"{response['message']}, status code: {response['statusCode']}"
  95. )
  96. return response["body"]
  97. # Old non-async method preserved for backwards compatibility
  98. @staticmethod
  99. def retrieve_encryption_key(device_mac: str, username: str, password: str):
  100. async def async_fn():
  101. async with aiohttp.ClientSession() as session:
  102. return await SwitchbotLock.async_retrieve_encryption_key(
  103. session, device_mac, username, password
  104. )
  105. return asyncio.run(async_fn())
  106. @staticmethod
  107. async def async_retrieve_encryption_key(
  108. session: aiohttp.ClientSession, device_mac: str, username: str, password: str
  109. ) -> dict:
  110. """Retrieve lock key from internal SwitchBot API."""
  111. device_mac = device_mac.replace(":", "").replace("-", "").upper()
  112. try:
  113. auth_result = await SwitchbotLock.api_request(
  114. session,
  115. "account",
  116. "account/api/v1/user/login",
  117. {
  118. "clientId": SWITCHBOT_APP_CLIENT_ID,
  119. "username": username,
  120. "password": password,
  121. "grantType": "password",
  122. "verifyCode": "",
  123. },
  124. )
  125. auth_headers = {"authorization": auth_result["access_token"]}
  126. except Exception as err:
  127. raise SwitchbotAuthenticationError(f"Authentication failed: {err}") from err
  128. try:
  129. userinfo = await SwitchbotLock.api_request(
  130. session, "account", "account/api/v1/user/userinfo", {}, auth_headers
  131. )
  132. if "botRegion" in userinfo and userinfo["botRegion"] != "":
  133. region = userinfo["botRegion"]
  134. else:
  135. region = "us"
  136. except Exception as err:
  137. raise SwitchbotAccountConnectionError(
  138. f"Failed to retrieve SwitchBot Account user details: {err}"
  139. ) from err
  140. try:
  141. device_info = await SwitchbotLock.api_request(
  142. session,
  143. f"wonderlabs.{region}",
  144. "wonder/keys/v1/communicate",
  145. {
  146. "device_mac": device_mac,
  147. "keyType": "user",
  148. },
  149. auth_headers,
  150. )
  151. return {
  152. "key_id": device_info["communicationKey"]["keyId"],
  153. "encryption_key": device_info["communicationKey"]["key"],
  154. }
  155. except Exception as err:
  156. raise SwitchbotAccountConnectionError(
  157. f"Failed to retrieve encryption key from SwitchBot Account: {err}"
  158. ) from err
  159. async def lock(self) -> bool:
  160. """Send lock command."""
  161. return await self._lock_unlock(
  162. COMMAND_LOCK, {LockStatus.LOCKED, LockStatus.LOCKING}
  163. )
  164. async def unlock(self) -> bool:
  165. """Send unlock command. If unlatch feature is enabled in EU firmware, also unlatches door"""
  166. return await self._lock_unlock(
  167. COMMAND_UNLOCK, {LockStatus.UNLOCKED, LockStatus.UNLOCKING}
  168. )
  169. async def unlock_without_unlatch(self) -> bool:
  170. """Send unlock command. This command will not unlatch the door."""
  171. return await self._lock_unlock(
  172. COMMAND_UNLOCK_WITHOUT_UNLATCH,
  173. {LockStatus.UNLOCKED, LockStatus.UNLOCKING, LockStatus.NOT_FULLY_LOCKED},
  174. )
  175. def _parse_basic_data(self, basic_data: bytes) -> dict[str, Any]:
  176. """Parse basic data from lock."""
  177. return {
  178. "battery": basic_data[1],
  179. "firmware": basic_data[2] / 10.0,
  180. }
  181. async def _lock_unlock(
  182. self, command: str, ignore_statuses: set[LockStatus]
  183. ) -> bool:
  184. status = self.get_lock_status()
  185. if status is None:
  186. await self.update()
  187. status = self.get_lock_status()
  188. if status in ignore_statuses:
  189. return True
  190. await self._enable_notifications()
  191. result = await self._send_command(command)
  192. status = self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES)
  193. # Also update the battery and firmware version
  194. if basic_data := await self._get_basic_info():
  195. self._last_full_update = time.monotonic()
  196. if len(basic_data) >= 3:
  197. self._update_parsed_data(self._parse_basic_data(basic_data))
  198. else:
  199. _LOGGER.warning("Invalid basic data received: %s", basic_data)
  200. self._fire_callbacks()
  201. return status
  202. async def get_basic_info(self) -> dict[str, Any] | None:
  203. """Get device basic status."""
  204. lock_raw_data = await self._get_lock_info()
  205. if not lock_raw_data:
  206. return None
  207. basic_data = await self._get_basic_info()
  208. if not basic_data:
  209. return None
  210. return self._parse_lock_data(lock_raw_data[1:]) | self._parse_basic_data(
  211. basic_data
  212. )
  213. def is_calibrated(self) -> Any:
  214. """Return True if lock is calibrated."""
  215. return self._get_adv_value("calibration")
  216. def get_lock_status(self) -> LockStatus:
  217. """Return lock status."""
  218. return self._get_adv_value("status")
  219. def is_door_open(self) -> bool:
  220. """Return True if door is open."""
  221. return self._get_adv_value("door_open")
  222. def is_unclosed_alarm_on(self) -> bool:
  223. """Return True if unclosed door alarm is on."""
  224. return self._get_adv_value("unclosed_alarm")
  225. def is_unlocked_alarm_on(self) -> bool:
  226. """Return True if lock unlocked alarm is on."""
  227. return self._get_adv_value("unlocked_alarm")
  228. def is_auto_lock_paused(self) -> bool:
  229. """Return True if auto lock is paused."""
  230. return self._get_adv_value("auto_lock_paused")
  231. def is_night_latch_enabled(self) -> bool:
  232. """Return True if Night Latch is enabled on EU firmware."""
  233. return self._get_adv_value("night_latch")
  234. async def _get_lock_info(self) -> bytes | None:
  235. """Return lock info of device."""
  236. _data = await self._send_command(key=COMMAND_LOCK_INFO, retry=self._retry_count)
  237. if not self._check_command_result(_data, 0, COMMAND_RESULT_EXPECTED_VALUES):
  238. _LOGGER.error("Unsuccessful, please try again")
  239. return None
  240. return _data
  241. async def _enable_notifications(self) -> bool:
  242. if self._notifications_enabled:
  243. return True
  244. result = await self._send_command(COMMAND_ENABLE_NOTIFICATIONS)
  245. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  246. self._notifications_enabled = True
  247. return self._notifications_enabled
  248. async def _disable_notifications(self) -> bool:
  249. if not self._notifications_enabled:
  250. return True
  251. result = await self._send_command(COMMAND_DISABLE_NOTIFICATIONS)
  252. if self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES):
  253. self._notifications_enabled = False
  254. return not self._notifications_enabled
  255. def _notification_handler(self, _sender: int, data: bytearray) -> None:
  256. if self._notifications_enabled and self._check_command_result(data, 0, {0xF}):
  257. self._update_lock_status(data)
  258. else:
  259. super()._notification_handler(_sender, data)
  260. def _update_lock_status(self, data: bytearray) -> None:
  261. lock_data = self._parse_lock_data(self._decrypt(data[4:]))
  262. if self._update_parsed_data(lock_data):
  263. # We leave notifications enabled in case
  264. # the lock is operated manually before we
  265. # disconnect.
  266. self._reset_disconnect_timer()
  267. self._fire_callbacks()
  268. @staticmethod
  269. def _parse_lock_data(data: bytes) -> dict[str, Any]:
  270. return {
  271. "calibration": bool(data[0] & 0b10000000),
  272. "status": LockStatus((data[0] & 0b01110000) >> 4),
  273. "door_open": bool(data[0] & 0b00000100),
  274. "unclosed_alarm": bool(data[1] & 0b00100000),
  275. "unlocked_alarm": bool(data[1] & 0b00010000),
  276. }
  277. async def _send_command(
  278. self, key: str, retry: int | None = None, encrypt: bool = True
  279. ) -> bytes | None:
  280. if not encrypt:
  281. return await super()._send_command(key[:2] + "000000" + key[2:], retry)
  282. result = await self._ensure_encryption_initialized()
  283. if not result:
  284. _LOGGER.error("Failed to initialize encryption")
  285. return None
  286. encrypted = (
  287. key[:2] + self._key_id + self._iv[0:2].hex() + self._encrypt(key[2:])
  288. )
  289. result = await super()._send_command(encrypted, retry)
  290. return result[:1] + self._decrypt(result[4:])
  291. async def _ensure_encryption_initialized(self) -> bool:
  292. if self._iv is not None:
  293. return True
  294. result = await self._send_command(
  295. COMMAND_GET_CK_IV + self._key_id, encrypt=False
  296. )
  297. ok = self._check_command_result(result, 0, COMMAND_RESULT_EXPECTED_VALUES)
  298. if ok:
  299. self._iv = result[4:]
  300. return ok
  301. async def _execute_disconnect(self) -> None:
  302. await super()._execute_disconnect()
  303. self._iv = None
  304. self._cipher = None
  305. self._notifications_enabled = False
  306. def _get_cipher(self) -> Cipher:
  307. if self._cipher is None:
  308. self._cipher = Cipher(
  309. algorithms.AES128(self._encryption_key), modes.CTR(self._iv)
  310. )
  311. return self._cipher
  312. def _encrypt(self, data: str) -> str:
  313. if len(data) == 0:
  314. return ""
  315. encryptor = self._get_cipher().encryptor()
  316. return (encryptor.update(bytearray.fromhex(data)) + encryptor.finalize()).hex()
  317. def _decrypt(self, data: bytearray) -> bytes:
  318. if len(data) == 0:
  319. return b""
  320. decryptor = self._get_cipher().decryptor()
  321. return decryptor.update(data) + decryptor.finalize()