__init__.py 5.8 KB

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