__init__.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """Library to handle connection with Switchbot"""
  2. import binascii
  3. import logging
  4. import bluepy
  5. UUID = "cba20d00-224d-11e6-9fb8-0002a5d5c51b"
  6. HANDLE = "cba20002-224d-11e6-9fb8-0002a5d5c51b"
  7. PRESS_KEY = "570100"
  8. ON_KEY = "570101"
  9. OFF_KEY = "570102"
  10. _LOGGER = logging.getLogger(__name__)
  11. class Switchbot:
  12. """Representation of a Switchbot."""
  13. def __init__(self, mac) -> None:
  14. self._mac = mac
  15. self._device = None
  16. self._connect()
  17. def _connect(self) -> bool:
  18. if self._device is not None:
  19. _LOGGER.debug("Disconnecting")
  20. try:
  21. self._device.disconnect()
  22. except bluepy.btle.BTLEException:
  23. pass
  24. try:
  25. _LOGGER.debug("Connecting")
  26. self._device = bluepy.btle.Peripheral(self._mac,
  27. bluepy.btle.ADDR_TYPE_RANDOM)
  28. except bluepy.btle.BTLEException:
  29. _LOGGER.error("Failed to connect to Switchbot", exc_info=True)
  30. return False
  31. return True
  32. def _sendpacket(self, key, retry=2) -> bool:
  33. try:
  34. _LOGGER.debug("Prepare to send")
  35. hand_service = self._device.getServiceByUUID(UUID)
  36. hand = hand_service.getCharacteristics(HANDLE)[0]
  37. _LOGGER.debug("Sending command, %s", key)
  38. hand.write(binascii.a2b_hex(key))
  39. except bluepy.btle.BTLEException:
  40. if retry < 1 or not self._connect():
  41. _LOGGER.error("Cannot connect to switchbot.", exc_info=True)
  42. return False
  43. _LOGGER.warning("Cannot connect to switchbot. Retrying")
  44. return self._sendpacket(key, retry-1)
  45. return True
  46. def turn_on(self) -> None:
  47. """Turn device on."""
  48. return self._sendpacket(ON_KEY)
  49. def turn_off(self) -> None:
  50. """Turn device off."""
  51. return self._sendpacket(OFF_KEY)
  52. def press(self) -> None:
  53. """Press command to device."""
  54. return self._sendpacket(PRESS_KEY)