__init__.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 Switchmate."""
  13. def __init__(self, mac) -> None:
  14. self._mac = mac
  15. def _sendpacket(self, key, retry=2) -> bool:
  16. try:
  17. _LOGGER.debug("Connecting")
  18. device = bluepy.btle.Peripheral(self._mac,
  19. bluepy.btle.ADDR_TYPE_RANDOM)
  20. hand_service = device.getServiceByUUID(UUID)
  21. hand = hand_service.getCharacteristics(HANDLE)[0]
  22. _LOGGER.debug("Sending command, %s", key)
  23. hand.write(binascii.a2b_hex(key))
  24. _LOGGER.debug("Disconnecting")
  25. device.disconnect()
  26. except bluepy.btle.BTLEException:
  27. _LOGGER.error("Cannot connect to switchbot. Retrying", exc_info=True)
  28. if retry < 1:
  29. _LOGGER.error("Cannot connect to switchbot.", exc_info=True)
  30. return False
  31. return self._sendpacket(key, retry-1)
  32. return True
  33. def turn_on(self) -> None:
  34. """Turn device on."""
  35. return self._sendpacket(ON_KEY)
  36. def turn_off(self) -> None:
  37. """Turn device off."""
  38. return self._sendpacket(OFF_KEY)
  39. def press(self) -> None:
  40. """Press command to device."""
  41. return self._sendpacket(PRESS_KEY)