__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. """Library to handle connection with Switchbot."""
  2. from __future__ import annotations
  3. import binascii
  4. import logging
  5. import threading
  6. import time
  7. import bluepy
  8. DEFAULT_RETRY_COUNT = 3
  9. DEFAULT_RETRY_TIMEOUT = 1
  10. DEFAULT_SCAN_TIMEOUT = 5
  11. UUID = "cba20d00-224d-11e6-9fb8-0002a5d5c51b"
  12. HANDLE = "cba20002-224d-11e6-9fb8-0002a5d5c51b"
  13. KEY_PASSWORD_PREFIX = "5711"
  14. PRESS_KEY = "570100"
  15. ON_KEY = "570101"
  16. OFF_KEY = "570102"
  17. OPEN_KEY = "570f450105ff00" # 570F4501010100
  18. CLOSE_KEY = "570f450105ff64" # 570F4501010164
  19. POSITION_KEY = "570F450105ff" # +actual_position ex: 570F450105ff32 for 50%
  20. STOP_KEY = "570F450100ff"
  21. ON_KEY_SUFFIX = "01"
  22. OFF_KEY_SUFFIX = "02"
  23. PRESS_KEY_SUFFIX = "00"
  24. _LOGGER = logging.getLogger(__name__)
  25. CONNECT_LOCK = threading.Lock()
  26. def _process_wohand(data) -> dict:
  27. """Process woHand/Bot services data."""
  28. _bot_data = {}
  29. _sensor_data = binascii.unhexlify(data.encode())
  30. # 128 switch or 0 press.
  31. _bot_data["switchMode"] = bool(_sensor_data[1] & 0b10000000)
  32. # 64 off or 0 for on, if not inversed in app.
  33. if _bot_data["switchMode"]:
  34. _bot_data["isOn"] = not bool(_sensor_data[1] & 0b01000000)
  35. else:
  36. _bot_data["isOn"] = False
  37. _bot_data["battery"] = _sensor_data[2] & 0b01111111
  38. return _bot_data
  39. def _process_wocurtain(data, reverse=True) -> dict:
  40. """Process woCurtain/Curtain services data."""
  41. _curtain_data = {}
  42. _sensor_data = binascii.unhexlify(data.encode())
  43. _curtain_data["calibration"] = bool(_sensor_data[1] & 0b01000000)
  44. _curtain_data["battery"] = _sensor_data[2] & 0b01111111
  45. _position = max(min(_sensor_data[3] & 0b01111111, 100), 0)
  46. _curtain_data["position"] = (100 - _position) if reverse else _position
  47. # light sensor level (1-10)
  48. _curtain_data["lightLevel"] = (_sensor_data[4] >> 4) & 0b00001111
  49. return _curtain_data
  50. def _process_wosensorth(data) -> dict:
  51. """Process woSensorTH/Temp sensor services data."""
  52. _wosensorth_data = {}
  53. _sensor_data = binascii.unhexlify(data.encode())
  54. _temp_sign = 1 if _sensor_data[4] & 0b10000000 else -1
  55. _temp_c = _temp_sign * ((_sensor_data[4] & 0b01111111) + (_sensor_data[3] / 10))
  56. _temp_f = (_temp_c * 9 / 5) + 32
  57. _temp_f = (_temp_f * 10) / 10
  58. _wosensorth_data["temp"] = {}
  59. _wosensorth_data["temp"]["c"] = _temp_c
  60. _wosensorth_data["temp"]["f"] = _temp_f
  61. _wosensorth_data["fahrenheit"] = bool(_sensor_data[5] & 0b10000000)
  62. _wosensorth_data["humidity"] = _sensor_data[5] & 0b01111111
  63. _wosensorth_data["battery"] = _sensor_data[2] & 0b01111111
  64. return _wosensorth_data
  65. class GetSwitchbotDevices:
  66. """Scan for all Switchbot devices and return by type."""
  67. def __init__(self, interface=None) -> None:
  68. """Get switchbot devices class constructor."""
  69. self._interface = interface
  70. self._all_services_data = {}
  71. def discover(
  72. self, retry=DEFAULT_RETRY_COUNT, scan_timeout=DEFAULT_SCAN_TIMEOUT
  73. ) -> dict | None:
  74. """Find switchbot devices and their advertisement data."""
  75. devices = None
  76. try:
  77. devices = bluepy.btle.Scanner(self._interface).scan(scan_timeout)
  78. except bluepy.btle.BTLEManagementError:
  79. _LOGGER.error("Error scanning for switchbot devices", exc_info=True)
  80. if devices is None:
  81. if retry < 1:
  82. _LOGGER.error(
  83. "Scanning for Switchbot devices failed. Stop trying", exc_info=True
  84. )
  85. return None
  86. _LOGGER.warning(
  87. "Error scanning for Switchbot devices. Retrying (remaining: %d)",
  88. retry,
  89. )
  90. time.sleep(DEFAULT_RETRY_TIMEOUT)
  91. return self.discover(retry - 1, scan_timeout)
  92. for dev in devices:
  93. if dev.getValueText(7) == UUID:
  94. dev_id = dev.addr.replace(":", "")
  95. self._all_services_data[dev_id] = {}
  96. self._all_services_data[dev_id]["mac_address"] = dev.addr
  97. for (adtype, desc, value) in dev.getScanData():
  98. if adtype == 22:
  99. _model = chr(binascii.unhexlify(value.encode())[2] & 0b01111111)
  100. if _model == "H":
  101. self._all_services_data[dev_id]["data"] = _process_wohand(
  102. value[4:]
  103. )
  104. self._all_services_data[dev_id]["data"]["rssi"] = dev.rssi
  105. self._all_services_data[dev_id]["model"] = _model
  106. self._all_services_data[dev_id]["modelName"] = "WoHand"
  107. elif _model == "c":
  108. self._all_services_data[dev_id][
  109. "data"
  110. ] = _process_wocurtain(value[4:])
  111. self._all_services_data[dev_id]["data"]["rssi"] = dev.rssi
  112. self._all_services_data[dev_id]["model"] = _model
  113. self._all_services_data[dev_id]["modelName"] = "WoCurtain"
  114. elif _model == "T":
  115. self._all_services_data[dev_id][
  116. "data"
  117. ] = _process_wosensorth(value[4:])
  118. self._all_services_data[dev_id]["data"]["rssi"] = dev.rssi
  119. self._all_services_data[dev_id]["model"] = _model
  120. self._all_services_data[dev_id]["modelName"] = "WoSensorTH"
  121. else:
  122. continue
  123. else:
  124. self._all_services_data[dev_id][desc] = value
  125. return self._all_services_data
  126. def get_curtains(self) -> dict | None:
  127. """Return all WoCurtain/Curtains devices with services data."""
  128. if not self._all_services_data:
  129. self.discover()
  130. _curtain_devices = {}
  131. for item in self._all_services_data:
  132. if self._all_services_data[item]["model"] == "c":
  133. _curtain_devices[item] = self._all_services_data[item]
  134. return _curtain_devices
  135. def get_bots(self) -> dict | None:
  136. """Return all WoHand/Bot devices with services data."""
  137. if not self._all_services_data:
  138. self.discover()
  139. _bot_devices = {}
  140. for item in self._all_services_data:
  141. if self._all_services_data[item]["model"] == "H":
  142. _bot_devices[item] = self._all_services_data[item]
  143. return _bot_devices
  144. def get_device_data(self, mac) -> dict | None:
  145. """Return data for specific device."""
  146. if not self._all_services_data:
  147. self.discover()
  148. _switchbot_data = {}
  149. for item in self._all_services_data:
  150. if self._all_services_data[item]["mac_address"] == mac:
  151. _switchbot_data = self._all_services_data[item]
  152. return _switchbot_data
  153. class SwitchbotDevice:
  154. """Base Representation of a Switchbot Device."""
  155. def __init__(self, mac, password=None, interface=None, **kwargs) -> None:
  156. """Switchbot base class constructor."""
  157. self._interface = interface
  158. self._mac = mac
  159. self._device = None
  160. self._switchbot_device_data = {}
  161. self._scan_timeout = kwargs.pop("scan_timeout", DEFAULT_SCAN_TIMEOUT)
  162. self._retry_count = kwargs.pop("retry_count", DEFAULT_RETRY_COUNT)
  163. if password is None or password == "":
  164. self._password_encoded = None
  165. else:
  166. self._password_encoded = "%x" % (
  167. binascii.crc32(password.encode("ascii")) & 0xFFFFFFFF
  168. )
  169. def _connect(self) -> None:
  170. if self._device is not None:
  171. return
  172. try:
  173. _LOGGER.debug("Connecting to Switchbot")
  174. self._device = bluepy.btle.Peripheral(
  175. self._mac, bluepy.btle.ADDR_TYPE_RANDOM, self._interface
  176. )
  177. _LOGGER.debug("Connected to Switchbot")
  178. except bluepy.btle.BTLEException:
  179. _LOGGER.debug("Failed connecting to Switchbot", exc_info=True)
  180. self._device = None
  181. raise
  182. def _disconnect(self) -> None:
  183. if self._device is None:
  184. return
  185. _LOGGER.debug("Disconnecting")
  186. try:
  187. self._device.disconnect()
  188. except bluepy.btle.BTLEException:
  189. _LOGGER.warning("Error disconnecting from Switchbot", exc_info=True)
  190. finally:
  191. self._device = None
  192. def _commandkey(self, key) -> str:
  193. if self._password_encoded is None:
  194. return key
  195. key_suffix = PRESS_KEY_SUFFIX
  196. if key == ON_KEY:
  197. key_suffix = ON_KEY_SUFFIX
  198. elif key == OFF_KEY:
  199. key_suffix = OFF_KEY_SUFFIX
  200. return KEY_PASSWORD_PREFIX + self._password_encoded + key_suffix
  201. def _writekey(self, key) -> bool:
  202. _LOGGER.debug("Prepare to send")
  203. hand_service = self._device.getServiceByUUID(UUID)
  204. hand = hand_service.getCharacteristics(HANDLE)[0]
  205. _LOGGER.debug("Sending command, %s", key)
  206. write_result = hand.write(binascii.a2b_hex(key), withResponse=True)
  207. if not write_result:
  208. _LOGGER.error(
  209. "Sent command but didn't get a response from Switchbot confirming command was sent."
  210. " Please check the Switchbot"
  211. )
  212. else:
  213. _LOGGER.info("Successfully sent command to Switchbot (MAC: %s)", self._mac)
  214. return write_result
  215. def _sendcommand(self, key, retry) -> bool:
  216. send_success = False
  217. command = self._commandkey(key)
  218. _LOGGER.debug("Sending command to switchbot %s", command)
  219. with CONNECT_LOCK:
  220. try:
  221. self._connect()
  222. send_success = self._writekey(command)
  223. except bluepy.btle.BTLEException:
  224. _LOGGER.warning("Error talking to Switchbot", exc_info=True)
  225. finally:
  226. self._disconnect()
  227. if send_success:
  228. return True
  229. if retry < 1:
  230. _LOGGER.error(
  231. "Switchbot communication failed. Stopping trying", exc_info=True
  232. )
  233. return False
  234. _LOGGER.warning("Cannot connect to Switchbot. Retrying (remaining: %d)", retry)
  235. time.sleep(DEFAULT_RETRY_TIMEOUT)
  236. return self._sendcommand(key, retry - 1)
  237. def get_mac(self) -> str:
  238. """Return mac address of device."""
  239. return self._mac
  240. def get_battery_percent(self) -> int:
  241. """Return device battery level in percent."""
  242. if not self._switchbot_device_data:
  243. return None
  244. return self._switchbot_device_data["data"]["battery"]
  245. def get_device_data(self, retry=DEFAULT_RETRY_COUNT, interface=None) -> dict | None:
  246. """Find switchbot devices and their advertisement data."""
  247. if interface:
  248. _interface = interface
  249. else:
  250. _interface = self._interface
  251. devices = None
  252. try:
  253. devices = bluepy.btle.Scanner(_interface).scan(self._scan_timeout)
  254. except bluepy.btle.BTLEManagementError:
  255. _LOGGER.error("Error scanning for switchbot devices", exc_info=True)
  256. if devices is None:
  257. if retry < 1:
  258. _LOGGER.error(
  259. "Scanning for Switchbot devices failed. Stop trying", exc_info=True
  260. )
  261. return None
  262. _LOGGER.warning(
  263. "Error scanning for Switchbot devices. Retrying (remaining: %d)",
  264. retry,
  265. )
  266. time.sleep(DEFAULT_RETRY_TIMEOUT)
  267. return self.get_device_data(retry=retry - 1, interface=_interface)
  268. for dev in devices:
  269. if self._mac.lower() == dev.addr.lower():
  270. self._switchbot_device_data["mac_address"] = dev.addr
  271. for (adtype, desc, value) in dev.getScanData():
  272. if adtype == 22:
  273. _model = chr(binascii.unhexlify(value.encode())[2] & 0b01111111)
  274. if _model == "H":
  275. self._switchbot_device_data["data"] = _process_wohand(
  276. value[4:]
  277. )
  278. self._switchbot_device_data["data"]["rssi"] = dev.rssi
  279. self._switchbot_device_data["model"] = _model
  280. self._switchbot_device_data["modelName"] = "WoHand"
  281. elif _model == "c":
  282. self._switchbot_device_data["data"] = _process_wocurtain(
  283. value[4:]
  284. )
  285. self._switchbot_device_data["data"]["rssi"] = dev.rssi
  286. self._switchbot_device_data["model"] = _model
  287. self._switchbot_device_data["modelName"] = "WoCurtain"
  288. elif _model == "T":
  289. self._switchbot_device_data["data"] = _process_wosensorth(
  290. value[4:]
  291. )
  292. self._switchbot_device_data["data"]["rssi"] = dev.rssi
  293. self._switchbot_device_data["model"] = _model
  294. self._switchbot_device_data["modelName"] = "WoSensorTH"
  295. else:
  296. continue
  297. else:
  298. self._switchbot_device_data[desc] = value
  299. return self._switchbot_device_data
  300. class Switchbot(SwitchbotDevice):
  301. """Representation of a Switchbot."""
  302. def __init__(self, *args, **kwargs) -> None:
  303. """Switchbot Bot/WoHand constructor."""
  304. super().__init__(*args, **kwargs)
  305. self._inverse = kwargs.pop("inverse_mode", False)
  306. def update(self, interface=None) -> None:
  307. """Update mode, battery percent and state of device."""
  308. self.get_device_data(retry=self._retry_count, interface=interface)
  309. def turn_on(self) -> bool:
  310. """Turn device on."""
  311. return self._sendcommand(ON_KEY, self._retry_count)
  312. def turn_off(self) -> bool:
  313. """Turn device off."""
  314. return self._sendcommand(OFF_KEY, self._retry_count)
  315. def press(self) -> bool:
  316. """Press command to device."""
  317. return self._sendcommand(PRESS_KEY, self._retry_count)
  318. def switch_mode(self) -> str:
  319. """Return true or false from cache."""
  320. # To get actual position call update() first.
  321. if not self._switchbot_device_data:
  322. return None
  323. return self._switchbot_device_data["data"]["switchMode"]
  324. def is_on(self) -> bool:
  325. """Return switch state from cache."""
  326. # To get actual position call update() first.
  327. if not self._switchbot_device_data:
  328. return None
  329. if self._inverse:
  330. return not self._switchbot_device_data["data"]["isOn"]
  331. return self._switchbot_device_data["data"]["isOn"]
  332. class SwitchbotCurtain(SwitchbotDevice):
  333. """Representation of a Switchbot Curtain."""
  334. def __init__(self, *args, **kwargs) -> None:
  335. """Switchbot Curtain/WoCurtain constructor."""
  336. # The position of the curtain is saved returned with 0 = open and 100 = closed.
  337. # This is independent of the calibration of the curtain bot (Open left to right/
  338. # Open right to left/Open from the middle).
  339. # The parameter 'reverse_mode' reverse these values,
  340. # if 'reverse_mode' = True, position = 0 equals close
  341. # and position = 100 equals open. The parameter is default set to True so that
  342. # the definition of position is the same as in Home Assistant.
  343. super().__init__(*args, **kwargs)
  344. self._reverse = kwargs.pop("reverse_mode", True)
  345. def open(self) -> bool:
  346. """Send open command."""
  347. return self._sendcommand(OPEN_KEY, self._retry_count)
  348. def close(self) -> bool:
  349. """Send close command."""
  350. return self._sendcommand(CLOSE_KEY, self._retry_count)
  351. def stop(self) -> bool:
  352. """Send stop command to device."""
  353. return self._sendcommand(STOP_KEY, self._retry_count)
  354. def set_position(self, position: int) -> bool:
  355. """Send position command (0-100) to device."""
  356. position = (100 - position) if self._reverse else position
  357. hex_position = "%0.2X" % position
  358. return self._sendcommand(POSITION_KEY + hex_position, self._retry_count)
  359. def update(self, interface=None) -> None:
  360. """Update position, battery percent and light level of device."""
  361. self.get_device_data(retry=self._retry_count, interface=interface)
  362. def get_position(self) -> int:
  363. """Return cached position (0-100) of Curtain."""
  364. # To get actual position call update() first.
  365. if not self._switchbot_device_data:
  366. return None
  367. return self._switchbot_device_data["data"]["position"]
  368. def get_light_level(self) -> int:
  369. """Return cached light level."""
  370. # To get actual light level call update() first.
  371. if not self._switchbot_device_data:
  372. return None
  373. return self._switchbot_device_data["data"]["lightLevel"]
  374. def is_reversed(self) -> bool:
  375. """Return True if the curtain open from left to right."""
  376. return self._reverse
  377. def is_calibrated(self) -> bool:
  378. """Return True curtain is calibrated."""
  379. # To get actual light level call update() first.
  380. if not self._switchbot_device_data:
  381. return None
  382. return self._switchbot_device_data["data"]["calibration"]