device.py 14 KB

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