controller.py 6.8 KB

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