controller.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. from abc import ABC, abstractmethod
  2. from base64 import b64encode
  3. import binascii
  4. import requests
  5. import logging
  6. import json
  7. from homeassistant.const import ATTR_ENTITY_ID
  8. from . import Helper
  9. _LOGGER = logging.getLogger(__name__)
  10. BROADLINK_CONTROLLER = 'Broadlink'
  11. XIAOMI_CONTROLLER = 'Xiaomi'
  12. MQTT_CONTROLLER = 'MQTT'
  13. LOOKIN_CONTROLLER = 'LOOKin'
  14. ESPHOME_CONTROLLER = 'ESPHome'
  15. ENC_BASE64 = 'Base64'
  16. ENC_HEX = 'Hex'
  17. ENC_PRONTO = 'Pronto'
  18. ENC_RAW = 'Raw'
  19. BROADLINK_COMMANDS_ENCODING = [ENC_BASE64, ENC_HEX, ENC_PRONTO]
  20. XIAOMI_COMMANDS_ENCODING = [ENC_PRONTO, ENC_RAW]
  21. MQTT_COMMANDS_ENCODING = [ENC_RAW]
  22. LOOKIN_COMMANDS_ENCODING = [ENC_PRONTO, ENC_RAW]
  23. ESPHOME_COMMANDS_ENCODING = [ENC_RAW]
  24. def get_controller(hass, controller, encoding, controller_data):
  25. """Return a controller compatible with the specification provided."""
  26. controllers = {
  27. BROADLINK_CONTROLLER: BroadlinkController,
  28. XIAOMI_CONTROLLER: XiaomiController,
  29. MQTT_CONTROLLER: MQTTController,
  30. LOOKIN_CONTROLLER: LookinController,
  31. ESPHOME_CONTROLLER: ESPHomeController
  32. }
  33. try:
  34. return controllers[controller](hass, controller, encoding, controller_data)
  35. except KeyError:
  36. raise Exception("The controller is not supported.")
  37. class AbstractController(ABC):
  38. """Representation of a controller."""
  39. def __init__(self, hass, controller, encoding, controller_data):
  40. self.check_encoding(encoding)
  41. self.hass = hass
  42. self._controller = controller
  43. self._encoding = encoding
  44. self._controller_data = controller_data
  45. @abstractmethod
  46. def check_encoding(self, encoding):
  47. """Check if the encoding is supported by the controller."""
  48. pass
  49. @abstractmethod
  50. async def send(self, command):
  51. """Send a command."""
  52. pass
  53. class BroadlinkController(AbstractController):
  54. """Controls a Broadlink device."""
  55. def check_encoding(self, encoding):
  56. """Check if the encoding is supported by the controller."""
  57. if encoding not in BROADLINK_COMMANDS_ENCODING:
  58. raise Exception("The encoding is not supported "
  59. "by the Broadlink controller.")
  60. async def send(self, command):
  61. """Send a command."""
  62. commands = []
  63. if not isinstance(command, list):
  64. command = [command]
  65. for _command in command:
  66. if self._encoding == ENC_HEX:
  67. try:
  68. _command = binascii.unhexlify(_command)
  69. _command = b64encode(_command).decode('utf-8')
  70. except:
  71. raise Exception("Error while converting "
  72. "Hex to Base64 encoding")
  73. if self._encoding == ENC_PRONTO:
  74. try:
  75. _command = _command.replace(' ', '')
  76. _command = bytearray.fromhex(_command)
  77. _command = Helper.pronto2lirc(_command)
  78. _command = Helper.lirc2broadlink(_command)
  79. _command = b64encode(_command).decode('utf-8')
  80. except:
  81. raise Exception("Error while converting "
  82. "Pronto to Base64 encoding")
  83. commands.append('b64:' + _command)
  84. service_data = {
  85. ATTR_ENTITY_ID: self._controller_data,
  86. 'command': commands
  87. }
  88. await self.hass.services.async_call(
  89. 'remote', 'send_command', service_data)
  90. class XiaomiController(AbstractController):
  91. """Controls a Xiaomi device."""
  92. def check_encoding(self, encoding):
  93. """Check if the encoding is supported by the controller."""
  94. if encoding not in XIAOMI_COMMANDS_ENCODING:
  95. raise Exception("The encoding is not supported "
  96. "by the Xiaomi controller.")
  97. async def send(self, command):
  98. """Send a command."""
  99. service_data = {
  100. ATTR_ENTITY_ID: self._controller_data,
  101. 'command': self._encoding.lower() + ':' + command
  102. }
  103. await self.hass.services.async_call(
  104. 'remote', 'send_command', service_data)
  105. class MQTTController(AbstractController):
  106. """Controls a MQTT device."""
  107. def check_encoding(self, encoding):
  108. """Check if the encoding is supported by the controller."""
  109. if encoding not in MQTT_COMMANDS_ENCODING:
  110. raise Exception("The encoding is not supported "
  111. "by the mqtt controller.")
  112. async def send(self, command):
  113. """Send a command."""
  114. service_data = {
  115. 'topic': self._controller_data,
  116. 'payload': command
  117. }
  118. await self.hass.services.async_call(
  119. 'mqtt', 'publish', service_data)
  120. class LookinController(AbstractController):
  121. """Controls a Lookin device."""
  122. def check_encoding(self, encoding):
  123. """Check if the encoding is supported by the controller."""
  124. if encoding not in LOOKIN_COMMANDS_ENCODING:
  125. raise Exception("The encoding is not supported "
  126. "by the LOOKin controller.")
  127. async def send(self, command):
  128. """Send a command."""
  129. encoding = self._encoding.lower().replace('pronto', 'prontohex')
  130. url = f"http://{self._controller_data}/commands/ir/" \
  131. f"{encoding}/{command}"
  132. await self.hass.async_add_executor_job(requests.get, url)
  133. class ESPHomeController(AbstractController):
  134. """Controls a ESPHome device."""
  135. def check_encoding(self, encoding):
  136. """Check if the encoding is supported by the controller."""
  137. if encoding not in ESPHOME_COMMANDS_ENCODING:
  138. raise Exception("The encoding is not supported "
  139. "by the ESPHome controller.")
  140. async def send(self, command):
  141. """Send a command."""
  142. service_data = {'command': json.loads(command)}
  143. await self.hass.services.async_call(
  144. 'esphome', self._controller_data, service_data)