device.py 20 KB

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