light.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import asyncio
  2. import aiofiles
  3. import json
  4. import logging
  5. import os.path
  6. import voluptuous as vol
  7. from homeassistant.components.light import (
  8. ATTR_BRIGHTNESS,
  9. ATTR_COLOR_TEMP_KELVIN,
  10. ColorMode,
  11. LightEntity,
  12. PLATFORM_SCHEMA,
  13. )
  14. from homeassistant.const import (
  15. CONF_NAME,
  16. STATE_OFF,
  17. STATE_ON,
  18. )
  19. from homeassistant.core import callback
  20. from homeassistant.helpers.event import async_track_state_change_event
  21. import homeassistant.helpers.config_validation as cv
  22. from homeassistant.helpers.restore_state import RestoreEntity
  23. from . import COMPONENT_ABS_DIR, Helper
  24. from .controller import get_controller
  25. _LOGGER = logging.getLogger(__name__)
  26. DEFAULT_NAME = "SmartIR Light"
  27. DEFAULT_DELAY = 0.5
  28. CONF_UNIQUE_ID = "unique_id"
  29. CONF_DEVICE_CODE = "device_code"
  30. CONF_CONTROLLER_DATA = "controller_data"
  31. CONF_DELAY = "delay"
  32. CONF_POWER_SENSOR = "power_sensor"
  33. CMD_BRIGHTNESS_INCREASE = "brighten"
  34. CMD_BRIGHTNESS_DECREASE = "dim"
  35. CMD_COLORMODE_COLDER = "colder"
  36. CMD_COLORMODE_WARMER = "warmer"
  37. CMD_POWER_ON = "on"
  38. CMD_POWER_OFF = "off"
  39. CMD_NIGHTLIGHT = "night"
  40. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
  41. {
  42. vol.Optional(CONF_UNIQUE_ID): cv.string,
  43. vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
  44. vol.Required(CONF_DEVICE_CODE): cv.positive_int,
  45. vol.Required(CONF_CONTROLLER_DATA): cv.string,
  46. vol.Optional(CONF_DELAY, default=DEFAULT_DELAY): cv.string,
  47. vol.Optional(CONF_POWER_SENSOR): cv.entity_id,
  48. }
  49. )
  50. async def async_setup_platform(
  51. hass,
  52. config,
  53. async_add_entities,
  54. discovery_info=None,
  55. ):
  56. """Set up the IR Light platform."""
  57. device_code = config.get(CONF_DEVICE_CODE)
  58. device_files_subdir = os.path.join("codes", "light")
  59. device_files_absdir = os.path.join(COMPONENT_ABS_DIR, device_files_subdir)
  60. if not os.path.isdir(device_files_absdir):
  61. os.makedirs(device_files_absdir)
  62. device_json_filename = str(device_code) + ".json"
  63. device_json_path = os.path.join(device_files_absdir, device_json_filename)
  64. if not os.path.exists(device_json_path):
  65. _LOGGER.warning(
  66. "Couldn't find the device Json file. The component "
  67. "will try to download it from the Github repo."
  68. )
  69. try:
  70. codes_source = (
  71. "https://raw.githubusercontent.com/"
  72. "smartHomeHub/SmartIR/master/"
  73. "codes/light/{}.json"
  74. )
  75. await Helper.downloader(
  76. codes_source.format(device_code),
  77. device_json_path,
  78. )
  79. except Exception:
  80. _LOGGER.error(
  81. "There was an error while downloading the device Json file. "
  82. "Please check your internet connection or if the device code "
  83. "exists on GitHub. If the problem still exists please "
  84. "place the file manually in the proper directory."
  85. )
  86. return
  87. try:
  88. async with aiofiles.open(device_json_path, mode='r') as j:
  89. _LOGGER.debug(f"loading json file {device_json_path}")
  90. content = await j.read()
  91. device_data = json.loads(content)
  92. _LOGGER.debug(f"{device_json_path} file loaded")
  93. except Exception:
  94. _LOGGER.error("The device JSON file is invalid")
  95. return
  96. async_add_entities([SmartIRLight(hass, config, device_data)])
  97. # find the closest match in a sorted list
  98. def closest_match(value, list):
  99. prev_val = None
  100. for index, entry in enumerate(list):
  101. if entry > (value or 0):
  102. if prev_val is None:
  103. return index
  104. diff_lo = value - prev_val
  105. diff_hi = entry - value
  106. if diff_lo < diff_hi:
  107. return index - 1
  108. return index
  109. prev_val = entry
  110. return len(list) - 1
  111. class SmartIRLight(LightEntity, RestoreEntity):
  112. def __init__(self, hass, config, device_data):
  113. self.hass = hass
  114. self._unique_id = config.get(CONF_UNIQUE_ID)
  115. self._name = config.get(CONF_NAME)
  116. self._device_code = config.get(CONF_DEVICE_CODE)
  117. self._controller_data = config.get(CONF_CONTROLLER_DATA)
  118. self._delay = config.get(CONF_DELAY)
  119. self._power_sensor = config.get(CONF_POWER_SENSOR)
  120. self._manufacturer = device_data["manufacturer"]
  121. self._supported_models = device_data["supportedModels"]
  122. self._supported_controller = device_data["supportedController"]
  123. self._commands_encoding = device_data["commandsEncoding"]
  124. self._brightnesses = device_data["brightness"]
  125. self._colortemps = device_data["colorTemperature"]
  126. self._commands = device_data["commands"]
  127. self._power = STATE_ON
  128. self._brightness = None
  129. self._colortemp = None
  130. self._temp_lock = asyncio.Lock()
  131. self._on_by_remote = False
  132. self._support_color_mode = ColorMode.UNKNOWN
  133. if (
  134. CMD_COLORMODE_COLDER in self._commands
  135. and CMD_COLORMODE_WARMER in self._commands
  136. ):
  137. self._colortemp = self.max_color_temp_kelvin
  138. self._support_color_mode = ColorMode.COLOR_TEMP
  139. if CMD_NIGHTLIGHT in self._commands or (
  140. CMD_BRIGHTNESS_INCREASE in self._commands
  141. and CMD_BRIGHTNESS_DECREASE in self._commands
  142. ):
  143. self._brightness = 100
  144. self._support_brightness = True
  145. if self._support_color_mode == ColorMode.UNKNOWN:
  146. self._support_color_mode = ColorMode.BRIGHTNESS
  147. else:
  148. self._support_brightness = False
  149. if (
  150. CMD_POWER_OFF in self._commands
  151. and CMD_POWER_ON in self._commands
  152. and self._support_color_mode == ColorMode.UNKNOWN
  153. ):
  154. self._support_color_mode = ColorMode.ONOFF
  155. # Init the IR/RF controller
  156. self._controller = get_controller(
  157. self.hass,
  158. self._supported_controller,
  159. self._commands_encoding,
  160. self._controller_data,
  161. self._delay,
  162. )
  163. async def async_added_to_hass(self):
  164. """Run when entity about to be added."""
  165. await super().async_added_to_hass()
  166. last_state = await self.async_get_last_state()
  167. if last_state is not None:
  168. self._power = last_state.state
  169. if ATTR_BRIGHTNESS in last_state.attributes:
  170. self._brightness = last_state.attributes[ATTR_BRIGHTNESS]
  171. if ATTR_COLOR_TEMP_KELVIN in last_state.attributes:
  172. self._colortemp = last_state.attributes[ATTR_COLOR_TEMP_KELVIN]
  173. if self._power_sensor:
  174. async_track_state_change_event(
  175. self.hass, self._power_sensor, self._async_power_sensor_changed
  176. )
  177. @property
  178. def unique_id(self):
  179. """Return a unique ID."""
  180. return self._unique_id
  181. @property
  182. def name(self):
  183. """Return the display name of the light."""
  184. return self._name
  185. @property
  186. def supported_color_modes(self):
  187. """Return the list of supported color modes."""
  188. return [self._support_color_mode]
  189. @property
  190. def color_mode(self):
  191. return self._support_color_mode
  192. @property
  193. def color_temp_kelvin(self):
  194. return self._colortemp
  195. @property
  196. def min_color_temp_kelvin(self):
  197. if self._colortemps:
  198. return self._colortemps[0]
  199. @property
  200. def max_color_temp_kelvin(self):
  201. if self._colortemps:
  202. return self._colortemps[-1]
  203. @property
  204. def is_on(self):
  205. return self._power == STATE_ON or self._on_by_remote
  206. @property
  207. def brightness(self):
  208. return self._brightness
  209. @property
  210. def extra_state_attributes(self):
  211. """Platform specific attributes."""
  212. return {
  213. "device_code": self._device_code,
  214. "manufacturer": self._manufacturer,
  215. "supported_models": self._supported_models,
  216. "supported_controller": self._supported_controller,
  217. "commands_encoding": self._commands_encoding,
  218. "on_by_remote": self._on_by_remote,
  219. }
  220. async def async_turn_on(self, **params):
  221. did_something = False
  222. # Turn the light on if off
  223. if self._power != STATE_ON and not self._on_by_remote:
  224. self._power = STATE_ON
  225. did_something = True
  226. await self.send_command(CMD_POWER_ON)
  227. if (
  228. ATTR_COLOR_TEMP_KELVIN in params
  229. and ColorMode.COLOR_TEMP == self._support_color_mode
  230. ):
  231. target = params.get(ATTR_COLOR_TEMP_KELVIN)
  232. old_color_temp = closest_match(self._colortemp, self._colortemps)
  233. new_color_temp = closest_match(target, self._colortemps)
  234. _LOGGER.debug(
  235. f"Changing color temp from {self._colortemp}K step {old_color_temp} to {target}K step {new_color_temp}"
  236. )
  237. steps = new_color_temp - old_color_temp
  238. did_something = True
  239. if steps < 0:
  240. cmd = CMD_COLORMODE_WARMER
  241. steps = abs(steps)
  242. else:
  243. cmd = CMD_COLORMODE_COLDER
  244. if steps > 0 and cmd:
  245. # If we are heading for the highest or lowest value,
  246. # take the opportunity to resync by issuing enough
  247. # commands to go the full range.
  248. if new_color_temp == len(self._colortemps) - 1 or new_color_temp == 0:
  249. steps = len(self._colortemps)
  250. self._colortemp = self._colortemps[new_color_temp]
  251. await self.send_command(cmd, steps)
  252. if ATTR_BRIGHTNESS in params and self._support_brightness:
  253. # before checking the supported brightnesses, make a special case
  254. # when a nightlight is fitted for brightness of 1
  255. if params.get(ATTR_BRIGHTNESS) == 1 and CMD_NIGHTLIGHT in self._commands:
  256. self._brightness = 1
  257. self._power = STATE_ON
  258. did_something = True
  259. await self.send_command(CMD_NIGHTLIGHT)
  260. elif self._brightnesses:
  261. target = params.get(ATTR_BRIGHTNESS)
  262. old_brightness = closest_match(self._brightness, self._brightnesses)
  263. new_brightness = closest_match(target, self._brightnesses)
  264. did_something = True
  265. _LOGGER.debug(
  266. f"Changing brightness from {self._brightness} step {old_brightness} to {target} step {new_brightness}"
  267. )
  268. steps = new_brightness - old_brightness
  269. if steps < 0:
  270. cmd = CMD_BRIGHTNESS_DECREASE
  271. steps = abs(steps)
  272. else:
  273. cmd = CMD_BRIGHTNESS_INCREASE
  274. if steps > 0 and cmd:
  275. # If we are heading for the highest or lowest value,
  276. # take the opportunity to resync by issuing enough
  277. # commands to go the full range.
  278. if (
  279. new_brightness == len(self._brightnesses) - 1
  280. or new_brightness == 0
  281. ):
  282. steps = len(self._colortemps)
  283. did_something = True
  284. self._brightness = self._brightnesses[new_brightness]
  285. await self.send_command(cmd, steps)
  286. # If we did nothing above, and the light is not detected as on
  287. # already issue the on command, even though we think the light
  288. # is on. This is because we may be out of sync due to use of the
  289. # remote when we don't have anything to detect it.
  290. # If we do have such monitoring, avoid issuing the command in case
  291. # on and off are the same remote code.
  292. if not did_something and not self._on_by_remote:
  293. self._power = STATE_ON
  294. await self.send_command(CMD_POWER_ON)
  295. self.async_write_ha_state()
  296. async def async_turn_off(self):
  297. self._power = STATE_OFF
  298. await self.send_command(CMD_POWER_OFF)
  299. self.async_write_ha_state()
  300. async def async_toggle(self):
  301. await (self.async_turn_on() if not self.is_on else self.async_turn_off())
  302. async def send_command(self, cmd, count=1):
  303. if cmd not in self._commands:
  304. _LOGGER.error(f"Unknown command '{cmd}'")
  305. return
  306. _LOGGER.debug(f"Sending {cmd} remote command {count} times.")
  307. remote_cmd = self._commands.get(cmd)
  308. async with self._temp_lock:
  309. self._on_by_remote = False
  310. try:
  311. for _ in range(count):
  312. await self._controller.send(remote_cmd)
  313. except Exception as e:
  314. _LOGGER.exception(e)
  315. @callback
  316. async def _async_power_sensor_changed(self, event):
  317. """Handle power sensor changes."""
  318. new_state = event.data["new_state"]
  319. if new_state is None:
  320. return
  321. old_state = event.data["old_state"]
  322. if new_state.state == old_state.state:
  323. return
  324. if new_state.state == STATE_ON:
  325. self._on_by_remote = True
  326. self.async_write_ha_state()
  327. if new_state.state == STATE_OFF:
  328. self._on_by_remote = False
  329. self._power = STATE_OFF
  330. self.async_write_ha_state()