controller.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. MQTT_CONTROLLER = 'MQTT'
  9. XIAOMI_CONTROLLER = 'Xiaomi'
  10. ENC_BASE64 = 'Base64'
  11. ENC_HEX = 'Hex'
  12. ENC_PRONTO = 'Pronto'
  13. ENC_RAW = 'Raw'
  14. BROADLINK_COMMANDS_ENCODING = [
  15. ENC_BASE64, ENC_HEX, ENC_PRONTO]
  16. MQTT_COMMANDS_ENCODING = [ENC_RAW]
  17. class Controller():
  18. def __init__(self, hass, controller, encoding, service, topic=None):
  19. if controller not in [
  20. BROADLINK_CONTROLLER, XIAOMI_CONTROLLER, MQTT_CONTROLLER]:
  21. raise Exception("The controller is not supported.")
  22. if controller == BROADLINK_CONTROLLER:
  23. if encoding not in BROADLINK_COMMANDS_ENCODING:
  24. raise Exception("The encoding is not supported "
  25. "by the Broadlink controller.")
  26. if controller == XIAOMI_CONTROLLER:
  27. raise Exception("The Xiaomi IR controller "
  28. "is not yet supported.")
  29. if controller == MQTT_CONTROLLER:
  30. if encoding not in MQTT_COMMANDS_ENCODING:
  31. raise Exception("The encoding is not supported "
  32. "by the mqtt controller.")
  33. if not topic:
  34. raise Exception("controller_command_topic must be "
  35. "specified for mqtt controllers.")
  36. self.hass = hass
  37. self._service_domain = split_entity_id(service)[0]
  38. self._service_name = split_entity_id(service)[1]
  39. self._command_topic = topic
  40. self._controller = controller
  41. self._encoding = encoding
  42. async def send(self, command):
  43. if self._controller == BROADLINK_CONTROLLER:
  44. if self._encoding == ENC_HEX:
  45. try:
  46. command = binascii.unhexlify(command)
  47. command = b64encode(command).decode('utf-8')
  48. except:
  49. raise Exception("Error while converting "
  50. "Hex to Base64 encoding")
  51. if self._encoding == ENC_PRONTO:
  52. try:
  53. command = command.replace(' ', '')
  54. command = bytearray.fromhex(command)
  55. command = Helper.pronto2lirc(command)
  56. command = Helper.lirc2broadlink(command)
  57. command = b64encode(command).decode('utf-8')
  58. except:
  59. raise Exception("Error while converting "
  60. "Pronto to Base64 encoding")
  61. service_data = {
  62. 'packet': command
  63. }
  64. await self.hass.services.async_call(
  65. self._service_domain, self._service_name,
  66. service_data)
  67. if self._controller == MQTT_CONTROLLER:
  68. service_data = {
  69. 'topic': self._command_topic,
  70. 'payload': command
  71. }
  72. await self.hass.services.async_call(
  73. self._service_domain, self._service_name,
  74. service_data)