device.py 14 KB

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