device.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. """Library to handle connection with Switchbot."""
  2. from __future__ import annotations
  3. import asyncio
  4. import binascii
  5. import logging
  6. from enum import Enum
  7. from typing import Any, Callable
  8. from uuid import UUID
  9. import async_timeout
  10. from bleak import BleakError
  11. from bleak.backends.device import BLEDevice
  12. from bleak.backends.service import BleakGATTCharacteristic, BleakGATTServiceCollection
  13. from bleak.exc import BleakDBusError
  14. from bleak_retry_connector import (
  15. BleakClientWithServiceCache,
  16. BleakNotFoundError,
  17. ble_device_has_changed,
  18. establish_connection,
  19. )
  20. from ..const import DEFAULT_RETRY_COUNT, DEFAULT_SCAN_TIMEOUT
  21. from ..discovery import GetSwitchbotDevices
  22. from ..models import SwitchBotAdvertisement
  23. _LOGGER = logging.getLogger(__name__)
  24. REQ_HEADER = "570f"
  25. # Keys common to all device types
  26. DEVICE_GET_BASIC_SETTINGS_KEY = "5702"
  27. DEVICE_SET_MODE_KEY = "5703"
  28. DEVICE_SET_EXTENDED_KEY = REQ_HEADER
  29. # Base key when encryption is set
  30. KEY_PASSWORD_PREFIX = "571"
  31. BLEAK_EXCEPTIONS = (
  32. AttributeError,
  33. BleakError,
  34. EOFError,
  35. asyncio.exceptions.TimeoutError,
  36. )
  37. # How long to hold the connection
  38. # to wait for additional commands for
  39. # disconnecting the device.
  40. DISCONNECT_DELAY = 49
  41. class ColorMode(Enum):
  42. OFF = 0
  43. COLOR_TEMP = 1
  44. RGB = 2
  45. EFFECT = 3
  46. class CharacteristicMissingError(Exception):
  47. """Raised when a characteristic is missing."""
  48. class SwitchbotOperationError(Exception):
  49. """Raised when an operation fails."""
  50. def _sb_uuid(comms_type: str = "service") -> UUID | str:
  51. """Return Switchbot UUID."""
  52. _uuid = {"tx": "002", "rx": "003", "service": "d00"}
  53. if comms_type in _uuid:
  54. return UUID(f"cba20{_uuid[comms_type]}-224d-11e6-9fb8-0002a5d5c51b")
  55. return "Incorrect type, choose between: tx, rx or service"
  56. READ_CHAR_UUID = _sb_uuid(comms_type="rx")
  57. WRITE_CHAR_UUID = _sb_uuid(comms_type="tx")
  58. class SwitchbotBaseDevice:
  59. """Base Representation of a Switchbot Device."""
  60. def __init__(
  61. self,
  62. device: BLEDevice,
  63. password: str | None = None,
  64. interface: int = 0,
  65. **kwargs: Any,
  66. ) -> None:
  67. """Switchbot base class constructor."""
  68. self._interface = f"hci{interface}"
  69. self._device = device
  70. self._sb_adv_data: SwitchBotAdvertisement | None = None
  71. self._override_adv_data: dict[str, Any] | None = None
  72. self._scan_timeout: int = kwargs.pop("scan_timeout", DEFAULT_SCAN_TIMEOUT)
  73. self._retry_count: int = kwargs.pop("retry_count", DEFAULT_RETRY_COUNT)
  74. self._connect_lock = asyncio.Lock()
  75. self._operation_lock = asyncio.Lock()
  76. if password is None or password == "":
  77. self._password_encoded = None
  78. else:
  79. self._password_encoded = "%08x" % (
  80. binascii.crc32(password.encode("ascii")) & 0xFFFFFFFF
  81. )
  82. self._client: BleakClientWithServiceCache | None = None
  83. self._read_char: BleakGATTCharacteristic | None = None
  84. self._write_char: BleakGATTCharacteristic | None = None
  85. self._disconnect_timer: asyncio.TimerHandle | None = None
  86. self._expected_disconnect = False
  87. self.loop = asyncio.get_event_loop()
  88. self._callbacks: list[Callable[[], None]] = []
  89. def advertisement_changed(self, advertisement: SwitchBotAdvertisement) -> bool:
  90. """Check if the advertisement has changed."""
  91. return bool(
  92. not self._sb_adv_data
  93. or ble_device_has_changed(self._sb_adv_data.device, advertisement.device)
  94. or advertisement.data != self._sb_adv_data.data
  95. )
  96. def _commandkey(self, key: str) -> str:
  97. """Add password to key if set."""
  98. if self._password_encoded is None:
  99. return key
  100. key_action = key[3]
  101. key_suffix = key[4:]
  102. return KEY_PASSWORD_PREFIX + key_action + self._password_encoded + key_suffix
  103. async def _send_command(self, key: str, retry: int | None = None) -> bytes | None:
  104. """Send command to device and read response."""
  105. if retry is None:
  106. retry = self._retry_count
  107. command = bytearray.fromhex(self._commandkey(key))
  108. _LOGGER.debug("%s: Sending command %s", self.name, command)
  109. if self._operation_lock.locked():
  110. _LOGGER.debug(
  111. "%s: Operation already in progress, waiting for it to complete; RSSI: %s",
  112. self.name,
  113. self.rssi,
  114. )
  115. max_attempts = retry + 1
  116. if self._operation_lock.locked():
  117. _LOGGER.debug(
  118. "%s: Operation already in progress, waiting for it to complete; RSSI: %s",
  119. self.name,
  120. self.rssi,
  121. )
  122. async with self._operation_lock:
  123. for attempt in range(max_attempts):
  124. try:
  125. return await self._send_command_locked(key, command)
  126. except BleakNotFoundError:
  127. _LOGGER.error(
  128. "%s: device not found, no longer in range, or poor RSSI: %s",
  129. self.name,
  130. self.rssi,
  131. exc_info=True,
  132. )
  133. raise
  134. except CharacteristicMissingError as ex:
  135. if attempt == retry:
  136. _LOGGER.error(
  137. "%s: characteristic missing: %s; Stopping trying; RSSI: %s",
  138. self.name,
  139. ex,
  140. self.rssi,
  141. exc_info=True,
  142. )
  143. raise
  144. _LOGGER.debug(
  145. "%s: characteristic missing: %s; RSSI: %s",
  146. self.name,
  147. ex,
  148. self.rssi,
  149. exc_info=True,
  150. )
  151. except BLEAK_EXCEPTIONS:
  152. if attempt == retry:
  153. _LOGGER.error(
  154. "%s: communication failed; Stopping trying; RSSI: %s",
  155. self.name,
  156. self.rssi,
  157. exc_info=True,
  158. )
  159. raise
  160. _LOGGER.debug(
  161. "%s: communication failed with:", self.name, exc_info=True
  162. )
  163. raise RuntimeError("Unreachable")
  164. @property
  165. def name(self) -> str:
  166. """Return device name."""
  167. return f"{self._device.name} ({self._device.address})"
  168. @property
  169. def rssi(self) -> int:
  170. """Return RSSI of device."""
  171. return self._get_adv_value("rssi") or self._device.rssi
  172. async def _ensure_connected(self):
  173. """Ensure connection to device is established."""
  174. if self._connect_lock.locked():
  175. _LOGGER.debug(
  176. "%s: Connection already in progress, waiting for it to complete; RSSI: %s",
  177. self.name,
  178. self.rssi,
  179. )
  180. if self._client and self._client.is_connected:
  181. self._reset_disconnect_timer()
  182. return
  183. async with self._connect_lock:
  184. # Check again while holding the lock
  185. if self._client and self._client.is_connected:
  186. self._reset_disconnect_timer()
  187. return
  188. _LOGGER.debug("%s: Connecting; RSSI: %s", self.name, self.rssi)
  189. client = await establish_connection(
  190. BleakClientWithServiceCache,
  191. self._device,
  192. self.name,
  193. self._disconnected,
  194. use_services_cache=True,
  195. ble_device_callback=lambda: self._device,
  196. )
  197. _LOGGER.debug("%s: Connected; RSSI: %s", self.name, self.rssi)
  198. resolved = self._resolve_characteristics(client.services)
  199. if not resolved:
  200. # Try to handle services failing to load
  201. resolved = self._resolve_characteristics(await client.get_services())
  202. self._client = client
  203. self._reset_disconnect_timer()
  204. def _resolve_characteristics(self, services: BleakGATTServiceCollection) -> bool:
  205. """Resolve characteristics."""
  206. self._read_char = services.get_characteristic(READ_CHAR_UUID)
  207. self._write_char = services.get_characteristic(WRITE_CHAR_UUID)
  208. return bool(self._read_char and self._write_char)
  209. def _reset_disconnect_timer(self):
  210. """Reset disconnect timer."""
  211. self._cancel_disconnect_timer()
  212. self._expected_disconnect = False
  213. self._disconnect_timer = self.loop.call_later(
  214. DISCONNECT_DELAY, self._disconnect
  215. )
  216. def _disconnected(self, client: BleakClientWithServiceCache) -> None:
  217. """Disconnected callback."""
  218. if self._expected_disconnect:
  219. _LOGGER.debug(
  220. "%s: Disconnected from device; RSSI: %s", self.name, self.rssi
  221. )
  222. return
  223. _LOGGER.warning(
  224. "%s: Device unexpectedly disconnected; RSSI: %s",
  225. self.name,
  226. self.rssi,
  227. )
  228. def _disconnect(self):
  229. """Disconnect from device."""
  230. self._cancel_disconnect_timer()
  231. asyncio.create_task(self._execute_timed_disconnect())
  232. def _cancel_disconnect_timer(self):
  233. """Cancel disconnect timer."""
  234. if self._disconnect_timer:
  235. self._disconnect_timer.cancel()
  236. self._disconnect_timer = None
  237. async def _execute_forced_disconnect(self) -> None:
  238. """Execute forced disconnection."""
  239. self._cancel_disconnect_timer()
  240. _LOGGER.debug(
  241. "%s: Executing forced disconnect",
  242. self.name,
  243. )
  244. await self._execute_disconnect()
  245. async def _execute_timed_disconnect(self) -> None:
  246. """Execute timed disconnection."""
  247. _LOGGER.debug(
  248. "%s: Executing timed disconnect after timeout of %s",
  249. self.name,
  250. DISCONNECT_DELAY,
  251. )
  252. await self._execute_disconnect()
  253. async def _execute_disconnect(self) -> None:
  254. """Execute disconnection."""
  255. async with self._connect_lock:
  256. if self._disconnect_timer: # If the timer was reset, don't disconnect
  257. return
  258. client = self._client
  259. self._expected_disconnect = True
  260. self._client = None
  261. self._read_char = None
  262. self._write_char = None
  263. if client and client.is_connected:
  264. _LOGGER.debug("%s: Disconnecting", self.name)
  265. await client.disconnect()
  266. _LOGGER.debug("%s: Disconnect completed", self.name)
  267. async def _send_command_locked(self, key: str, command: bytes) -> bytes:
  268. """Send command to device and read response."""
  269. await self._ensure_connected()
  270. try:
  271. return await self._execute_command_locked(key, command)
  272. except BleakDBusError as ex:
  273. # Disconnect so we can reset state and try again
  274. await asyncio.sleep(0.25)
  275. _LOGGER.debug(
  276. "%s: RSSI: %s; Backing off %ss; Disconnecting due to error: %s",
  277. self.name,
  278. self.rssi,
  279. 0.25,
  280. ex,
  281. )
  282. await self._execute_forced_disconnect()
  283. raise
  284. except BleakError as ex:
  285. # Disconnect so we can reset state and try again
  286. _LOGGER.debug(
  287. "%s: RSSI: %s; Disconnecting due to error: %s", self.name, self.rssi, ex
  288. )
  289. await self._execute_forced_disconnect()
  290. raise
  291. async def _execute_command_locked(self, key: str, command: bytes) -> bytes:
  292. """Execute command and read response."""
  293. assert self._client is not None
  294. if not self._read_char:
  295. raise CharacteristicMissingError(READ_CHAR_UUID)
  296. if not self._write_char:
  297. raise CharacteristicMissingError(WRITE_CHAR_UUID)
  298. future: asyncio.Future[bytearray] = asyncio.Future()
  299. client = self._client
  300. def _notification_handler(_sender: int, data: bytearray) -> None:
  301. """Handle notification responses."""
  302. if future.done():
  303. _LOGGER.debug("%s: Notification handler already done", self.name)
  304. return
  305. future.set_result(data)
  306. _LOGGER.debug("%s: Subscribe to notifications; RSSI: %s", self.name, self.rssi)
  307. await client.start_notify(self._read_char, _notification_handler)
  308. _LOGGER.debug("%s: Sending command: %s", self.name, key)
  309. await client.write_gatt_char(self._write_char, command, False)
  310. async with async_timeout.timeout(5):
  311. notify_msg = await future
  312. _LOGGER.debug("%s: Notification received: %s", self.name, notify_msg)
  313. _LOGGER.debug("%s: UnSubscribe to notifications", self.name)
  314. await client.stop_notify(self._read_char)
  315. if notify_msg == b"\x07":
  316. _LOGGER.error("Password required")
  317. elif notify_msg == b"\t":
  318. _LOGGER.error("Password incorrect")
  319. return notify_msg
  320. def get_address(self) -> str:
  321. """Return address of device."""
  322. return self._device.address
  323. def _get_adv_value(self, key: str) -> Any:
  324. """Return value from advertisement data."""
  325. if self._override_adv_data and key in self._override_adv_data:
  326. _LOGGER.debug(
  327. "%s: Using override value for %s: %s",
  328. self.name,
  329. key,
  330. self._override_adv_data[key],
  331. )
  332. return self._override_adv_data[key]
  333. if not self._sb_adv_data:
  334. return None
  335. return self._sb_adv_data.data["data"].get(key)
  336. def get_battery_percent(self) -> Any:
  337. """Return device battery level in percent."""
  338. return self._get_adv_value("battery")
  339. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  340. """Update device data from advertisement."""
  341. # Only accept advertisements if the data is not missing
  342. # if we already have an advertisement with data
  343. self._device = advertisement.device
  344. async def get_device_data(
  345. self, retry: int | None = None, interface: int | None = None
  346. ) -> SwitchBotAdvertisement | None:
  347. """Find switchbot devices and their advertisement data."""
  348. if retry is None:
  349. retry = self._retry_count
  350. if interface:
  351. _interface: int = interface
  352. else:
  353. _interface = int(self._interface.replace("hci", ""))
  354. _data = await GetSwitchbotDevices(interface=_interface).discover(
  355. retry=retry, scan_timeout=self._scan_timeout
  356. )
  357. if self._device.address in _data:
  358. self._sb_adv_data = _data[self._device.address]
  359. return self._sb_adv_data
  360. async def _get_basic_info(self) -> bytes | None:
  361. """Return basic info of device."""
  362. _data = await self._send_command(
  363. key=DEVICE_GET_BASIC_SETTINGS_KEY, retry=self._retry_count
  364. )
  365. if _data in (b"\x07", b"\x00"):
  366. _LOGGER.error("Unsuccessful, please try again")
  367. return None
  368. return _data
  369. def _fire_callbacks(self) -> None:
  370. """Fire callbacks."""
  371. _LOGGER.debug("%s: Fire callbacks", self.name)
  372. for callback in self._callbacks:
  373. callback()
  374. def subscribe(self, callback: Callable[[], None]) -> Callable[[], None]:
  375. """Subscribe to device notifications."""
  376. self._callbacks.append(callback)
  377. def _unsub() -> None:
  378. """Unsubscribe from device notifications."""
  379. self._callbacks.remove(callback)
  380. return _unsub
  381. async def update(self) -> None:
  382. """Update state of device."""
  383. def _check_command_result(
  384. self, result: bytes | None, index: int, values: set[int]
  385. ) -> bool:
  386. """Check command result."""
  387. if not result or len(result) - 1 < index:
  388. result_hex = result.hex() if result else "None"
  389. raise SwitchbotOperationError(
  390. f"{self.name}: Sending command failed (result={result_hex} index={index} expected={values} rssi={self.rssi})"
  391. )
  392. return result[index] in values
  393. def _set_advertisement_data(self, advertisement: SwitchBotAdvertisement) -> None:
  394. """Set advertisement data."""
  395. if advertisement.data.get("data") or not self._sb_adv_data.data.get("data"):
  396. self._sb_adv_data = advertisement
  397. self._override_adv_data = None
  398. def switch_mode(self) -> bool | None:
  399. """Return true or false from cache."""
  400. # To get actual position call update() first.
  401. return self._get_adv_value("switchMode")
  402. class SwitchbotDevice(SwitchbotBaseDevice):
  403. """Base Representation of a Switchbot Device.
  404. This base class consumes the advertisement data during connection. If the device
  405. sends stale advertisement data while connected, use
  406. SwitchbotDeviceOverrideStateDuringConnection instead.
  407. """
  408. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  409. """Update device data from advertisement."""
  410. super().update_from_advertisement(advertisement)
  411. self._set_advertisement_data(advertisement)
  412. class SwitchbotDeviceOverrideStateDuringConnection(SwitchbotBaseDevice):
  413. """Base Representation of a Switchbot Device.
  414. This base class ignores the advertisement data during connection and uses the
  415. data from the device instead.
  416. """
  417. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  418. super().update_from_advertisement(advertisement)
  419. if self._client and self._client.is_connected:
  420. # We do not consume the advertisement data if we are connected
  421. # to the device. This is because the advertisement data is not
  422. # updated when the device is connected for some devices.
  423. _LOGGER.debug("%s: Ignore advertisement data during connection", self.name)
  424. return
  425. self._set_advertisement_data(advertisement)
  426. class SwitchbotSequenceDevice(SwitchbotDevice):
  427. """A Switchbot sequence device.
  428. This class must not use SwitchbotDeviceOverrideStateDuringConnection because
  429. it needs to know when the sequence_number has changed.
  430. """
  431. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  432. """Update device data from advertisement."""
  433. current_state = self._get_adv_value("sequence_number")
  434. super().update_from_advertisement(advertisement)
  435. new_state = self._get_adv_value("sequence_number")
  436. _LOGGER.debug(
  437. "%s: update advertisement: %s (seq before: %s) (seq after: %s)",
  438. self.name,
  439. advertisement,
  440. current_state,
  441. new_state,
  442. )
  443. if current_state != new_state:
  444. asyncio.ensure_future(self.update())