1
0

device.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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
  7. from uuid import UUID
  8. import async_timeout
  9. from bleak import BleakError
  10. from bleak.exc import BleakDBusError
  11. from bleak.backends.device import BLEDevice
  12. from bleak.backends.service import BleakGATTCharacteristic, BleakGATTServiceCollection
  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. 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. class SwitchbotDevice:
  41. """Base Representation of a Switchbot Device."""
  42. def __init__(
  43. self,
  44. device: BLEDevice,
  45. password: str | None = None,
  46. interface: int = 0,
  47. **kwargs: Any,
  48. ) -> None:
  49. """Switchbot base class constructor."""
  50. self._interface = f"hci{interface}"
  51. self._device = device
  52. self._sb_adv_data: SwitchBotAdvertisement | None = None
  53. self._scan_timeout: int = kwargs.pop("scan_timeout", DEFAULT_SCAN_TIMEOUT)
  54. self._retry_count: int = kwargs.pop("retry_count", DEFAULT_RETRY_COUNT)
  55. self._connect_lock = asyncio.Lock()
  56. self._operation_lock = asyncio.Lock()
  57. if password is None or password == "":
  58. self._password_encoded = None
  59. else:
  60. self._password_encoded = "%08x" % (
  61. binascii.crc32(password.encode("ascii")) & 0xFFFFFFFF
  62. )
  63. self._client: BleakClientWithServiceCache | None = None
  64. self._cached_services: BleakGATTServiceCollection | None = None
  65. self._read_char: BleakGATTCharacteristic | None = None
  66. self._write_char: BleakGATTCharacteristic | None = None
  67. self._disconnect_timer: asyncio.TimerHandle | None = None
  68. self._expected_disconnect = False
  69. self.loop = asyncio.get_event_loop()
  70. def _commandkey(self, key: str) -> str:
  71. """Add password to key if set."""
  72. if self._password_encoded is None:
  73. return key
  74. key_action = key[3]
  75. key_suffix = key[4:]
  76. return KEY_PASSWORD_PREFIX + key_action + self._password_encoded + key_suffix
  77. async def _sendcommand(self, key: str, retry: int) -> bytes:
  78. """Send command to device and read response."""
  79. command = bytearray.fromhex(self._commandkey(key))
  80. _LOGGER.debug("%s: Sending command %s", self.name, command)
  81. if self._operation_lock.locked():
  82. _LOGGER.debug(
  83. "%s: Operation already in progress, waiting for it to complete; RSSI: %s",
  84. self.name,
  85. self.rssi,
  86. )
  87. max_attempts = retry + 1
  88. async with self._operation_lock:
  89. for attempt in range(max_attempts):
  90. try:
  91. return await self._send_command_locked(key, command)
  92. except BleakNotFoundError:
  93. _LOGGER.error(
  94. "%s: device not found or no longer in range; Try restarting Bluetooth",
  95. self.name,
  96. exc_info=True,
  97. )
  98. return b"\x00"
  99. except BLEAK_EXCEPTIONS:
  100. if attempt == retry:
  101. _LOGGER.error(
  102. "%s: communication failed; Stopping trying; RSSI: %s",
  103. self.name,
  104. self.rssi,
  105. exc_info=True,
  106. )
  107. return b"\x00"
  108. _LOGGER.debug(
  109. "%s: communication failed with:", self.name, exc_info=True
  110. )
  111. raise RuntimeError("Unreachable")
  112. @property
  113. def name(self) -> str:
  114. """Return device name."""
  115. return f"{self._device.name} ({self._device.address})"
  116. @property
  117. def rssi(self) -> int:
  118. """Return RSSI of device."""
  119. return self._get_adv_value("rssi")
  120. async def _ensure_connected(self):
  121. """Ensure connection to device is established."""
  122. if self._connect_lock.locked():
  123. _LOGGER.debug(
  124. "%s: Connection already in progress, waiting for it to complete; RSSI: %s",
  125. self.name,
  126. self.rssi,
  127. )
  128. if self._client and self._client.is_connected:
  129. self._reset_disconnect_timer()
  130. return
  131. async with self._connect_lock:
  132. # Check again while holding the lock
  133. if self._client and self._client.is_connected:
  134. self._reset_disconnect_timer()
  135. return
  136. _LOGGER.debug("%s: Connecting; RSSI: %s", self.name, self.rssi)
  137. client = await establish_connection(
  138. BleakClientWithServiceCache,
  139. self._device,
  140. self.name,
  141. self._disconnected,
  142. cached_services=self._cached_services,
  143. ble_device_callback=lambda: self._device,
  144. )
  145. self._cached_services = client.services
  146. _LOGGER.debug("%s: Connected; RSSI: %s", self.name, self.rssi)
  147. services = client.services
  148. self._read_char = services.get_characteristic(_sb_uuid(comms_type="rx"))
  149. self._write_char = services.get_characteristic(_sb_uuid(comms_type="tx"))
  150. self._client = client
  151. self._reset_disconnect_timer()
  152. def _reset_disconnect_timer(self):
  153. """Reset disconnect timer."""
  154. if self._disconnect_timer:
  155. self._disconnect_timer.cancel()
  156. self._expected_disconnect = False
  157. self._disconnect_timer = self.loop.call_later(
  158. DISCONNECT_DELAY, self._disconnect
  159. )
  160. def _disconnected(self, client: BleakClientWithServiceCache) -> None:
  161. """Disconnected callback."""
  162. if self._expected_disconnect:
  163. _LOGGER.debug(
  164. "%s: Disconnected from device; RSSI: %s", self.name, self.rssi
  165. )
  166. return
  167. _LOGGER.warning(
  168. "%s: Device unexpectedly disconnected; RSSI: %s",
  169. self.name,
  170. self.rssi,
  171. )
  172. def _disconnect(self):
  173. """Disconnect from device."""
  174. self._disconnect_timer = None
  175. asyncio.create_task(self._execute_timed_disconnect())
  176. async def _execute_timed_disconnect(self):
  177. """Execute timed disconnection."""
  178. _LOGGER.debug(
  179. "%s: Disconnecting after timeout of %s",
  180. self.name,
  181. DISCONNECT_DELAY,
  182. )
  183. await self._execute_disconnect()
  184. async def _execute_disconnect(self):
  185. """Execute disconnection."""
  186. async with self._connect_lock:
  187. if not self._client or not self._client.is_connected:
  188. return
  189. self._expected_disconnect = True
  190. await self._client.disconnect()
  191. self._client = None
  192. self._read_char = None
  193. self._write_char = None
  194. async def _send_command_locked(self, key: str, command: bytes) -> bytes:
  195. """Send command to device and read response."""
  196. await self._ensure_connected()
  197. try:
  198. return await self._execute_command_locked(key, command)
  199. except BleakDBusError as ex:
  200. # Disconnect so we can reset state and try again
  201. await asyncio.sleep(0.25)
  202. _LOGGER.debug(
  203. "%s: RSSI: %s; Backing off %ss; Disconnecting due to error: %s",
  204. self.name,
  205. self.rssi,
  206. 0.25,
  207. ex,
  208. )
  209. await self._execute_disconnect()
  210. except BleakError as ex:
  211. # Disconnect so we can reset state and try again
  212. _LOGGER.debug(
  213. "%s: RSSI: %s; Disconnecting due to error: %s", self.name, self.rssi, ex
  214. )
  215. await self._execute_disconnect()
  216. raise
  217. async def _execute_command_locked(self, key: str, command: bytes) -> bytes:
  218. """Execute command and read response."""
  219. assert self._client is not None
  220. assert self._read_char is not None
  221. assert self._write_char is not None
  222. future: asyncio.Future[bytearray] = asyncio.Future()
  223. client = self._client
  224. def _notification_handler(_sender: int, data: bytearray) -> None:
  225. """Handle notification responses."""
  226. if future.done():
  227. _LOGGER.debug("%s: Notification handler already done", self.name)
  228. return
  229. future.set_result(data)
  230. _LOGGER.debug("%s: Subscribe to notifications; RSSI: %s", self.name, self.rssi)
  231. await client.start_notify(self._read_char, _notification_handler)
  232. _LOGGER.debug("%s: Sending command: %s", self.name, key)
  233. await client.write_gatt_char(self._write_char, command, False)
  234. async with async_timeout.timeout(5):
  235. notify_msg = await future
  236. _LOGGER.debug("%s: Notification received: %s", self.name, notify_msg)
  237. _LOGGER.debug("%s: UnSubscribe to notifications", self.name)
  238. await client.stop_notify(self._read_char)
  239. if notify_msg == b"\x07":
  240. _LOGGER.error("Password required")
  241. elif notify_msg == b"\t":
  242. _LOGGER.error("Password incorrect")
  243. return notify_msg
  244. def get_address(self) -> str:
  245. """Return address of device."""
  246. return self._device.address
  247. def _get_adv_value(self, key: str) -> Any:
  248. """Return value from advertisement data."""
  249. if not self._sb_adv_data:
  250. return None
  251. return self._sb_adv_data.data["data"][key]
  252. def get_battery_percent(self) -> Any:
  253. """Return device battery level in percent."""
  254. return self._get_adv_value("battery")
  255. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  256. """Update device data from advertisement."""
  257. self._sb_adv_data = advertisement
  258. if self._device and ble_device_has_changed(self._device, advertisement.device):
  259. self._cached_services = None
  260. self._device = advertisement.device
  261. async def get_device_data(
  262. self, retry: int = DEFAULT_RETRY_COUNT, interface: int | None = None
  263. ) -> SwitchBotAdvertisement | None:
  264. """Find switchbot devices and their advertisement data."""
  265. if interface:
  266. _interface: int = interface
  267. else:
  268. _interface = int(self._interface.replace("hci", ""))
  269. _data = await GetSwitchbotDevices(interface=_interface).discover(
  270. retry=retry, scan_timeout=self._scan_timeout
  271. )
  272. if self._device.address in _data:
  273. self._sb_adv_data = _data[self._device.address]
  274. return self._sb_adv_data
  275. async def _get_basic_info(self) -> bytes | None:
  276. """Return basic info of device."""
  277. _data = await self._sendcommand(
  278. key=DEVICE_GET_BASIC_SETTINGS_KEY, retry=self._retry_count
  279. )
  280. if _data in (b"\x07", b"\x00"):
  281. _LOGGER.error("Unsuccessful, please try again")
  282. return None
  283. return _data