__init__.py 1.4 KB

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