__init__.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import aiofiles
  2. import aiohttp
  3. import asyncio
  4. import binascii
  5. from distutils.version import StrictVersion
  6. import json
  7. import logging
  8. import os.path
  9. import requests
  10. import struct
  11. import voluptuous as vol
  12. from aiohttp import ClientSession
  13. from homeassistant.const import (
  14. ATTR_FRIENDLY_NAME, __version__ as current_ha_version)
  15. import homeassistant.helpers.config_validation as cv
  16. from homeassistant.helpers.typing import ConfigType
  17. _LOGGER = logging.getLogger(__name__)
  18. DOMAIN = 'smartir'
  19. VERSION = '1.17.8'
  20. MANIFEST_URL = (
  21. "https://raw.githubusercontent.com/"
  22. "smartHomeHub/SmartIR/{}/"
  23. "custom_components/smartir/manifest.json")
  24. REMOTE_BASE_URL = (
  25. "https://raw.githubusercontent.com/"
  26. "smartHomeHub/SmartIR/{}/"
  27. "custom_components/smartir/")
  28. COMPONENT_ABS_DIR = os.path.dirname(
  29. os.path.abspath(__file__))
  30. CONF_CHECK_UPDATES = 'check_updates'
  31. CONF_UPDATE_BRANCH = 'update_branch'
  32. CONFIG_SCHEMA = vol.Schema({
  33. DOMAIN: vol.Schema({
  34. vol.Optional(CONF_CHECK_UPDATES, default=True): cv.boolean,
  35. vol.Optional(CONF_UPDATE_BRANCH, default='master'): vol.In(
  36. ['master', 'rc'])
  37. })
  38. }, extra=vol.ALLOW_EXTRA)
  39. async def async_setup(hass, config):
  40. """Set up the SmartIR component."""
  41. conf = config.get(DOMAIN)
  42. if conf is None:
  43. return True
  44. check_updates = conf[CONF_CHECK_UPDATES]
  45. update_branch = conf[CONF_UPDATE_BRANCH]
  46. async def _check_updates(service):
  47. await _update(hass, update_branch)
  48. async def _update_component(service):
  49. await _update(hass, update_branch, True)
  50. hass.services.async_register(DOMAIN, 'check_updates', _check_updates)
  51. hass.services.async_register(DOMAIN, 'update_component', _update_component)
  52. if check_updates:
  53. await _update(hass, update_branch, False, False)
  54. return True
  55. async def _update(hass, branch, do_update=False, notify_if_latest=True):
  56. try:
  57. async with aiohttp.ClientSession() as session:
  58. async with session.get(MANIFEST_URL.format(branch)) as response:
  59. if response.status == 200:
  60. data = await response.json(content_type='text/plain')
  61. min_ha_version = data['homeassistant']
  62. last_version = data['updater']['version']
  63. release_notes = data['updater']['releaseNotes']
  64. if StrictVersion(last_version) <= StrictVersion(VERSION):
  65. if notify_if_latest:
  66. hass.components.persistent_notification.async_create(
  67. "You're already using the latest version!",
  68. 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 integration, but it is **incompatible** "
  73. "with your system. Please first update Home Assistant.", title='SmartIR')
  74. return
  75. if do_update is False:
  76. hass.components.persistent_notification.async_create(
  77. "A new version of SmartIR integration is available ({}). "
  78. "Call the ``smartir.update_component`` service to update "
  79. "the integration. \n\n **Release notes:** \n{}"
  80. .format(last_version, release_notes), title='SmartIR')
  81. return
  82. # Begin update
  83. files = data['updater']['files']
  84. has_errors = False
  85. for file in files:
  86. try:
  87. source = REMOTE_BASE_URL.format(branch) + file
  88. dest = os.path.join(COMPONENT_ABS_DIR, file)
  89. os.makedirs(os.path.dirname(dest), exist_ok=True)
  90. await Helper.downloader(source, dest)
  91. except Exception:
  92. has_errors = True
  93. _LOGGER.error("Error updating %s. Please update the file manually.", file)
  94. if has_errors:
  95. hass.components.persistent_notification.async_create(
  96. "There was an error updating one or more files of SmartIR. "
  97. "Please check the logs for more information.", title='SmartIR')
  98. else:
  99. hass.components.persistent_notification.async_create(
  100. "Successfully updated to {}. Please restart Home Assistant."
  101. .format(last_version), title='SmartIR')
  102. except Exception:
  103. _LOGGER.error("An error occurred while checking for updates.")
  104. class Helper():
  105. @staticmethod
  106. async def downloader(source, dest):
  107. async with aiohttp.ClientSession() as session:
  108. async with session.get(source) as response:
  109. if response.status == 200:
  110. async with aiofiles.open(dest, mode='wb') as f:
  111. await f.write(await response.read())
  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