__init__.py 17 KB

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