controller.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import asyncio
  2. from base64 import b64encode
  3. import binascii
  4. import logging
  5. from homeassistant.core import split_entity_id
  6. from . import Helper
  7. BROADLINK_CONTROLLER = 'Broadlink'
  8. XIAOMI_CONTROLLER = 'Xiaomi'
  9. ENC_BASE64 = 'Base64'
  10. ENC_HEX = 'Hex'
  11. ENC_PRONTO = 'Pronto'
  12. BROADLINK_COMMANDS_ENCODING = [
  13. ENC_BASE64, ENC_HEX, ENC_PRONTO]
  14. class Controller():
  15. def __init__(self, hass, controller, encoding, service):
  16. if controller not in [
  17. BROADLINK_CONTROLLER, XIAOMI_CONTROLLER]:
  18. raise Exception("The controller is not supported.")
  19. if controller == BROADLINK_CONTROLLER:
  20. if encoding not in BROADLINK_COMMANDS_ENCODING:
  21. raise Exception("The encoding is not supported "
  22. "by the Broadlink controller.")
  23. self.hass = hass
  24. self._service_domain = split_entity_id(service)[0]
  25. self._service_name = split_entity_id(service)[1]
  26. self._controller = controller
  27. self._encoding = encoding
  28. if controller == XIAOMI_CONTROLLER:
  29. raise Exception("The Xiaomi IR controller "
  30. "is not yet supported.")
  31. async def send(self, command):
  32. if self._controller == BROADLINK_CONTROLLER:
  33. if self._encoding == ENC_HEX:
  34. try:
  35. command = binascii.unhexlify(command)
  36. command = b64encode(command).decode('utf-8')
  37. except:
  38. raise Exception("Error while converting "
  39. "Hex to Base64 encoding")
  40. if self._encoding == ENC_PRONTO:
  41. try:
  42. command = command.replace(' ', '')
  43. command = bytearray.fromhex(command)
  44. command = Helper.pronto2lirc(command)
  45. command = Helper.lirc2broadlink(command)
  46. command = b64encode(command).decode('utf-8')
  47. except:
  48. raise Exception("Error while converting "
  49. "Pronto to Base64 encoding")
  50. await self.hass.services.async_call(
  51. self._service_domain, self._service_name,
  52. {'packet': command})