__init__.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. device = bluepy.btle.Peripheral(self._mac,
  17. bluepy.btle.ADDR_TYPE_RANDOM)
  18. hand_service = device.getServiceByUUID(UUID)
  19. hand = hand_service.getCharacteristics(HANDLE)[0]
  20. hand.write(binascii.a2b_hex(key))
  21. device.disconnect()
  22. except bluepy.btle.BTLEException:
  23. _LOGGER.error("Cannot connect to switchbot.", exc_info=True)
  24. if retry < 1:
  25. return False
  26. self._sendpacket(key, retry-1)
  27. return True
  28. def turn_on(self) -> None:
  29. """Turn device on."""
  30. return self._sendpacket(ON_KEY)
  31. def turn_off(self) -> None:
  32. """Turn device off."""
  33. return self._sendpacket(OFF_KEY)