__init__.py 5.4 KB

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