device.py 15 KB

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