controller.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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, controller_data):
  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. self.hass = hass
  34. self._controller = controller
  35. self._encoding = encoding
  36. self._controller_data = controller_data
  37. async def send(self, command):
  38. if self._controller == BROADLINK_CONTROLLER:
  39. if self._encoding == ENC_HEX:
  40. try:
  41. command = binascii.unhexlify(command)
  42. command = b64encode(command).decode('utf-8')
  43. except:
  44. raise Exception("Error while converting "
  45. "Hex to Base64 encoding")
  46. if self._encoding == ENC_PRONTO:
  47. try:
  48. command = command.replace(' ', '')
  49. command = bytearray.fromhex(command)
  50. command = Helper.pronto2lirc(command)
  51. command = Helper.lirc2broadlink(command)
  52. command = b64encode(command).decode('utf-8')
  53. except:
  54. raise Exception("Error while converting "
  55. "Pronto to Base64 encoding")
  56. service_data = {
  57. 'host': self._controller_data,
  58. 'packet': command
  59. }
  60. await self.hass.services.async_call(
  61. 'broadlink', 'send', service_data)
  62. if self._controller == MQTT_CONTROLLER:
  63. service_data = {
  64. 'topic': self._controller_data,
  65. 'payload': command
  66. }
  67. await self.hass.services.async_call(
  68. 'mqtt', 'publish', service_data)