4
0

controller.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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, delay):
  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, delay)
  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, delay):
  40. self.check_encoding(encoding)
  41. self.hass = hass
  42. self._controller = controller
  43. self._encoding = encoding
  44. self._controller_data = controller_data
  45. self._delay = delay
  46. @abstractmethod
  47. def check_encoding(self, encoding):
  48. """Check if the encoding is supported by the controller."""
  49. pass
  50. @abstractmethod
  51. async def send(self, command):
  52. """Send a command."""
  53. pass
  54. class BroadlinkController(AbstractController):
  55. """Controls a Broadlink device."""
  56. def check_encoding(self, encoding):
  57. """Check if the encoding is supported by the controller."""
  58. if encoding not in BROADLINK_COMMANDS_ENCODING:
  59. raise Exception("The encoding is not supported "
  60. "by the Broadlink controller.")
  61. async def send(self, command):
  62. """Send a command."""
  63. commands = []
  64. if not isinstance(command, list):
  65. command = [command]
  66. for _command in command:
  67. if self._encoding == ENC_HEX:
  68. try:
  69. _command = binascii.unhexlify(_command)
  70. _command = b64encode(_command).decode('utf-8')
  71. except:
  72. raise Exception("Error while converting "
  73. "Hex to Base64 encoding")
  74. if self._encoding == ENC_PRONTO:
  75. try:
  76. _command = _command.replace(' ', '')
  77. _command = bytearray.fromhex(_command)
  78. _command = Helper.pronto2lirc(_command)
  79. _command = Helper.lirc2broadlink(_command)
  80. _command = b64encode(_command).decode('utf-8')
  81. except:
  82. raise Exception("Error while converting "
  83. "Pronto to Base64 encoding")
  84. commands.append('b64:' + _command)
  85. service_data = {
  86. ATTR_ENTITY_ID: self._controller_data,
  87. 'command': commands,
  88. 'delay_secs': self._delay
  89. }
  90. await self.hass.services.async_call(
  91. 'remote', 'send_command', service_data)
  92. class XiaomiController(AbstractController):
  93. """Controls a Xiaomi device."""
  94. def check_encoding(self, encoding):
  95. """Check if the encoding is supported by the controller."""
  96. if encoding not in XIAOMI_COMMANDS_ENCODING:
  97. raise Exception("The encoding is not supported "
  98. "by the Xiaomi controller.")
  99. async def send(self, command):
  100. """Send a command."""
  101. service_data = {
  102. ATTR_ENTITY_ID: self._controller_data,
  103. 'command': self._encoding.lower() + ':' + command
  104. }
  105. await self.hass.services.async_call(
  106. 'remote', 'send_command', service_data)
  107. class MQTTController(AbstractController):
  108. """Controls a MQTT device."""
  109. def check_encoding(self, encoding):
  110. """Check if the encoding is supported by the controller."""
  111. if encoding not in MQTT_COMMANDS_ENCODING:
  112. raise Exception("The encoding is not supported "
  113. "by the mqtt controller.")
  114. async def send(self, command):
  115. """Send a command."""
  116. service_data = {
  117. 'topic': self._controller_data,
  118. 'payload': command
  119. }
  120. await self.hass.services.async_call(
  121. 'mqtt', 'publish', service_data)
  122. class LookinController(AbstractController):
  123. """Controls a Lookin device."""
  124. def check_encoding(self, encoding):
  125. """Check if the encoding is supported by the controller."""
  126. if encoding not in LOOKIN_COMMANDS_ENCODING:
  127. raise Exception("The encoding is not supported "
  128. "by the LOOKin controller.")
  129. async def send(self, command):
  130. """Send a command."""
  131. encoding = self._encoding.lower().replace('pronto', 'prontohex')
  132. url = f"http://{self._controller_data}/commands/ir/" \
  133. f"{encoding}/{command}"
  134. await self.hass.async_add_executor_job(requests.get, url)
  135. class ESPHomeController(AbstractController):
  136. """Controls a ESPHome device."""
  137. def check_encoding(self, encoding):
  138. """Check if the encoding is supported by the controller."""
  139. if encoding not in ESPHOME_COMMANDS_ENCODING:
  140. raise Exception("The encoding is not supported "
  141. "by the ESPHome controller.")
  142. async def send(self, command):
  143. """Send a command."""
  144. service_data = {'command': json.loads(command)}
  145. await self.hass.services.async_call(
  146. 'esphome', self._controller_data, service_data)