__init__.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. self._device = None
  15. self._connect()
  16. def _connect(self) -> bool:
  17. if self._device is not None:
  18. _LOGGER.debug("Disconnecting")
  19. try:
  20. self._device.disconnect()
  21. except bluepy.btle.BTLEException:
  22. pass
  23. try:
  24. _LOGGER.debug("Connecting")
  25. self._device = bluepy.btle.Peripheral(self._mac,
  26. bluepy.btle.ADDR_TYPE_RANDOM)
  27. except bluepy.btle.BTLEException:
  28. _LOGGER.error("Failed to connect to switchmate", exc_info=True)
  29. return False
  30. return True
  31. def _sendpacket(self, key, retry=2) -> bool:
  32. try:
  33. _LOGGER.debug("Connecting")
  34. hand_service = self._device.getServiceByUUID(UUID)
  35. hand = hand_service.getCharacteristics(HANDLE)[0]
  36. _LOGGER.debug("Sending command, %s", key)
  37. hand.write(binascii.a2b_hex(key))
  38. except bluepy.btle.BTLEException:
  39. if retry < 1 or not self._connect():
  40. _LOGGER.error("Cannot connect to switchbot.", exc_info=True)
  41. return False
  42. _LOGGER.error("Cannot connect to switchbot. Retrying", exc_info=True)
  43. return self._sendpacket(key, retry-1)
  44. return True
  45. def turn_on(self) -> None:
  46. """Turn device on."""
  47. return self._sendpacket(ON_KEY)
  48. def turn_off(self) -> None:
  49. """Turn device off."""
  50. return self._sendpacket(OFF_KEY)