__init__.py 5.4 KB

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