__init__.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. import asyncio
  2. import binascii
  3. from distutils.version import StrictVersion
  4. import json
  5. import logging
  6. import os.path
  7. import requests
  8. import struct
  9. import voluptuous as vol
  10. from homeassistant.const import (
  11. ATTR_FRIENDLY_NAME, __version__ as current_ha_version)
  12. import homeassistant.helpers.config_validation as cv
  13. from homeassistant.helpers.typing import ConfigType
  14. _LOGGER = logging.getLogger(__name__)
  15. DOMAIN = 'smartir'
  16. VERSION = '1.2.1'
  17. VERSION_URL = (
  18. "https://raw.githubusercontent.com/smartHomeHub/SmartIR/master/version.json")
  19. REMOTE_BASE_DIR = (
  20. "https://raw.githubusercontent.com/smartHomeHub/SmartIR/master/smartir/"
  21. )
  22. CONF_CHECK_UPDATES = 'check_updates'
  23. CONFIG_SCHEMA = vol.Schema({
  24. DOMAIN: vol.Schema({
  25. vol.Optional(CONF_CHECK_UPDATES, default=True): cv.boolean
  26. })
  27. }, extra=vol.ALLOW_EXTRA)
  28. async def async_setup(hass, config):
  29. """Set up the SmartIR component."""
  30. conf = config.get(DOMAIN)
  31. async def check_updates(service):
  32. await _update(hass)
  33. async def update_component(service):
  34. await _update(hass, True)
  35. hass.services.async_register(DOMAIN, 'check_updates', check_updates)
  36. hass.services.async_register(DOMAIN, 'update_component', update_component)
  37. if conf[CONF_CHECK_UPDATES]:
  38. await _update(hass, False, False)
  39. return True
  40. async def _update(hass, do_update=False, notify_if_latest=True):
  41. has_errors = False
  42. request = requests.get(VERSION_URL, stream=True, timeout=10)
  43. if request.status_code == 200:
  44. data = request.json()
  45. last_version = data['version']
  46. min_ha_version = data['minHAVersion']
  47. release_notes = data['releaseNotes']
  48. if StrictVersion(last_version) <= StrictVersion(VERSION):
  49. if notify_if_latest:
  50. hass.components.persistent_notification.async_create(
  51. "You're already using the latest version", title='SmartIR')
  52. return
  53. if StrictVersion(current_ha_version) >= StrictVersion(min_ha_version):
  54. if do_update:
  55. files = data['files']
  56. abspath = os.path.dirname(os.path.abspath(__file__))
  57. for file in files:
  58. try:
  59. source = REMOTE_BASE_DIR + file
  60. dest = os.path.join(abspath, file)
  61. os.makedirs(os.path.dirname(dest), exist_ok=True)
  62. Helper.downloader(source, dest)
  63. except:
  64. _LOGGER.error("Error updating %s. Please update the file manually.", file)
  65. has_errors = True
  66. else:
  67. hass.components.persistent_notification.async_create(
  68. release_notes, title='SmartIR')
  69. else:
  70. hass.components.persistent_notification.async_create(
  71. "There is a new version of SmartIR, but it is **incompatible** "
  72. "with your HA version. Please first update Home Assistant.", title='SmartIR')
  73. else:
  74. _LOGGER.error("Invalid response from the server while checking for a new version")
  75. has_errors = True
  76. if do_update:
  77. if has_errors:
  78. hass.components.persistent_notification.async_create(
  79. "There was an error updating SmartIR. Please "
  80. "check the logs for more information.", title='SmartIR')
  81. else:
  82. hass.components.persistent_notification.async_create(
  83. "Successfully updated to {}. Please restart Home Assistant."
  84. .format(last_version), title='SmartIR')
  85. class Helper():
  86. @staticmethod
  87. def downloader(source, dest):
  88. req = requests.get(source, stream=True, timeout=10)
  89. if req.status_code == 200:
  90. with open(dest, 'wb') as fil:
  91. for chunk in req.iter_content(1024):
  92. fil.write(chunk)
  93. else:
  94. raise Exception('File not found')
  95. @staticmethod
  96. def pronto2lirc(pronto):
  97. codes = [int(binascii.hexlify(pronto[i:i+2]), 16) for i in range(0, len(pronto), 2)]
  98. if codes[0]:
  99. raise ValueError('Pronto code should start with 0000')
  100. if len(codes) != 4 + 2 * (codes[2] + codes[3]):
  101. raise ValueError('Number of pulse widths does not match the preamble')
  102. frequency = 1 / (codes[1] * 0.241246)
  103. return [int(round(code / frequency)) for code in codes[4:]]
  104. @staticmethod
  105. def lirc2broadlink(pulses):
  106. array = bytearray()
  107. for pulse in pulses:
  108. pulse = int(pulse * 269 / 8192)
  109. if pulse < 256:
  110. array += bytearray(struct.pack('>B', pulse))
  111. else:
  112. array += bytearray([0x00])
  113. array += bytearray(struct.pack('>H', pulse))
  114. packet = bytearray([0x26, 0x00])
  115. packet += bytearray(struct.pack('<H', len(array)))
  116. packet += array
  117. packet += bytearray([0x0d, 0x05])
  118. # Add 0s to make ultimate packet size a multiple of 16 for 128-bit AES encryption.
  119. remainder = (len(packet) + 4) % 16
  120. if remainder:
  121. packet += bytearray(16 - remainder)
  122. return packet