__init__.py 5.4 KB

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