Переглянути джерело

Support for light devices (#997)

* Implement an IR/RF controlled light entity.

Supports commands for on/off, brighten/dim, colder/warmer and night.
Start with a configuration for an Iris Ohyama light.

* Get light configs from the correct subdirectory.

* light: supported_color_modes is a list not a bitfield.

* Since self._supported_color_modes is an array, access it as one

* Don't include ColorMode.WHITE if ColorMode.COLOR_TEMP is supported.

* Simplify supported_color_modes as only one is supported at a time

* light: 1000 (Iris Ohyama) add intermediate steps.

Total steps is 10 (5 in each direction from "centre"), not 5.

* Fix some issues found in testing.

- Save the previous value in closest_match so we can judge whether it was
  closer than the higher value.
- There are various cases where we support brightness, so use a separate variable to track that
- Add some debug logging to changes
- Don't fallback to the "on" command when we got a brightness or color temperature but decided it was the same step we are on, so didn't do anything.

* light: Iris Ohyama (1000): Use the memory function

The remote has "Full" (full brightness, mid color temp), "Night" (nightlight)
and "Memory recall" buttons for turning on, and a "Memory set" button for
saving the current brightness and color temp in memory.

- Use the "Memory save" before the "off" command to save as we turn off.
- Use "Memory recall" rather than "Full" for turning on.

* Avoid resync when value is not changing

When using this with Adaptive lighting, during the day the light keeps beeping due to reaching the end of its range every 90s.
This is because Adaptive lighting is trying to adjust the brightness and color temperature, but they are not actually moving because of the limited number of steps.
Putting the resync code inside the condition that we actually need to move the brightness should prevent this, and only resync when we are actually changing to the end of the range.

* light: handle None value in closest_match.

* Light: properly replace None with 0 in closest_match

* Light: update to use async_track_state_change_event callback

* Lights: add four more light remote controls
Jason Rumney 1 рік тому
батько
коміт
7a58024d3c

+ 44 - 0
codes/light/1000.json

@@ -0,0 +1,44 @@
+{
+    "manufacturer": "Iris Ohyama",
+    "supportedModels": [
+        "LEDHCL-R2"
+    ],
+    "supportedController": "Broadlink",
+    "commandsEncoding": "Base64",
+    "brightness": [
+        26,
+        51,
+        77,
+        102,
+        128,
+        153,
+        179,
+        204,
+        230,
+        255
+    ],
+    "colorTemperature": [
+        2700,
+        3122,
+        3544,
+        3967,
+        4389,
+        4811,
+        5233,
+        5656,
+        6078,
+        6500
+    ],
+    "commands": {
+        "on": "JgACAbUfMhAQEQ8REBEQERAQEBEQETAREBEQEBAREBEQEBARMRAQERAREBEPERAREBEPERAREg8QEBAREBEPERAREBEQEBARMRAQETEQMRERDzERMBEQAAEntCAyDxAREBEQEQ8REBEQEQ8RMREPERAREBEPERAREBEwERAREBAQERAREBAQERAREBAQEREQEBEPERAREBEPERAREBEwERARMBExEBARMRAxERAAASa1IDEQEBEQEBAREBEQEBAREBEwERAREBEPERAREBEPETERDxEQERAREBAQERAREBAQERAREBAQERAREQ8QEREQEBAQETERDxExETAREBEwETEQEAANBQ==",
+        "off": [
+            "JgAEAT8ith4yDxAREBEQEBAREBEQEQ8RMREPERAREBEPERAREBEQEBARERAwERAREBAQERAREBAQEREQEBEPERAREBEPERAREBEwETEQMREwERARMBEQERAAASa1IDEQEBEQEBAREBEQEBAREBEwERAREBEPERAREBEPEREQEBEPETERDxEQERAREBAQERAREBAQERAREBAQERAREBAQETERMBEwETIQEBAxEQ8REAABJ7YeMhAPERAREBEPEREQEBEQEDEREBAREBAREBAQERAREBAQERARMBEQERARDxEREBEQDxEQERAREBAQERAREBAQERARMBExEDERMBEQETAREBEQAA0F",
+            "JgAEAUAgsyExEg8QEBEQEg8QEBEREBAQMRERDxEQEBEQETERDxEQEBARERAQEBEQEBEQEQ8REg8REA8REBEQEQ8REBERDxARERAwERARMBExETIPMRAQERAAASa0ITEQERAQERAQERAQERAQEBExEBEQERAQEBEQMRAQERAREBEQEBAREBEQEBAREBEQEBAREBEQEBEQEBEQEBASDxEQEDIQEBAyEDERMRAxEBAREAABJrMhMhEPEQ8REBEREA8REBEREDEQERAQEBAREBExEBEQEBAQEREQERAPEREQERAPEREQERAPERERDxEQEBAREBERDxARMRAQETIQMRAxEDIPERARAA0F"
+        ],
+        "brighten": "JgAEAUMgtCAyDxARERAQEBARERAQERAQMREPEREQEBEPERARERAQEBEQERAQEBARMRAQERAREBAQERAREQ8QERAREBEQEBAREBExEBARMRAREBAQMREQEBEAASa0IDIQDxEREBAREBAQEREQEBAxEREPERAQEREPEBEQERAREBAREBAREBAyEBAQEBEQERAQERAQERAQEBEREBAQEBEQETEQERAwERAREBExEBAREAABJrUfMhAQEQ8RERAREBAQEBEQETEQEBERDxARERAQEBAREBEQEBARERAREDAREBEPERAREBEPERAREBEQEBAREBEQEBARMRAREDEQERAQETEQERARAA0F",
+        "dim": "JgAEAUAhtCAxEBAREBEREBAQERAREBAQMREQEBARERARDxAREBEQEDIQEQ8REBAREQ8QEREQEBAREBARERAPERARERAPEREQMBExERAQMRExEBARMRAQEREAASW1IDEQEBEQEBAREBERDxAREBEwERARERAPEREQEBEQEBARMRAREBAREBAREBAREBAREBAREBAQEREQEQ8REBAREQ8yEDEQERAyDzEREBAxERAQEQABJrMhMhAQEBEQEBEQEBAREBEQEDEREBAREBEQEQ8QEREQERAxEBARDxEQEREQEQ8QEREQEBAQERAREBAREBEQEBAREDEQMREQETEQMBEQETARERAQAA0F",
+        "colder": "JgAEAUAgtCAyDxEQERARDxIPERAREBAQMhARDxEQERARDxEQERARDxEQERARDzIQEQ8SDxEQEQ8REBEQEBEQEBEQERARDxEQERAxEBEQEQ8yEBEPMhEQDxEAASa0IDIQEBAREBEQEBAREBEQEQ8yEBEPERAQEREQEBAREBEQEBAQEREQMRAREBAQERAREBAQEBEREBAQERAREBEPERAREDEQERAREDEQERAwERAREAABJrUgMRAREA8REBEREBAQERAREDARERARDxARERARDxARERAQEBARERAwEREQERAQEBEQERAQEBEQERAQEBEQERAQEBARMRAREBEQMBEQETEQEBEQAA0F",
+        "warmer": "JgAEAUAgtSAxEBAREQ8REBEQEQ8SDxEQMRAQERAREBAREBEQEBAREBARMBEREBAQEBEREBEPEBEREBEPEBEQERAQERAQEREQDxEREBARMRAwERARMg8REBAAASa0ITARERAREBAQERAQERAQERAyDxEQERAQEBEQERARDxEQEBEyDxAREBEPERARERAQEBEQERAQEBARERAQEBEQERAQEBEQEBEyDzEQEg8xERAQEQABJrMhMhAPEREQEBEPEREQEBEPETIQEBAREBEQEQ8REBAREQ8REDEQERAREBAQEBEQERAREBAQEREQEBAREBEQDxEREBEQEBAQETEQMhAQEDIQEBARAA0F",
+        "night": "JgAEAUAhtCAyEBAQERAREA8RERAREBEPMhARDxARERARDxEQMg8REBEQEQ8REBEQEBAREBEQERAQEBEQERAQEBEQEBEQEBEQEBExEBEQMRAyDxEQERAQEBEAASa0IDIQEBAQEREQEBAQEREQERAxEBEQEBAREBEQEBAxERAQERAREBAQERAQERAQERAREBAQEBEREBEPERAREBEQEBAQETEQEBExEDIQEBAREBEQEQABJbUgMRAREBAQEBEREBEPERAQETEQERARDxARERARDzIQEBEQEBARERAQEBEQERAPEREQERAQEBEQERAQEBEQERAQEBEQMRAREDIPMhAQERAQERARAA0F"
+    }
+}

+ 30 - 0
codes/light/1020.json

@@ -0,0 +1,30 @@
+{
+    "manufacturer": "NEC",
+    "supportedModels": [
+        "RE0201-CH1",
+    ],
+    "supportedController": "Broadlink",
+    "commandsEncoding": "Base64",
+    "brightness": [
+        26,
+        51,
+        77,
+        102,
+        128,
+        153,
+        179,
+        204,
+        230,
+        255
+    ],
+    "commands": {
+        "on": "JgBIAAABJ5QTEhI4EhMTEhMSExITEhM3EzcTEhM3EzgSExI4EjgSExM3ExITNxM3EzcTNxMTEjgSExI4EhMSExMSExITNxMSEwANBQ==",
+        "off": [
+            "JgBIAAABJpQTEhI4ExITEhMSExITEhM3EzcTExI4EjgSExI4FTUTEhM3ExITNxM3EzcTOBITEjgSExI4ExITEhMSExITNxMSEwANBQ==",
+            "JgBOAAABJ5QTEhI4EhMSExITExITEhM3EzcTEhM3EzcTExI4EjgSExITEjgTNxM3EzcTNxMSEzgSOBITEhMSExITExITNxMSEwAH6RYOEgANBQ=="
+        ],
+        "brighten": "JgBYAAABKJMVERI4EhMSExITEhMSExI4EzcTEhM3EzcTEhM4EjgSExITEjgSExM3EzcTNxMSEzcTOBITEjgSExITEhMSOBMSEwAFYAABJkoSAAxYAAEmShIADQU=",
+        "dim": "JgBYAAABJpQUERM3ExITEhMSExMSExI4EjgSExM3EzcTEhM3EzcTEhM4EjgSExI4EzcTNxMSEzcTEhMSEzgSExITExISOBITEgAFYQABJkoSAAxYAAEnSRMADQU=",
+        "night": "JgBIAAABJpQTEhI4ExITEhMSExITEhM3EzcTEhM4EjgSExI4EzcTEhMSExITNxM3EzcTOBITEjgSOBM3ExITEhMSExITNxMSEwANBQ=="
+    }
+}

+ 30 - 0
codes/light/1021.json

@@ -0,0 +1,30 @@
+{
+    "manufacturer": "NEC",
+    "supportedModels": [
+        "RE0201-CH2"
+    ],
+    "supportedController": "Broadlink",
+    "commandsEncoding": "Base64",
+    "brightness": [
+        26,
+        51,
+        77,
+        102,
+        128,
+        153,
+        179,
+        204,
+        230,
+        255
+    ],
+    "commands": {
+        "on": "JgBIAAABJ5QVEBI4EhMSExMSExITEhM3EzcTEhM3EzgSExI4EjgSExU1ExITNxM3EzcWNBMTEhMSExI4EhMSExMSExITNxM3EwANBQ==",
+        "off": [
+            "JgBIAAABJ5MUERM4EhMSExITEhMVEBI4EzcTEhM3EzcTEhM3EzgSExI4EhMSOBM3EzcTNxMSExITEhM4EhMSExITEhMSOBI4EwANBQ==",
+            "JgBIAAABJ5MUERM3ExMSExITEhMSExI4EjgTEhM3EzcTEhM3EzgSExITEjgSOBI4EzcTNxMSExITNxMTEhMSExITEhMSOBI4EwANBQ=="
+        ],
+        "brighten": "JgBYAAABJ5MUERM3ExITExITEhMSExI4EjgSExM3EzcTEhM3EzcTEhMTEjgSExI4EjgTNxMSExITNxMSEzcTEhMTEhMSOBI4EgAFYAABJ0kTAAxUAAErSRMADQU=",
+        "dim": "JgBYAAABKpEVEBI4EhMTEhMSExITEhM3FjQTEhM4EjgSExI4EzcTEhM3EzcTEhM4EjgSOBITEhMSExMSEzcTEhMSExITNxM3EwAFYAABJ0kTAAxaAAElShIADQU=",
+        "night": "JgBIAAABJpQTEhM3ExITEhMSExITEhM3EzgSExI4EjgTEhM3EzcTEhMSExITOBI4EjgSOBMSExITNxM3ExITEhMSExMSOBI4EgANBQ=="
+    }
+}

+ 56 - 0
codes/light/1040.json

@@ -0,0 +1,56 @@
+{
+    "manufacturer": "Toshiba",
+    "supportedModels": [
+        "FRC-199T"
+    ],
+    "supportedController": "Broadlink",
+    "commandsEncoding": "Base64",
+    "brightness": [
+        16,
+        32,
+        48,
+        64,
+        80,
+        96,
+        112,
+        128,
+        144,
+        160,
+        176,
+        192,
+        208,
+        224,
+        240,
+        255
+    ],
+    "colorTemperature": [
+        2700,
+        2953,
+        3207,
+        3460,
+        3713,
+        3967,
+        4220,
+        4473,
+        4727,
+        4980,
+        5233,
+        5487,
+        5740,
+        5993,
+        6247,
+        6500
+    ],
+    "commands": {
+        "on": "",
+        "off": [
+            "",
+            ""
+        ],
+        "brighten": "",
+        "dim": "",
+        "colder": "",
+        "warmer": "",
+        "night": ""
+    }
+}

+ 56 - 0
codes/light/1060.json

@@ -0,0 +1,56 @@
+{
+    "manufacturer": "Takizumi",
+    "supportedModels": [
+        "TLR-002"
+    ],
+    "supportedController": "Broadlink",
+    "commandsEncoding": "Base64",
+    "brightness": [
+        16,
+        32,
+        48,
+        64,
+        80,
+        96,
+        112,
+        128,
+        144,
+        160,
+        176,
+        192,
+        208,
+        224,
+        240,
+        255
+    ],
+    "colorTemperature": [
+        2700,
+        2953,
+        3207,
+        3460,
+        3713,
+        3967,
+        4220,
+        4473,
+        4727,
+        4980,
+        5233,
+        5487,
+        5740,
+        5993,
+        6247,
+        6500
+    ],
+    "commands": {
+        "on": "JgDYAAABKY8UERMRFDUUEBQRExITEBQ1FBETNhISFBEROBQQFDUSExMRFDUUEBQREzYUNRITExETNhQQFDYTNhQQFBETNhQ1FAAFoAABKpATERQQFDUUERMRFBAUEBQ2ExEUNRQRERMTNhQQFDYRExQQFDUUERMRFDUSOBMRExEUNRQREzYTNhITExETNhQ1FAAFoAABJ5MTERQQFDYTERQQFBAUERM2FBAUNRQRExEUNRQREzYUEBQQFDYTERQQFDUUNhQQFBAUNhMRFDUUNhMRFBAUNRQ2FAANBQ==",
+        "off": [
+            "JgAYAwABJpMVDxQREzYUEBQQFBEUEBM2FBAUNhQQFBAUNRQREzYUEBQQFDYUEBQQFDYTNhQQFBAUNhQQFDUUNhMRFBAUNRQ2EwAFoAABJ5MUEBQQFDYUEBQQFBAUERM2FBAUNhMRExEUNRQQFDYUEBQQFDYTERQQFDUUNhMRFBAUNRQRFDUUNRQRExEROBU0FAAFoAABKZEUEBQQFDUUERMRFBAUEBI4ExEUNRQQFBETNhQQFDUVEBQQEjcUEBQREzYUNRUQExEUNRQQFDYUNRQQFBAUNhQ1FQAFngABJ5MUEBQREzYUEBQQFBETERQ1FBAUNhMRFBAUNhMRFDUUEBQREzYUEBQQFDYTNhQQFBETNhQQFDUUNhMRFBAUNRQ2EwAFoAABJ5MSEhQREzYTERQQFBAUERM2FBAUNRQRExEUNRQREzYTERQQFTUTERQQFDUUNhMRFBETNhMREzYUNRITExESNxQ1FAAFoQABJpMTERMRFDUUERMREhIUEBQ2EhIUNRQQFBETNhISFDYTERMSEzUUERMREzYUNRQRExEUNRQQFDYUNRQQFBETNhQ1FAAFoAABJpMUERMRFDUUEBQRExEUEBQ1FBETNhMRFBAUNhMRFDUUERMREzYUEBQQFDYTNhQQFBEROBMRFDUUNhMRFBAUNhM2EwAFoQABJpMTERQQFDYTEhMQFBETERQ1FBAUNhMRFBAUNRQREzYTERQQFDYTERQREzYTNhMRFBASOBMRFDUSNxITExEUNRQ2EwAFoAABKZESEhQQFDUSExMRFBETEBQ2ExITNRITExESNxQREzYTERMRFDUUERMRFDUSOBMRExEUNRITEzYSNxQQFBETNhI3EgAFogABKZASExMREzYUEBQRExETERQ1FBETNhITExETNhISEzYSExMREzYSEhQREzYSNxITExETNhISFDYROBISExEUNhE4EgAFogABKJESEhQREzYSEhQQFBERExM2FBAUNhETExITNRITEzYSEhQREzYTEhMREzYROBISExEUNhEUEjYSOBETExESNxI4EgANBQ==",
+            "JgDYAAABJZMUEBISEjgSEhISEhISExE4FBASOBMREhISNxQRETgUEBITERMROBM2EzcROBQ1FBESNxQ1FBERExETEhISExE4EgAFogABKJIVDxISEjgTERISEhISExE4FBATNhMSERMSNxMREzcUEBISExIROBM2EzcTNhI3FBASOBQ1FBATEhETEhISEhI4FAAFoAABJ5MTERISEjcUERETEhISEhI4EhISNxMRExIROBQQEjgRExISEhISOBI3FTQSOBM2FBASOBM2FBASEhITERMSEhI3EwANBQ=="
+        ],
+        "brighten": "JgDYAAABJpMUEBISEjgSEhISEhISExE4ExESOBISEhISNxMSETgTERISEhMRExISEjcTEhE4ExESOBI3EzYVNRISEjcTERI4EwAFoQABKJEVEBISEjcVEBETEhISEhI4ExESNxMREhMROBMREjgSEhISEhISExETETgTERI4EhISNxM3ETgUNRUPEjgTERI3EwAFoQABJ5MVDxITETgTERISEhMRExI3ExESOBISEhISOBETEjcTERITERMSEhISEjgUEBI3ExESOBE4EzYVNRISEjcTEhE4EwANBQ==",
+        "dim": "JgCQAAABJ5ESEhITETgSEhISEhMRExE4EhISOBETEhISNxITETgSEhITERMROBISEjgROBI3EhMROBI3EhMROBISEhISExE4EgAFoQABKZESExETEjcSEhITERMSEhI3EhMROBISEhISOBISEjcSExETEhISNxITETgSNxI4ERMSNxI4ERMSNxISEhMRExI3EgANBQ==",
+        "colder": "JgAgAQABJZMVDxQQFDYUEBQQFBETERE4FBAUNhQQFBAXMxMRFDUUEBQQFBETNhQQFBETERQ1FBAUNhQ1FBAUNhI3EzYUERQ1EwAFoQABJpMVEBMRFDUUERMRExEUERM2ExETNxMQFBETNhMRFDYTERMRFBAUNhMRExEUERM2ERQSNhI4ExETNhQ1EjgSEhM2EgAFogABKZESEhQREzYTEhMRExETERM2EhMTNhITEhITNhETEzYSExMRExETNhITExETERM2EhMTNhI3EhIUNhE4EzYSExE4EgAFogABKZESEhMSEzUSExMRExEUERM2ERQSNhITExETNhMRFDYRExMRFBETNhETExITEBQ2ExETNhI4ERMTNhI4ETgSEhQ1EgANBQ==",
+        "warmer": "JgDYAAABJ5ERExISEjcSExETEhISEhI4ERMSNxITERMROBISEjgRExISEhMRExMREhITNhI4ERMSNxI4ETgSNxI4ERMSEhI3EgAFowABKZASEhISEjgRExISEhMRExM2EhISOBETEhITNhITETgSEhITERMRExMRExEUNhE4EhISOBE4EjcSOBE4EhISEhI4EgAFoQABKZESEhITEzYSEhQRExETERQ1FBETNhISEhIUNhETEzYSExMRExEUEBQRExETNhI3EhMTNhI3EjgROBI3EhMTERM2EwANBQ==",
+        "night": "JgDYAAABJpISExETEjcSExETERMSEhI4ERMROBISEhMROBISEjcSExETEhISEhI4EjcSEhI4ERMSNxI4ETgSEhISEjgRExI3EgAFoQABKpESExETETgSEhITERMSEhI3EhMROBITERMROBISEjcSExETEhISEhI4ETgSEhI4ERMROBI4ETgSEhISEjgRExI3EgAFowABKZASEhITETgSEhITERMRFBE3EhMROBISEhISOBETEjcSEhITERMSEhM2EjgSEhI3EhMROBI3EjgRExISEjcSExE4EgANBQ=="
+    }
+}

+ 382 - 0
custom_components/smartir/light.py

@@ -0,0 +1,382 @@
+import asyncio
+import json
+import logging
+import os.path
+
+import voluptuous as vol
+
+from homeassistant.components.light import (
+    ATTR_BRIGHTNESS,
+    ATTR_COLOR_TEMP_KELVIN,
+    ColorMode,
+    LightEntity,
+    PLATFORM_SCHEMA,
+)
+from homeassistant.const import (
+    CONF_NAME,
+    STATE_OFF,
+    STATE_ON,
+)
+from homeassistant.core import callback
+from homeassistant.helpers.event import async_track_state_change_event
+import homeassistant.helpers.config_validation as cv
+from homeassistant.helpers.restore_state import RestoreEntity
+from . import COMPONENT_ABS_DIR, Helper
+from .controller import get_controller
+
+_LOGGER = logging.getLogger(__name__)
+
+DEFAULT_NAME = "SmartIR Light"
+DEFAULT_DELAY = 0.5
+
+CONF_UNIQUE_ID = "unique_id"
+CONF_DEVICE_CODE = "device_code"
+CONF_CONTROLLER_DATA = "controller_data"
+CONF_DELAY = "delay"
+CONF_POWER_SENSOR = "power_sensor"
+
+CMD_BRIGHTNESS_INCREASE = "brighten"
+CMD_BRIGHTNESS_DECREASE = "dim"
+CMD_COLORMODE_COLDER = "colder"
+CMD_COLORMODE_WARMER = "warmer"
+CMD_POWER_ON = "on"
+CMD_POWER_OFF = "off"
+CMD_NIGHTLIGHT = "night"
+
+PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
+    {
+        vol.Optional(CONF_UNIQUE_ID): cv.string,
+        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
+        vol.Required(CONF_DEVICE_CODE): cv.positive_int,
+        vol.Required(CONF_CONTROLLER_DATA): cv.string,
+        vol.Optional(CONF_DELAY, default=DEFAULT_DELAY): cv.string,
+        vol.Optional(CONF_POWER_SENSOR): cv.entity_id,
+    }
+)
+
+
+async def async_setup_platform(
+    hass,
+    config,
+    async_add_entities,
+    discovery_info=None,
+):
+    """Set up the IR Light platform."""
+    device_code = config.get(CONF_DEVICE_CODE)
+    device_files_subdir = os.path.join("codes", "light")
+    device_files_absdir = os.path.join(COMPONENT_ABS_DIR, device_files_subdir)
+
+    if not os.path.isdir(device_files_absdir):
+        os.makedirs(device_files_absdir)
+
+    device_json_filename = str(device_code) + ".json"
+    device_json_path = os.path.join(device_files_absdir, device_json_filename)
+
+    if not os.path.exists(device_json_path):
+        _LOGGER.warning(
+            "Couldn't find the device Json file. The component "
+            "will try to download it from the Github repo."
+        )
+
+        try:
+            codes_source = (
+                "https://raw.githubusercontent.com/"
+                "smartHomeHub/SmartIR/master/"
+                "codes/light/{}.json"
+            )
+
+            await Helper.downloader(
+                codes_source.format(device_code),
+                device_json_path,
+            )
+        except Exception:
+            _LOGGER.error(
+                "There was an error while downloading the device Json file. "
+                "Please check your internet connection or if the device code "
+                "exists on GitHub. If the problem still exists please "
+                "place the file manually in the proper directory."
+            )
+            return
+
+    with open(device_json_path) as j:
+        try:
+            device_data = json.load(j)
+        except Exception:
+            _LOGGER.error("The device JSON file is invalid")
+            return
+
+    async_add_entities([SmartIRLight(hass, config, device_data)])
+
+
+# find the closest match in a sorted list
+def closest_match(value, list):
+    prev_val = None
+    for index, entry in enumerate(list):
+        if entry > (value or 0):
+            if prev_val is None:
+                return index
+            diff_lo = value - prev_val
+            diff_hi = entry - value
+            if diff_lo < diff_hi:
+                return index - 1
+            return index
+        prev_val = entry
+
+    return len(list) - 1
+
+
+class SmartIRLight(LightEntity, RestoreEntity):
+    def __init__(self, hass, config, device_data):
+        self.hass = hass
+        self._unique_id = config.get(CONF_UNIQUE_ID)
+        self._name = config.get(CONF_NAME)
+        self._device_code = config.get(CONF_DEVICE_CODE)
+        self._controller_data = config.get(CONF_CONTROLLER_DATA)
+        self._delay = config.get(CONF_DELAY)
+        self._power_sensor = config.get(CONF_POWER_SENSOR)
+
+        self._manufacturer = device_data["manufacturer"]
+        self._supported_models = device_data["supportedModels"]
+        self._supported_controller = device_data["supportedController"]
+        self._commands_encoding = device_data["commandsEncoding"]
+        self._brightnesses = device_data["brightness"]
+        self._colortemps = device_data["colorTemperature"]
+        self._commands = device_data["commands"]
+
+        self._power = STATE_ON
+        self._brightness = None
+        self._colortemp = None
+
+        self._temp_lock = asyncio.Lock()
+        self._on_by_remote = False
+        self._support_color_mode = ColorMode.UNKNOWN
+
+        if (
+            CMD_COLORMODE_COLDER in self._commands
+            and CMD_COLORMODE_WARMER in self._commands
+        ):
+            self._colortemp = self.max_color_temp_kelvin
+            self._support_color_mode = ColorMode.COLOR_TEMP
+
+        if CMD_NIGHTLIGHT in self._commands or (
+            CMD_BRIGHTNESS_INCREASE in self._commands
+            and CMD_BRIGHTNESS_DECREASE in self._commands
+        ):
+            self._brightness = 100
+            self._support_brightness = True
+            if self._support_color_mode == ColorMode.UNKNOWN:
+                self._support_color_mode = ColorMode.BRIGHTNESS
+        else:
+            self._support_brightness = False
+
+        if (
+            CMD_POWER_OFF in self._commands
+            and CMD_POWER_ON in self._commands
+            and self._support_color_mode == ColorMode.UNKNOWN
+        ):
+            self._support_color_mode = ColorMode.ONOFF
+
+        # Init the IR/RF controller
+        self._controller = get_controller(
+            self.hass,
+            self._supported_controller,
+            self._commands_encoding,
+            self._controller_data,
+            self._delay,
+        )
+
+    async def async_added_to_hass(self):
+        """Run when entity about to be added."""
+        await super().async_added_to_hass()
+
+        last_state = await self.async_get_last_state()
+        if last_state is not None:
+            self._power = last_state.state
+            if ATTR_BRIGHTNESS in last_state.attributes:
+                self._brightness = last_state.attributes[ATTR_BRIGHTNESS]
+            if ATTR_COLOR_TEMP_KELVIN in last_state.attributes:
+                self._colortemp = last_state.attributes[ATTR_COLOR_TEMP_KELVIN]
+
+        if self._power_sensor:
+            async_track_state_change_event(
+                self.hass, self._power_sensor, self._async_power_sensor_changed
+            )
+
+    @property
+    def unique_id(self):
+        """Return a unique ID."""
+        return self._unique_id
+
+    @property
+    def name(self):
+        """Return the display name of the light."""
+        return self._name
+
+    @property
+    def supported_color_modes(self):
+        """Return the list of supported color modes."""
+        return [self._support_color_mode]
+
+    @property
+    def color_mode(self):
+        return self._support_color_mode
+
+    @property
+    def color_temp_kelvin(self):
+        return self._colortemp
+
+    @property
+    def min_color_temp_kelvin(self):
+        if self._colortemps:
+            return self._colortemps[0]
+
+    @property
+    def max_color_temp_kelvin(self):
+        if self._colortemps:
+            return self._colortemps[-1]
+
+    @property
+    def is_on(self):
+        return self._power == STATE_ON or self._on_by_remote
+
+    @property
+    def brightness(self):
+        return self._brightness
+
+    @property
+    def extra_state_attributes(self):
+        """Platform specific attributes."""
+        return {
+            "device_code": self._device_code,
+            "manufacturer": self._manufacturer,
+            "supported_models": self._supported_models,
+            "supported_controller": self._supported_controller,
+            "commands_encoding": self._commands_encoding,
+            "on_by_remote": self._on_by_remote,
+        }
+
+    async def async_turn_on(self, **params):
+        did_something = False
+        # Turn the light on if off
+        if self._power != STATE_ON and not self._on_by_remote:
+            self._power = STATE_ON
+            did_something = True
+            await self.send_command(CMD_POWER_ON)
+
+        if (
+            ATTR_COLOR_TEMP_KELVIN in params
+            and ColorMode.COLOR_TEMP == self._support_color_mode
+        ):
+            target = params.get(ATTR_COLOR_TEMP_KELVIN)
+            old_color_temp = closest_match(self._colortemp, self._colortemps)
+            new_color_temp = closest_match(target, self._colortemps)
+            _LOGGER.debug(
+                f"Changing color temp from {self._colortemp}K step {old_color_temp} to {target}K step {new_color_temp}"
+            )
+
+            steps = new_color_temp - old_color_temp
+            did_something = True
+            if steps < 0:
+                cmd = CMD_COLORMODE_WARMER
+                steps = abs(steps)
+            else:
+                cmd = CMD_COLORMODE_COLDER
+
+            if steps > 0 and cmd:
+                # If we are heading for the highest or lowest value,
+                # take the opportunity to resync by issuing enough
+                # commands to go the full range.
+                if new_color_temp == len(self._colortemps) - 1 or new_color_temp == 0:
+                    steps = len(self._colortemps)
+                self._colortemp = self._colortemps[new_color_temp]
+                await self.send_command(cmd, steps)
+
+        if ATTR_BRIGHTNESS in params and self._support_brightness:
+            # before checking the supported brightnesses, make a special case
+            # when a nightlight is fitted for brightness of 1
+            if params.get(ATTR_BRIGHTNESS) == 1 and CMD_NIGHTLIGHT in self._commands:
+                self._brightness = 1
+                self._power = STATE_ON
+                did_something = True
+                await self.send_command(CMD_NIGHTLIGHT)
+
+            elif self._brightnesses:
+                target = params.get(ATTR_BRIGHTNESS)
+                old_brightness = closest_match(self._brightness, self._brightnesses)
+                new_brightness = closest_match(target, self._brightnesses)
+                did_something = True
+                _LOGGER.debug(
+                    f"Changing brightness from {self._brightness} step {old_brightness} to {target} step {new_brightness}"
+                )
+                steps = new_brightness - old_brightness
+                if steps < 0:
+                    cmd = CMD_BRIGHTNESS_DECREASE
+                    steps = abs(steps)
+                else:
+                    cmd = CMD_BRIGHTNESS_INCREASE
+
+                if steps > 0 and cmd:
+                    # If we are heading for the highest or lowest value,
+                    # take the opportunity to resync by issuing enough
+                    # commands to go the full range.
+                    if (
+                        new_brightness == len(self._brightnesses) - 1
+                        or new_brightness == 0
+                    ):
+                        steps = len(self._colortemps)
+                    did_something = True
+                    self._brightness = self._brightnesses[new_brightness]
+                    await self.send_command(cmd, steps)
+
+        # If we did nothing above, and the light is not detected as on
+        # already issue the on command, even though we think the light
+        # is on.  This is because we may be out of sync due to use of the
+        # remote when we don't have anything to detect it.
+        # If we do have such monitoring, avoid issuing the command in case
+        # on and off are the same remote code.
+        if not did_something and not self._on_by_remote:
+            self._power = STATE_ON
+            await self.send_command(CMD_POWER_ON)
+
+        await self.async_write_ha_state()
+
+    async def async_turn_off(self):
+        self._power = STATE_OFF
+        await self.send_command(CMD_POWER_OFF)
+
+    async def async_toggle(self):
+        await (self.async_turn_on() if not self.is_on else self.async_turn_off())
+
+    async def send_command(self, cmd, count=1):
+        if cmd not in self._commands:
+            _LOGGER.error(f"Unknown command '{cmd}'")
+            return
+        _LOGGER.debug(f"Sending {cmd} remote command {count} times.")
+        remote_cmd = self._commands.get(cmd)
+        async with self._temp_lock:
+            self._on_by_remote = False
+            try:
+                for _ in range(count):
+                    await self._controller.send(remote_cmd)
+            except Exception as e:
+                _LOGGER.exception(e)
+
+    @callback
+    async def _async_power_sensor_changed(self, event):
+    ):
+        """Handle power sensor changes."""
+        new_state = event.data["new_state"]
+        if new_state is None:
+            return
+        old_state = event.data["old_state"]
+        if new_state.state == old_state.state:
+            return
+
+        if new_state.state == STATE_ON:
+            self._on_by_remote = True
+            await self.async_write_ha_state()
+
+        if new_state.state == STATE_OFF:
+            self._on_by_remote = False
+            self._power = STATE_OFF
+            await self.async_write_ha_state()

+ 2 - 1
custom_components/smartir/manifest.json

@@ -15,9 +15,10 @@
       "climate.py",
       "media_player.py",
       "fan.py",
+      "light.py",  
       "controller.py",
       "manifest.json",
       "services.yaml"
     ]
   }
-}
+}

+ 73 - 0
docs/LIGHT.md

@@ -0,0 +1,73 @@
+<p align="center">
+    <a href="#"><img src="assets/smartir_light.png" width="350" alt="SmartIR light"></a>
+</p>
+
+For this platform to work, we need a .json file containing all the necessary IR or RF commands.
+Find your device's brand code [here](LIGHT.md#available-codes-for-light-devices) and add the number in the `device_code` field. The component will download it to the correct folder.  If your device is not working, you will need to learn your own codes and place the .json file in `smartir/codes/fan` subfolders. Please note that the `device_code` field only accepts positive numbers. The .json extension is not required.
+
+## Configuration variables
+
+**name** (Optional): The name of the device<br />
+**nuique_id** (Optional): An ID that uniquely identified this device. If two devices have the same unique ID, Home Assistant will raise an exception.<br />
+**device_code** (Required): ...... (Accepts only positive numbers)<br />
+**controller_data** (Required): The data required for the controller to function. Enter the entity_id of the Broadlink or Xiaomi IR controller, or the MQTT topic on which to send commands.<br />
+**delay** (Optional): Adjusts the delay in seconds between multiple commands. The default is 0.5 <br />
+**power_sensor** (Optional): *entity_id* for a sensor that monitors whether your device is actually On or Off. This may be a power monitor sensor. (Accepts only on/off states)<br />
+
+## Example (using broadlink controller)
+
+Add a Broadlink RM device named "Bedroom" via config flow (read the [docs](https://www.homeassistant.io/integrations/broadlink/)).
+
+```yaml
+smartir:
+
+light:
+  - platform: smartir
+    name: Bedroom Ceiling Light
+    unique_id: bedroom_ceiling_light
+    device_code: 1000
+    controller_data: remote.bedroom_remote
+    power_sensor: binary_sensor.bedroom_light_power
+```
+
+## Light configuration
+
+As well as the generic settings, the light supports two lists:
+`brightness` and `color_temperature`.  These should be sorted lists
+from lower to higher values of brightness on a scale of 1 to 255, and
+color temperature in Kelvin (normally from 2700 to 6500).  Supported
+commands are "on", "off", "brighten", "dim", "warmer", "colder" and "night".
+If "night" is configured, it is implemented as a special brightness step that
+can be selected by setting a brightness of 1 (such lights usually have a
+separate small and dim nightlight bulb inside the fixture).
+
+
+## Available codes for Light devices
+
+The following are the code files created by the amazing people in the community. Before you start creating your own code file, try if one of them works for your device. **Please open an issue if your device is working and not included in the supported models.**
+Contributing your own code files is welcome. However, we do not accept incomplete files as well as files related to MQTT controllers.
+
+#### Iris Ohyama
+
+| Code                             | Supported Models | Controller |
+|----------------------------------|------------------|------------|
+| [1000](../codes/light/1000.json) | LEDHCL-R2        | Broadlink  |
+
+#### NEC
+
+| Code                             | Supported Models | Controller |
+|----------------------------------|------------------|------------|
+| [1020](../codes/light/1020.json) | RE0201 CH1       | Broadlink  |
+| [1021](../codes/light/1021.json) | RE0201 CH2       | Broadlink  |
+
+#### Toshiba
+
+| Code                             | Supported Models | Controller |
+|----------------------------------|------------------|------------|
+| [1040](../codes/light/1040.json) | FRC-199T         | Broadlink  |
+
+#### Takizumi
+
+| Code                             | Supported Models | Controller |
+|----------------------------------|------------------|------------|
+| [1060](../codes/light/1060.json) | TLR-002          | Broadlink  |

+ 3 - 1
docs/README.md

@@ -1,7 +1,7 @@
 [![](https://img.shields.io/github/v/release/smartHomeHub/SmartIR.svg?style=flat-square)](https://github.com/smartHomeHub/SmartIR/releases/latest) [![](https://img.shields.io/badge/HACS-Custom-orange.svg?style=flat-square)](https://github.com/custom-components/hacs)
 
 ## Overview
-SmartIR is a custom integration for controlling **climate devices**, **media players** and **fans** via infrared controllers.<br>
+SmartIR is a custom integration for controlling **climate devices**, **media players**, **fans** and **lights** via infrared controllers.<br>
 SmartIR currently supports the following controllers:
 * [Broadlink](https://www.home-assistant.io/integrations/broadlink/)
 * [Xiaomi IR Remote (ChuangmiIr)](https://www.home-assistant.io/integrations/remote.xiaomi_miio/)
@@ -24,6 +24,7 @@ It should look similar to this:
 |       |-- __init__.py
 |       |-- climate.py
 |       |-- fan.py
+|       |-- light.py
 |       |-- media_player.py
 |       |-- etc...
 ```
@@ -56,6 +57,7 @@ Click on the links below for instructions on how to configure each platform.
 * [Climate platform](/docs/CLIMATE.md)
 * [Media Player platform](/docs/MEDIA_PLAYER.md)
 * [Fan platform](/docs/FAN.md)
+* [Light platform](docs/LIGHT.md)
 <br><br>
 
 ## See also

BIN
docs/assets/smartir_light.png