Example #1
0
    def _turn_on_rgb_and_w(self, hex_template, **kwargs):
        """Turn on RGB or RGBW child device."""
        rgb = list(color_util.color_hs_to_RGB(*self._hs))
        white = self._white
        hex_color = self._values.get(self.value_type)
        hs_color = kwargs.get(ATTR_HS_COLOR)
        if hs_color is not None:
            new_rgb = color_util.color_hs_to_RGB(*hs_color)
        else:
            new_rgb = None
        new_white = kwargs.get(ATTR_WHITE_VALUE)

        if new_rgb is None and new_white is None:
            return
        if new_rgb is not None:
            rgb = list(new_rgb)
        if hex_template == "%02x%02x%02x%02x":
            if new_white is not None:
                rgb.append(new_white)
            else:
                rgb.append(white)
        hex_color = hex_template % tuple(rgb)
        if len(rgb) > 3:
            white = rgb.pop()
        self.gateway.set_child_value(
            self.node_id, self.child_id, self.value_type, hex_color, ack=1
        )

        if self.assumed_state:
            # optimistically assume that light has changed state
            self._hs = color_util.color_RGB_to_hs(*rgb)
            self._white = white
            self._values[self.value_type] = hex_color
Example #2
0
    def turn_on(self, **kwargs):
        """Turn the light on."""
        if not self.is_on:
            self._lamp.switch(True)
        if ATTR_BRIGHTNESS in kwargs:
            brightness = int((kwargs[ATTR_BRIGHTNESS] / 255.0) * 200.0)
            self._lamp.brightness(brightness)
            return

        if ATTR_HS_COLOR in kwargs:
            rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
            self._lamp.rgb(*rgb)
            return

        if ATTR_COLOR_TEMP in kwargs:
            kelvin = int(
                color_util.color_temperature_mired_to_kelvin(
                    kwargs[ATTR_COLOR_TEMP]))
            self._lamp.white(kelvin)
            return

        if ATTR_EFFECT in kwargs:
            effect = kwargs[ATTR_EFFECT]
            self._lamp.effect(effect)
            return
    def state_attributes(self):
        """Return state attributes."""
        if not self.is_on:
            return None

        data = {}
        supported_features = self.supported_features

        if supported_features & SUPPORT_BRIGHTNESS:
            data[ATTR_BRIGHTNESS] = self.brightness

        if supported_features & SUPPORT_COLOR_TEMP:
            data[ATTR_COLOR_TEMP] = self.color_temp

        if supported_features & SUPPORT_COLOR and self.hs_color:
            # pylint: disable=unsubscriptable-object,not-an-iterable
            hs_color = self.hs_color
            data[ATTR_HS_COLOR] = (round(hs_color[0],
                                         3), round(hs_color[1], 3))
            data[ATTR_RGB_COLOR] = color_util.color_hs_to_RGB(*hs_color)
            data[ATTR_XY_COLOR] = color_util.color_hs_to_xy(*hs_color)

        if supported_features & SUPPORT_WHITE_VALUE:
            data[ATTR_WHITE_VALUE] = self.white_value

        if supported_features & SUPPORT_EFFECT:
            data[ATTR_EFFECT] = self.effect

        return {key: val for key, val in data.items() if val is not None}
Example #4
0
 def turn_on(self, **kwargs):
     """Instruct the light to turn on, optionally set colour/brightness."""
     # when no arguments, just turn light on (full brightness)
     if not kwargs:
         self._light.turn_on()
     else:
         if ATTR_HS_COLOR in kwargs and ATTR_BRIGHTNESS in kwargs:
             rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
             bright = int(kwargs[ATTR_BRIGHTNESS] / 255 * 100)
             self._light.set_all(rgb[0], rgb[1], rgb[2], bright)
         elif ATTR_HS_COLOR in kwargs:
             rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
             self._light.set_rgb_color(rgb[0], rgb[1], rgb[2])
         elif ATTR_BRIGHTNESS in kwargs:
             bright = int(kwargs[ATTR_BRIGHTNESS] / 255 * 100)
             self._light.set_brightness(bright)
Example #5
0
    def set_flash(self, flash) -> None:
        """Activate flash."""
        if flash:
            if int(self._bulb.last_properties["color_mode"]) != 1:
                _LOGGER.error("Flash supported currently only in RGB mode")
                return

            transition = int(self.config[CONF_TRANSITION])
            if flash == FLASH_LONG:
                count = 1
                duration = transition * 5
            if flash == FLASH_SHORT:
                count = 1
                duration = transition * 2

            red, green, blue = color_util.color_hs_to_RGB(*self._hs)

            transitions = []
            transitions.append(
                RGBTransition(255, 0, 0, brightness=10, duration=duration))
            transitions.append(SleepTransition(duration=transition))
            transitions.append(
                RGBTransition(red,
                              green,
                              blue,
                              brightness=self.brightness,
                              duration=duration))

            flow = Flow(count=count, transitions=transitions)
            try:
                self._bulb.start_flow(flow, light_type=self.light_type)
            except BulbException as ex:
                _LOGGER.error("Unable to set flash: %s", ex)
Example #6
0
 def turn_on(self, **kwargs):
     """Instruct the light to turn on."""
     self._light.light_on()
     if ATTR_HS_COLOR in kwargs:
         self._rgb_color = color_util.color_hs_to_RGB(
             *kwargs[ATTR_HS_COLOR])
         self._light.set_color(*self._rgb_color)
         self._effect = None
     if ATTR_BRIGHTNESS in kwargs:
         self._brightness = kwargs.get(ATTR_BRIGHTNESS)
         brightness = int(self._brightness / 255 * 100)
         self._light.set_light_option(lw12.LW12_LIGHT.BRIGHTNESS,
                                      brightness)
     if ATTR_EFFECT in kwargs:
         self._effect = kwargs[ATTR_EFFECT].replace(" ", "_").upper()
         # Check if a known and supported effect was selected.
         if self._effect in [eff.name for eff in lw12.LW12_EFFECT]:
             # Selected effect is supported and will be applied.
             self._light.set_effect(lw12.LW12_EFFECT[self._effect])
         else:
             # Unknown effect was set, recover by disabling the effect
             # mode and log an error.
             _LOGGER.error("Unknown effect selected: %s", self._effect)
             self._effect = None
     if ATTR_TRANSITION in kwargs:
         transition_speed = int(kwargs[ATTR_TRANSITION])
         self._light.set_light_option(lw12.LW12_LIGHT.FLASH,
                                      transition_speed)
     self._state = True
Example #7
0
 def turn_on(self, **kwargs):
     """Turn on the light."""
     if ATTR_HS_COLOR in kwargs:
         rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
         self._device.led_rgb = rgb
     elif ATTR_BRIGHTNESS in kwargs:
         self._device.led_intensity = _to_skybell_level(
             kwargs[ATTR_BRIGHTNESS])
     else:
         self._device.led_intensity = _to_skybell_level(255)
Example #8
0
 async def async_turn_on(self, **kwargs):
     """Turn the light on."""
     if ATTR_BRIGHTNESS in kwargs:
         brightness_pct = kwargs[ATTR_BRIGHTNESS] / 255.0
         await self._lightpad.set_config({"glowIntensity": brightness_pct})
     elif ATTR_HS_COLOR in kwargs:
         hs_color = kwargs[ATTR_HS_COLOR]
         red, green, blue = color_util.color_hs_to_RGB(*hs_color)
         await self._lightpad.set_glow_color(red, green, blue, 0)
     else:
         await self._lightpad.set_config({"glowEnabled": True})
Example #9
0
 def turn_on(self, **kwargs):
     """Instruct the light to turn on."""
     if not kwargs:
         self._light.set_brightness(4095)
     else:
         if ATTR_BRIGHTNESS in kwargs:
             bright = round((kwargs[ATTR_BRIGHTNESS] / 255) * 4095)
             self._light.set_brightness(bright)
         if ATTR_HS_COLOR in kwargs:
             rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
             self._light.set_rgb(rgb[0], rgb[1], rgb[2])
Example #10
0
    def turn_on(self, **kwargs: Any) -> None:
        """Turn the light on."""
        if ATTR_HS_COLOR in kwargs and self._color:
            rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
            self.vera_device.set_color(rgb)
        elif ATTR_BRIGHTNESS in kwargs and self.vera_device.is_dimmable:
            self.vera_device.set_brightness(kwargs[ATTR_BRIGHTNESS])
        else:
            self.vera_device.switch_on()

        self._state = True
        self.schedule_update_op_state(True)
Example #11
0
    async def async_turn_on(self, **kwargs):
        """Turn the device on."""
        self.async_set_duration(**kwargs)

        rgbw = None
        white = kwargs.get(ATTR_WHITE_VALUE)
        hs_color = kwargs.get(ATTR_HS_COLOR)
        color_temp = kwargs.get(ATTR_COLOR_TEMP)

        if hs_color is not None:
            rgbw = "#"
            for colorval in color_util.color_hs_to_RGB(*hs_color):
                rgbw += f"{colorval:02x}"
            if self._color_channels and self._color_channels & COLOR_CHANNEL_COLD_WHITE:
                rgbw += "0000"
            else:
                # trim the CW value or it will not work correctly
                rgbw += "00"
            # white LED must be off in order for color to work

        elif white is not None:
            if self._color_channels & COLOR_CHANNEL_WARM_WHITE:
                # trim the CW value or it will not work correctly
                rgbw = f"#000000{white:02x}"
            else:
                rgbw = f"#00000000{white:02x}"

        elif color_temp is not None:
            # Limit color temp to min/max values
            cold = max(
                0,
                min(
                    255,
                    round((self._max_mireds - color_temp) /
                          (self._max_mireds - self._min_mireds) * 255),
                ),
            )
            warm = 255 - cold
            rgbw = f"#000000{warm:02x}{cold:02x}"

        if rgbw and self.values.color:
            self.values.color.send_value(rgbw)

        # Zwave multilevel switches use a range of [0, 99] to control
        # brightness. Level 255 means to set it to previous value.
        if ATTR_BRIGHTNESS in kwargs:
            brightness = kwargs[ATTR_BRIGHTNESS]
            brightness = byte_to_zwave_brightness(brightness)
        else:
            brightness = 255

        self.values.primary.send_value(brightness)
Example #12
0
def _close_enough(actual_rgb, testing_rgb):
    """Validate the given RGB value is in acceptable tolerance."""
    # Convert the given RGB values to hue / saturation and then back again
    # as it wasn't reading the same RGB value set against it.
    actual_hs = color_util.color_RGB_to_hs(*actual_rgb)
    actual_rgb = color_util.color_hs_to_RGB(*actual_hs)

    testing_hs = color_util.color_RGB_to_hs(*testing_rgb)
    testing_rgb = color_util.color_hs_to_RGB(*testing_hs)

    actual_red, actual_green, actual_blue = actual_rgb
    testing_red, testing_green, testing_blue = testing_rgb

    r_diff = abs(actual_red - testing_red)
    g_diff = abs(actual_green - testing_green)
    b_diff = abs(actual_blue - testing_blue)

    return (
        r_diff <= CLOSE_THRESHOLD
        and g_diff <= CLOSE_THRESHOLD
        and b_diff <= CLOSE_THRESHOLD
    )
Example #13
0
    def _light_internal_rgbw_color(self) -> tuple[int, int, int, int] | None:
        """Return the rgbw color value [int, int, int, int]."""
        rgbw_color = self.rgbw_color
        if (rgbw_color is None and self.hs_color is not None
                and self.white_value is not None):
            # Backwards compatibility for rgbw_color added in 2021.4
            # Add warning in 2021.6, remove in 2021.10
            r, g, b = color_util.color_hs_to_RGB(  # pylint: disable=invalid-name
                *self.hs_color)
            w = self.white_value  # pylint: disable=invalid-name
            rgbw_color = (r, g, b, w)

        return rgbw_color
Example #14
0
    def turn_on(self, **kwargs):
        """Turn the light on."""
        if ATTR_HS_COLOR in kwargs:
            rgb = color.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
        else:
            rgb = self._rgb

        if ATTR_BRIGHTNESS in kwargs:
            brightness_pct = int(100 * kwargs[ATTR_BRIGHTNESS] / 255)
        else:
            brightness_pct = self._brightness_pct

        self._gateway.light.set_rgb(brightness_pct, rgb)

        self.schedule_update_op_state()
Example #15
0
    def _turn_on(self, **kwargs):
        """Really turn the light on."""
        if self._supported_flags & SUPPORT_BRIGHTNESS:
            target_brightness = kwargs.get(ATTR_BRIGHTNESS)

            # No brightness specified, so we either restore it to
            # last brightness or switch it on at maximum level
            if target_brightness is None:
                if self._brightness == 0:
                    if self._last_brightness:
                        self._brightness = self._last_brightness
                    else:
                        self._brightness = 100
            else:
                # We set it to the target brightness and turn it on
                self._brightness = scaleto100(target_brightness)

        if self._supported_flags & SUPPORT_COLOR and (
                kwargs.get(ATTR_WHITE_VALUE) is not None
                or kwargs.get(ATTR_HS_COLOR) is not None):
            if self._reset_color:
                self._color = (100, 0)

            # Update based on parameters
            self._white = kwargs.get(ATTR_WHITE_VALUE, self._white)
            self._color = kwargs.get(ATTR_HS_COLOR, self._color)
            rgb = color_util.color_hs_to_RGB(*self._color)
            self.call_set_color(
                round(rgb[0]),
                round(rgb[1]),
                round(rgb[2]),
                round(self._white),
            )

            if self.state == "off":
                self.set_level(min(int(self._brightness), 99))
            return

        if self._reset_color:
            bri255 = scaleto255(self._brightness)
            self.call_set_color(bri255, bri255, bri255, bri255)

        if self._supported_flags & SUPPORT_BRIGHTNESS:
            self.set_level(min(int(self._brightness), 99))
            return

        # The simplest case is left for last. No dimming, just switch on
        self.call_turn_on()
Example #16
0
    def turn_on(self, **kwargs):
        """Turn the light on."""
        if ATTR_HS_COLOR in kwargs:
            self._hs = kwargs[ATTR_HS_COLOR]

        if ATTR_BRIGHTNESS in kwargs:
            self._brightness = int(100 * kwargs[ATTR_BRIGHTNESS] / 255)

        rgb = color_util.color_hs_to_RGB(*self._hs)
        rgba = (self._brightness, ) + rgb
        rgbhex = binascii.hexlify(struct.pack("BBBB", *rgba)).decode("ASCII")
        rgbhex = int(rgbhex, 16)

        if self._write_to_hub(self._sid, **{self._data_key: rgbhex}):
            self._state = True
            self.schedule_update_op_state()
Example #17
0
    def turn_on(self, **kwargs):
        """Instruct the light to turn on and set correct brightness & color."""
        if ATTR_HS_COLOR in kwargs:
            self._hs_color = kwargs[ATTR_HS_COLOR]
        if ATTR_BRIGHTNESS in kwargs:
            self._brightness = kwargs[ATTR_BRIGHTNESS]

        percent_bright = self._brightness / 255
        rgb_color = color_util.color_hs_to_RGB(*self._hs_color)
        self._blinkt.set_pixel(self._index, rgb_color[0], rgb_color[1],
                               rgb_color[2], percent_bright)

        self._blinkt.show()

        self._is_on = True
        self.schedule_update_op_state()
Example #18
0
    def turn_on(self, **kwargs):
        """Turn the specified light on."""
        self._state = True

        hs_color = kwargs.get(ATTR_HS_COLOR)
        brightness = kwargs.get(ATTR_BRIGHTNESS)

        if hs_color is not None:
            self._hs = hs_color
        if brightness is not None:
            self._brightness = brightness

        rgb = color_util.color_hs_to_RGB(*self._hs)

        self.set_state(rgb[0], rgb[1], rgb[2], self.brightness)
        self.schedule_update_op_state()
Example #19
0
    def turn_on(self, **kwargs) -> None:
        """Turn the bulb on."""
        brightness = kwargs.get(ATTR_BRIGHTNESS)
        colortemp = kwargs.get(ATTR_COLOR_TEMP)
        hs_color = kwargs.get(ATTR_HS_COLOR)
        rgb = color_util.color_hs_to_RGB(*hs_color) if hs_color else None
        flash = kwargs.get(ATTR_FLASH)
        effect = kwargs.get(ATTR_EFFECT)

        duration = int(self.config[CONF_TRANSITION])  # in ms
        if ATTR_TRANSITION in kwargs:  # passed kwarg overrides config
            duration = int(kwargs.get(ATTR_TRANSITION) * 1000)  # kwarg in s

        self.device.turn_on(
            duration=duration,
            light_type=self.light_type,
            power_mode=self._turn_on_power_mode,
        )

        if self.config[CONF_MODE_MUSIC] and not self._bulb.music_mode:
            try:
                self.set_music_mode(self.config[CONF_MODE_MUSIC])
            except BulbException as ex:
                _LOGGER.error(
                    "Unable to turn on music mode, consider disabling it: %s",
                    ex)

        try:
            # values checked for none in methods
            self.set_rgb(rgb, duration)
            self.set_colortemp(colortemp, duration)
            self.set_brightness(brightness, duration)
            self.set_flash(flash)
            self.set_effect(effect)
        except BulbException as ex:
            _LOGGER.error("Unable to set bulb properties: %s", ex)
            return

        # save the current state if we had a manual change.
        if self.config[CONF_SAVE_ON_CHANGE] and (brightness or colortemp
                                                 or rgb):
            try:
                self.set_default()
            except BulbException as ex:
                _LOGGER.error("Unable to set the defaults: %s", ex)
                return
        self.device.update()
Example #20
0
    def turn_on(self, **kwargs):
        """Turn the device on."""
        rgbw = None

        if ATTR_WHITE_VALUE in kwargs:
            self._white = kwargs[ATTR_WHITE_VALUE]

        if ATTR_COLOR_TEMP in kwargs:
            # Color temperature. With the AEOTEC ZW098 bulb, only two color
            # temperatures are supported. The warm and cold channel values
            # indicate brightness for warm/cold color temperature.
            if self._zw098:
                if kwargs[ATTR_COLOR_TEMP] > TEMP_MID_OPP:
                    self._ct = TEMP_WARM_OPP
                    rgbw = "#000000ff00"
                else:
                    self._ct = TEMP_COLD_OPP
                    rgbw = "#00000000ff"
        elif ATTR_HS_COLOR in kwargs:
            self._hs = kwargs[ATTR_HS_COLOR]
            if ATTR_WHITE_VALUE not in kwargs:
                # white LED must be off in order for color to work
                self._white = 0

        if (ATTR_WHITE_VALUE in kwargs
                or ATTR_HS_COLOR in kwargs) and self._hs is not None:
            rgbw = "#"
            for colorval in color_util.color_hs_to_RGB(*self._hs):
                rgbw += format(colorval, "02x")
            if self._white is not None:
                rgbw += format(self._white, "02x") + "00"
            else:
                rgbw += "0000"

        if rgbw and self.values.color:
            self.values.color.data = rgbw

        super().turn_on(**kwargs)
Example #21
0
 def _light_internal_convert_color(self, color_mode: str) -> dict:
     data: dict[str, tuple] = {}
     if color_mode == COLOR_MODE_HS and self.hs_color:
         hs_color = self.hs_color
         data[ATTR_HS_COLOR] = (round(hs_color[0],
                                      3), round(hs_color[1], 3))
         data[ATTR_RGB_COLOR] = color_util.color_hs_to_RGB(*hs_color)
         data[ATTR_XY_COLOR] = color_util.color_hs_to_xy(*hs_color)
     elif color_mode == COLOR_MODE_XY and self.xy_color:
         xy_color = self.xy_color
         data[ATTR_HS_COLOR] = color_util.color_xy_to_hs(*xy_color)
         data[ATTR_RGB_COLOR] = color_util.color_xy_to_RGB(*xy_color)
         data[ATTR_XY_COLOR] = (round(xy_color[0],
                                      6), round(xy_color[1], 6))
     elif color_mode == COLOR_MODE_RGB and self.rgb_color:
         rgb_color = self.rgb_color
         data[ATTR_HS_COLOR] = color_util.color_RGB_to_hs(*rgb_color)
         data[ATTR_RGB_COLOR] = tuple(int(x) for x in rgb_color[0:3])
         data[ATTR_XY_COLOR] = color_util.color_RGB_to_xy(*rgb_color)
     elif color_mode == COLOR_MODE_RGBW and self._light_internal_rgbw_color:
         rgbw_color = self._light_internal_rgbw_color
         rgb_color = color_util.color_rgbw_to_rgb(*rgbw_color)
         data[ATTR_HS_COLOR] = color_util.color_RGB_to_hs(*rgb_color)
         data[ATTR_RGB_COLOR] = tuple(int(x) for x in rgb_color[0:3])
         data[ATTR_RGBW_COLOR] = tuple(int(x) for x in rgbw_color[0:4])
         data[ATTR_XY_COLOR] = color_util.color_RGB_to_xy(*rgb_color)
     elif color_mode == COLOR_MODE_RGBWW and self.rgbww_color:
         rgbww_color = self.rgbww_color
         rgb_color = color_util.color_rgbww_to_rgb(*rgbww_color,
                                                   self.min_mireds,
                                                   self.max_mireds)
         data[ATTR_HS_COLOR] = color_util.color_RGB_to_hs(*rgb_color)
         data[ATTR_RGB_COLOR] = tuple(int(x) for x in rgb_color[0:3])
         data[ATTR_RGBWW_COLOR] = tuple(int(x) for x in rgbww_color[0:5])
         data[ATTR_XY_COLOR] = color_util.color_RGB_to_xy(*rgb_color)
     return data
Example #22
0
    def turn_on(self, **kwargs):
        """Turn the device on."""
        transition = int(kwargs.get(ATTR_TRANSITION, 0) * 10)
        if ATTR_EFFECT in kwargs:
            self.play_effect(kwargs[ATTR_EFFECT], transition)
            return

        if ATTR_HS_COLOR in kwargs:
            self._rgb_color = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
            self._luminary.set_rgb(*self._rgb_color, transition)

        if ATTR_COLOR_TEMP in kwargs:
            self._color_temp = kwargs[ATTR_COLOR_TEMP]
            self._luminary.set_temperature(
                int(color_util.color_temperature_mired_to_kelvin(self._color_temp)),
                transition,
            )

        self._is_on = True
        if ATTR_BRIGHTNESS in kwargs:
            self._brightness = kwargs[ATTR_BRIGHTNESS]
            self._luminary.set_luminance(int(self._brightness / 2.55), transition)
        else:
            self._luminary.set_onoff(True)
Example #23
0
async def test_device_types(opp: OpenPeerPower):
    """Test different device types."""
    mocked_bulb = _mocked_bulb()
    properties = {**PROPERTIES}
    properties.pop("active_mode")
    properties["color_mode"] = "3"
    mocked_bulb.last_properties = properties

    async def _async_setup(config_entry):
        with patch(f"{MODULE}.Bulb", return_value=mocked_bulb):
            await opp.config_entries.async_setup(config_entry.entry_id)
            await opp.async_block_till_done()

    async def _async_test(
        bulb_type,
        model,
        target_properties,
        nightlight_properties=None,
        name=UNIQUE_NAME,
        entity_id=ENTITY_LIGHT,
    ):
        config_entry = MockConfigEntry(
            domain=DOMAIN,
            data={
                **CONFIG_ENTRY_DATA,
                CONF_NIGHTLIGHT_SWITCH: False,
            },
        )
        config_entry.add_to_opp(opp)

        mocked_bulb.bulb_type = bulb_type
        model_specs = _MODEL_SPECS.get(model)
        type(mocked_bulb).get_model_specs = MagicMock(return_value=model_specs)
        await _async_setup(config_entry)

        state = opp.states.get(entity_id)
        assert state.state == "on"
        target_properties["friendly_name"] = name
        target_properties["flowing"] = False
        target_properties["night_light"] = True
        target_properties["music_mode"] = False
        assert dict(state.attributes) == target_properties

        await opp.config_entries.async_unload(config_entry.entry_id)
        await config_entry.async_remove(opp)
        registry = er.async_get(opp)
        registry.async_clear_config_entry(config_entry.entry_id)

        # nightlight
        if nightlight_properties is None:
            return
        config_entry = MockConfigEntry(
            domain=DOMAIN,
            data={
                **CONFIG_ENTRY_DATA,
                CONF_NIGHTLIGHT_SWITCH: True,
            },
        )
        config_entry.add_to_opp(opp)
        await _async_setup(config_entry)

        assert opp.states.get(entity_id).state == "off"
        state = opp.states.get(f"{entity_id}_nightlight")
        assert state.state == "on"
        nightlight_properties["friendly_name"] = f"{name} nightlight"
        nightlight_properties["icon"] = "mdi:weather-night"
        nightlight_properties["flowing"] = False
        nightlight_properties["night_light"] = True
        nightlight_properties["music_mode"] = False
        assert dict(state.attributes) == nightlight_properties

        await opp.config_entries.async_unload(config_entry.entry_id)
        await config_entry.async_remove(opp)
        registry.async_clear_config_entry(config_entry.entry_id)

    bright = round(255 * int(PROPERTIES["bright"]) / 100)
    current_brightness = round(255 * int(PROPERTIES["current_brightness"]) /
                               100)
    ct = color_temperature_kelvin_to_mired(int(PROPERTIES["ct"]))
    hue = int(PROPERTIES["hue"])
    sat = int(PROPERTIES["sat"])
    hs_color = (round(hue / 360 * 65536, 3), round(sat / 100 * 255, 3))
    rgb_color = color_hs_to_RGB(*hs_color)
    xy_color = color_hs_to_xy(*hs_color)
    bg_bright = round(255 * int(PROPERTIES["bg_bright"]) / 100)
    bg_ct = color_temperature_kelvin_to_mired(int(PROPERTIES["bg_ct"]))
    bg_rgb = int(PROPERTIES["bg_rgb"])
    bg_rgb_color = ((bg_rgb >> 16) & 0xFF, (bg_rgb >> 8) & 0xFF, bg_rgb & 0xFF)
    bg_hs_color = color_RGB_to_hs(*bg_rgb_color)
    bg_xy_color = color_RGB_to_xy(*bg_rgb_color)
    nl_br = round(255 * int(PROPERTIES["nl_br"]) / 100)

    # Default
    await _async_test(
        None,
        "mono",
        {
            "effect_list": YEELIGHT_MONO_EFFECT_LIST,
            "supported_features": SUPPORT_YEELIGHT,
            "brightness": bright,
            "color_mode": "brightness",
            "supported_color_modes": ["brightness"],
        },
    )

    # White
    await _async_test(
        BulbType.White,
        "mono",
        {
            "effect_list": YEELIGHT_MONO_EFFECT_LIST,
            "supported_features": SUPPORT_YEELIGHT,
            "brightness": bright,
            "color_mode": "brightness",
            "supported_color_modes": ["brightness"],
        },
    )

    # Color
    model_specs = _MODEL_SPECS["color"]
    await _async_test(
        BulbType.Color,
        "color",
        {
            "effect_list":
            YEELIGHT_COLOR_EFFECT_LIST,
            "supported_features":
            SUPPORT_YEELIGHT_RGB,
            "min_mireds":
            color_temperature_kelvin_to_mired(
                model_specs["color_temp"]["max"]),
            "max_mireds":
            color_temperature_kelvin_to_mired(
                model_specs["color_temp"]["min"]),
            "brightness":
            current_brightness,
            "color_temp":
            ct,
            "hs_color":
            hs_color,
            "rgb_color":
            rgb_color,
            "xy_color":
            xy_color,
            "color_mode":
            "hs",
            "supported_color_modes": ["color_temp", "hs"],
        },
        {
            "supported_features": 0,
            "color_mode": "onoff",
            "supported_color_modes": ["onoff"],
        },
    )

    # WhiteTemp
    model_specs = _MODEL_SPECS["ceiling1"]
    await _async_test(
        BulbType.WhiteTemp,
        "ceiling1",
        {
            "effect_list":
            YEELIGHT_TEMP_ONLY_EFFECT_LIST,
            "supported_features":
            SUPPORT_YEELIGHT_WHITE_TEMP,
            "min_mireds":
            color_temperature_kelvin_to_mired(
                model_specs["color_temp"]["max"]),
            "max_mireds":
            color_temperature_kelvin_to_mired(
                model_specs["color_temp"]["min"]),
            "brightness":
            current_brightness,
            "color_temp":
            ct,
            "color_mode":
            "color_temp",
            "supported_color_modes": ["color_temp"],
        },
        {
            "effect_list": YEELIGHT_TEMP_ONLY_EFFECT_LIST,
            "supported_features": SUPPORT_YEELIGHT,
            "brightness": nl_br,
            "color_mode": "brightness",
            "supported_color_modes": ["brightness"],
        },
    )

    # WhiteTempMood
    properties.pop("power")
    properties["main_power"] = "on"
    model_specs = _MODEL_SPECS["ceiling4"]
    await _async_test(
        BulbType.WhiteTempMood,
        "ceiling4",
        {
            "friendly_name":
            NAME,
            "effect_list":
            YEELIGHT_TEMP_ONLY_EFFECT_LIST,
            "flowing":
            False,
            "night_light":
            True,
            "supported_features":
            SUPPORT_YEELIGHT_WHITE_TEMP,
            "min_mireds":
            color_temperature_kelvin_to_mired(
                model_specs["color_temp"]["max"]),
            "max_mireds":
            color_temperature_kelvin_to_mired(
                model_specs["color_temp"]["min"]),
            "brightness":
            current_brightness,
            "color_temp":
            ct,
            "color_mode":
            "color_temp",
            "supported_color_modes": ["color_temp"],
        },
        {
            "effect_list": YEELIGHT_TEMP_ONLY_EFFECT_LIST,
            "supported_features": SUPPORT_YEELIGHT,
            "brightness": nl_br,
            "color_mode": "brightness",
            "supported_color_modes": ["brightness"],
        },
    )
    await _async_test(
        BulbType.WhiteTempMood,
        "ceiling4",
        {
            "effect_list": YEELIGHT_COLOR_EFFECT_LIST,
            "supported_features": SUPPORT_YEELIGHT_RGB,
            "min_mireds": color_temperature_kelvin_to_mired(6500),
            "max_mireds": color_temperature_kelvin_to_mired(1700),
            "brightness": bg_bright,
            "color_temp": bg_ct,
            "hs_color": bg_hs_color,
            "rgb_color": bg_rgb_color,
            "xy_color": bg_xy_color,
            "color_mode": "hs",
            "supported_color_modes": ["color_temp", "hs"],
        },
        name=f"{UNIQUE_NAME} ambilight",
        entity_id=f"{ENTITY_LIGHT}_ambilight",
    )
Example #24
0
    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn on the light."""
        # == Get key parameters ==
        if ATTR_EFFECT not in kwargs and ATTR_HS_COLOR in kwargs:
            effect = KEY_EFFECT_SOLID
        else:
            effect = kwargs.get(ATTR_EFFECT, self._effect)
        rgb_color: Sequence[int]
        if ATTR_HS_COLOR in kwargs:
            rgb_color = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])
        else:
            rgb_color = self._rgb_color

        # == Set brightness ==
        if ATTR_BRIGHTNESS in kwargs:
            brightness = kwargs[ATTR_BRIGHTNESS]
            for item in self._client.adjustment or []:
                if (const.KEY_ID in item
                        and not await self._client.async_send_set_adjustment(
                            **{
                                const.KEY_ADJUSTMENT: {
                                    const.KEY_BRIGHTNESS:
                                    int(round((float(brightness) * 100) /
                                              255)),
                                    const.KEY_ID:
                                    item[const.KEY_ID],
                                }
                            })):
                    return

        # == Set an external source
        if (effect and self._support_external_effects
                and (effect in const.KEY_COMPONENTID_EXTERNAL_SOURCES
                     or effect in const.KEY_COMPONENTID_FROM_NAME)):
            if effect in const.KEY_COMPONENTID_FROM_NAME:
                component = const.KEY_COMPONENTID_FROM_NAME[effect]
            else:
                _LOGGER.warning(
                    "Use of Hyperion effect '%s' is deprecated and will be removed "
                    "in a future release. Please use '%s' instead",
                    effect,
                    const.KEY_COMPONENTID_TO_NAME[effect],
                )
                component = effect

            # Clear any color/effect.
            if not await self._client.async_send_clear(
                    **{const.KEY_PRIORITY: self._get_option(CONF_PRIORITY)}):
                return

            # Turn off all external sources, except the intended.
            for key in const.KEY_COMPONENTID_EXTERNAL_SOURCES:
                if not await self._client.async_send_set_component(
                        **{
                            const.KEY_COMPONENTSTATE: {
                                const.KEY_COMPONENT: key,
                                const.KEY_STATE: component == key,
                            }
                        }):
                    return

        # == Set an effect
        elif effect and effect != KEY_EFFECT_SOLID:
            # This call should not be necessary, but without it there is no priorities-update issued:
            # https://github.com/hyperion-project/hyperion.ng/issues/992
            if not await self._client.async_send_clear(
                    **{const.KEY_PRIORITY: self._get_option(CONF_PRIORITY)}):
                return

            if not await self._client.async_send_set_effect(
                    **{
                        const.KEY_PRIORITY: self._get_option(CONF_PRIORITY),
                        const.KEY_EFFECT: {
                            const.KEY_NAME: effect
                        },
                        const.KEY_ORIGIN: DEFAULT_ORIGIN,
                    }):
                return
        # == Set a color
        else:
            if not await self._client.async_send_set_color(
                    **{
                        const.KEY_PRIORITY: self._get_option(CONF_PRIORITY),
                        const.KEY_COLOR: rgb_color,
                        const.KEY_ORIGIN: DEFAULT_ORIGIN,
                    }):
                return
Example #25
0
    def turn_on(self, **kwargs):
        """Turn the specified or all lights on."""
        if not self.is_on:
            self._bulb.turnOn()

        hs_color = kwargs.get(ATTR_HS_COLOR)

        if hs_color:
            rgb = color_util.color_hs_to_RGB(*hs_color)
        else:
            rgb = None

        brightness = kwargs.get(ATTR_BRIGHTNESS)
        effect = kwargs.get(ATTR_EFFECT)
        white = kwargs.get(ATTR_WHITE_VALUE)
        color_temp = kwargs.get(ATTR_COLOR_TEMP)

        # handle special modes
        if color_temp is not None:
            if brightness is None:
                brightness = self.brightness
            if color_temp > COLOR_TEMP_WARM_VS_COLD_WHITE_CUT_OFF:
                self._bulb.setRgbw(w=brightness)
            else:
                self._bulb.setRgbw(w2=brightness)
            return

        # Show warning if effect set with rgb, brightness, or white level
        if effect and (brightness or white or rgb):
            _LOGGER.warning("RGB, brightness and white level are ignored when"
                            " an effect is specified for a flux bulb")

        # Random color effect
        if effect == EFFECT_RANDOM:
            self._bulb.setRgb(random.randint(0, 255), random.randint(0, 255),
                              random.randint(0, 255))
            return

        if effect == EFFECT_CUSTOM:
            if self._custom_effect:
                self._bulb.setCustomPattern(
                    self._custom_effect[CONF_COLORS],
                    self._custom_effect[CONF_SPEED_PCT],
                    self._custom_effect[CONF_TRANSITION],
                )
            return

        # Effect selection
        if effect in EFFECT_MAP:
            self._bulb.setPresetPattern(EFFECT_MAP[effect], 50)
            return

        # Preserve current brightness on color/white level change
        if brightness is None:
            brightness = self.brightness

        # Preserve color on brightness/white level change
        if rgb is None:
            rgb = self._bulb.getRgb()

        if white is None and self._mode == MODE_RGBW:
            white = self.white_value

        # handle W only mode (use brightness instead of white value)
        if self._mode == MODE_WHITE:
            self._bulb.setRgbw(0, 0, 0, w=brightness)

        # handle RGBW mode
        elif self._mode == MODE_RGBW:
            self._bulb.setRgbw(*tuple(rgb), w=white, brightness=brightness)

        # handle RGB mode
        else:
            self._bulb.setRgb(*tuple(rgb), brightness=brightness)
Example #26
0
    def limitlessled_color(self):
        """Convert Open Peer Power HS list to RGB Color tuple."""

        return Color(*color_hs_to_RGB(*tuple(self._color)))
Example #27
0
    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn the device on."""
        # RGB/HS color
        hs_color = kwargs.get(ATTR_HS_COLOR)
        if hs_color is not None and self._supports_color:
            red, green, blue = color_util.color_hs_to_RGB(*hs_color)
            colors = {
                ColorComponent.RED: red,
                ColorComponent.GREEN: green,
                ColorComponent.BLUE: blue,
            }
            if self._supports_color_temp:
                # turn of white leds when setting rgb
                colors[ColorComponent.WARM_WHITE] = 0
                colors[ColorComponent.COLD_WHITE] = 0
            await self._async_set_colors(colors)

        # Color temperature
        color_temp = kwargs.get(ATTR_COLOR_TEMP)
        if color_temp is not None and self._supports_color_temp:
            # Limit color temp to min/max values
            cold = max(
                0,
                min(
                    255,
                    round((self._max_mireds - color_temp) /
                          (self._max_mireds - self._min_mireds) * 255),
                ),
            )
            warm = 255 - cold
            await self._async_set_colors({
                # turn off color leds when setting color temperature
                ColorComponent.RED:
                0,
                ColorComponent.GREEN:
                0,
                ColorComponent.BLUE:
                0,
                ColorComponent.WARM_WHITE:
                warm,
                ColorComponent.COLD_WHITE:
                cold,
            })

        # RGBW
        rgbw = kwargs.get(ATTR_RGBW_COLOR)
        if rgbw is not None and self._supports_rgbw:
            rgbw_channels = {
                ColorComponent.RED: rgbw[0],
                ColorComponent.GREEN: rgbw[1],
                ColorComponent.BLUE: rgbw[2],
            }
            if self._warm_white:
                rgbw_channels[ColorComponent.WARM_WHITE] = rgbw[3]

            if self._cold_white:
                rgbw_channels[ColorComponent.COLD_WHITE] = rgbw[3]
            await self._async_set_colors(rgbw_channels)

        # set brightness
        await self._async_set_brightness(kwargs.get(ATTR_BRIGHTNESS),
                                         kwargs.get(ATTR_TRANSITION))
Example #28
0
    async def async_turn_on(self, **kwargs):
        """Turn the light on."""
        if ATTR_COLOR_TEMP in kwargs:
            color_temp = kwargs[ATTR_COLOR_TEMP]
            percent_color_temp = self.translate(color_temp, self.max_mireds,
                                                self.min_mireds, CCT_MIN,
                                                CCT_MAX)

        if ATTR_BRIGHTNESS in kwargs:
            brightness = kwargs[ATTR_BRIGHTNESS]
            percent_brightness = ceil(100 * brightness / 255.0)

        if ATTR_HS_COLOR in kwargs:
            hs_color = kwargs[ATTR_HS_COLOR]
            rgb = color.color_hs_to_RGB(*hs_color)

        if ATTR_BRIGHTNESS in kwargs and ATTR_HS_COLOR in kwargs:
            _LOGGER.debug(
                "Setting brightness and color: %s %s%%, %s",
                brightness,
                percent_brightness,
                rgb,
            )

            result = await self._try_command(
                "Setting brightness and color failed: %s bri, %s color",
                self._device.set_brightness_and_rgb,
                percent_brightness,
                rgb,
            )

            if result:
                self._hs_color = hs_color
                self._brightness = brightness

        elif ATTR_BRIGHTNESS in kwargs and ATTR_COLOR_TEMP in kwargs:
            _LOGGER.debug(
                "Setting brightness and color temperature: "
                "%s %s%%, %s mireds, %s%% cct",
                brightness,
                percent_brightness,
                color_temp,
                percent_color_temp,
            )

            result = await self._try_command(
                "Setting brightness and color temperature failed: %s bri, %s cct",
                self._device.set_brightness_and_color_temperature,
                percent_brightness,
                percent_color_temp,
            )

            if result:
                self._color_temp = color_temp
                self._brightness = brightness

        elif ATTR_HS_COLOR in kwargs:
            _LOGGER.debug("Setting color: %s", rgb)

            result = await self._try_command("Setting color failed: %s",
                                             self._device.set_rgb, rgb)

            if result:
                self._hs_color = hs_color

        elif ATTR_COLOR_TEMP in kwargs:
            _LOGGER.debug(
                "Setting color temperature: %s mireds, %s%% cct",
                color_temp,
                percent_color_temp,
            )

            result = await self._try_command(
                "Setting color temperature failed: %s cct",
                self._device.set_color_temperature,
                percent_color_temp,
            )

            if result:
                self._color_temp = color_temp

        elif ATTR_BRIGHTNESS in kwargs:
            brightness = kwargs[ATTR_BRIGHTNESS]
            percent_brightness = ceil(100 * brightness / 255.0)

            _LOGGER.debug("Setting brightness: %s %s%%", brightness,
                          percent_brightness)

            result = await self._try_command(
                "Setting brightness failed: %s",
                self._device.set_brightness,
                percent_brightness,
            )

            if result:
                self._brightness = brightness

        else:
            await self._try_command("Turning the light on failed.",
                                    self._device.on)
Example #29
0
                rgbw_color = params.pop(ATTR_RGBW_COLOR)
                params[ATTR_RGB_COLOR] = rgbw_color[0:3]
                params[ATTR_WHITE_VALUE] = rgbw_color[3]

        # If a color is specified, convert to the color space supported by the light
        # Backwards compatibility: Fall back to hs color if light.supported_color_modes
        # is not implemented
        if not supported_color_modes:
            if (rgb_color := params.pop(ATTR_RGB_COLOR, None)) is not None:
                params[ATTR_HS_COLOR] = color_util.color_RGB_to_hs(*rgb_color)
            elif (xy_color := params.pop(ATTR_XY_COLOR, None)) is not None:
                params[ATTR_HS_COLOR] = color_util.color_xy_to_hs(*xy_color)
        elif ATTR_HS_COLOR in params and COLOR_MODE_HS not in supported_color_modes:
            hs_color = params.pop(ATTR_HS_COLOR)
            if COLOR_MODE_RGB in supported_color_modes:
                params[ATTR_RGB_COLOR] = color_util.color_hs_to_RGB(*hs_color)
            elif COLOR_MODE_RGBW in supported_color_modes:
                rgb_color = color_util.color_hs_to_RGB(*hs_color)
                params[ATTR_RGBW_COLOR] = color_util.color_rgb_to_rgbw(
                    *rgb_color)
            elif COLOR_MODE_RGBWW in supported_color_modes:
                rgb_color = color_util.color_hs_to_RGB(*hs_color)
                params[ATTR_RGBWW_COLOR] = color_util.color_rgb_to_rgbww(
                    *rgb_color, light.min_mireds, light.max_mireds)
            elif COLOR_MODE_XY in supported_color_modes:
                params[ATTR_XY_COLOR] = color_util.color_hs_to_xy(*hs_color)
        elif ATTR_RGB_COLOR in params and COLOR_MODE_RGB not in supported_color_modes:
            rgb_color = params.pop(ATTR_RGB_COLOR)
            if COLOR_MODE_RGBW in supported_color_modes:
                params[ATTR_RGBW_COLOR] = color_util.color_rgb_to_rgbw(
                    *rgb_color)