Exemple #1
0
    def _turn_on(self, **kwargs):
        """Turn the specified or all lights on."""
        self._bulb.turnOn()

        hs_color = kwargs.get(ATTR_HS_COLOR)
        brightness = kwargs.get(ATTR_BRIGHTNESS)
        effect = kwargs.get(ATTR_EFFECT)
        white = kwargs.get(ATTR_WHITE_VALUE)

        # Show warning if effect set with rgb, brightness, or white level
        if effect and (brightness or white or hs_color):
            _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

        if hs_color:
            self._color = (hs_color[0], hs_color[1], brightness / 255 * 100)
        elif brightness and (hs_color is None) and self._mode != MODE_WHITE:
            self._color = (self._color[0], self._color[1],
                           brightness / 255 * 100)

        # 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:
            if white is None:
                self._bulb.setRgbw(*color_util.color_hsv_to_RGB(*self._color))
            else:
                self._bulb.setRgbw(w=white)
        # handle RGB mode
        else:
            self._bulb.setRgb(*color_util.color_hsv_to_RGB(*self._color))
        return
    def _turn_on(self, **kwargs):
        """Turn the specified or all lights on."""
        self._bulb.turnOn()

        hs_color = kwargs.get(ATTR_HS_COLOR)
        brightness = kwargs.get(ATTR_BRIGHTNESS)
        effect = kwargs.get(ATTR_EFFECT)
        white = kwargs.get(ATTR_WHITE_VALUE)

        if all(item is None for item in [hs_color, brightness, effect, white]):
            return

        # handle W only mode (use brightness instead of white value)
        if self._mode == MODE_WHITE:
            if brightness is not None:
                self._bulb.setWarmWhite255(brightness)
            return
        if effect is not None:
            # Random color effect
            if effect == EFFECT_RANDOM:
                self._bulb.setRgb(random.randint(0, 255),
                                  random.randint(0, 255),
                                  random.randint(0, 255))
            elif 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])
                # Effect selection
            elif effect in EFFECT_MAP:
                self._bulb.setPresetPattern(EFFECT_MAP[effect], 50)
            return
        # Preserve current brightness on color/white level change
        if hs_color is not None:
            if brightness is None:
                brightness = self.brightness
            color = (hs_color[0], hs_color[1], brightness / 255 * 100)
        elif brightness is not None:
            color = (self._color[0], self._color[1],
                     brightness / 255 * 100)
        # handle RGBW mode
        if self._mode == MODE_RGBW:
            if white is None:
                self._bulb.setRgbw(*color_util.color_hsv_to_RGB(*color))
            else:
                self._bulb.setRgbw(w=white)
        # handle RGB mode
        else:
            self._bulb.setRgb(*color_util.color_hsv_to_RGB(*color))
    def test_color_hsv_to_RGB(self):
        """Test color_hsv_to_RGB."""
        self.assertEqual((0, 0, 0),
                         color_util.color_hsv_to_RGB(0, 0, 0))

        self.assertEqual((255, 255, 255),
                         color_util.color_hsv_to_RGB(0, 0, 100))

        self.assertEqual((0, 0, 255),
                         color_util.color_hsv_to_RGB(240, 100, 100))

        self.assertEqual((0, 255, 0),
                         color_util.color_hsv_to_RGB(120, 100, 100))

        self.assertEqual((255, 0, 0),
                         color_util.color_hsv_to_RGB(0, 100, 100))
    def turn_on(self, **kwargs):
        """Turn the specified light on."""
        self._state = True
        self._bulb.on()

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

        if white is not None:
            self._white = white
            self._hs_color = (0, 0)

        if hs_color is not None:
            self._white = 0
            self._hs_color = hs_color

        if brightness is not None:
            self._white = 0
            self._brightness = brightness

        if self._white != 0:
            self.set_white(self._white)
        else:
            rgb = color_util.color_hsv_to_RGB(
                self._hs_color[0], self._hs_color[1],
                self._brightness / 255 * 100)
            self.set_rgb(*rgb)
    def test_color_hsv_to_RGB(self):
        """Test color_hsv_to_RGB."""
        self.assertEqual((0, 0, 0),
                         color_util.color_hsv_to_RGB(0, 0, 0))

        self.assertEqual((255, 255, 255),
                         color_util.color_hsv_to_RGB(0, 0, 255))

        self.assertEqual((0, 0, 255),
                         color_util.color_hsv_to_RGB(43690, 255, 255))

        self.assertEqual((0, 255, 0),
                         color_util.color_hsv_to_RGB(21845, 255, 255))

        self.assertEqual((255, 0, 0),
                         color_util.color_hsv_to_RGB(0, 255, 255))
    def async_turn_on(self, **kwargs):
        """Turn the entity on.

        This method is a coroutine.
        """
        values = {'state': True}
        if self._optimistic:
            self._state = True

        if ATTR_BRIGHTNESS in kwargs:
            values['brightness'] = int(kwargs[ATTR_BRIGHTNESS])

            if self._optimistic:
                self._brightness = kwargs[ATTR_BRIGHTNESS]

        if ATTR_COLOR_TEMP in kwargs:
            values['color_temp'] = int(kwargs[ATTR_COLOR_TEMP])

            if self._optimistic:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]

        if ATTR_HS_COLOR in kwargs:
            hs_color = kwargs[ATTR_HS_COLOR]
            brightness = kwargs.get(
                ATTR_BRIGHTNESS, self._brightness if self._brightness else 255)
            rgb = color_util.color_hsv_to_RGB(
                hs_color[0], hs_color[1], brightness / 255 * 100)
            values['red'] = rgb[0]
            values['green'] = rgb[1]
            values['blue'] = rgb[2]

            if self._optimistic:
                self._hs = kwargs[ATTR_HS_COLOR]

        if ATTR_WHITE_VALUE in kwargs:
            values['white_value'] = int(kwargs[ATTR_WHITE_VALUE])

            if self._optimistic:
                self._white_value = kwargs[ATTR_WHITE_VALUE]

        if ATTR_EFFECT in kwargs:
            values['effect'] = kwargs.get(ATTR_EFFECT)

        if ATTR_FLASH in kwargs:
            values['flash'] = kwargs.get(ATTR_FLASH)

        if ATTR_TRANSITION in kwargs:
            values['transition'] = int(kwargs[ATTR_TRANSITION])

        mqtt.async_publish(
            self.hass, self._topics[CONF_COMMAND_TOPIC],
            self._templates[CONF_COMMAND_ON_TEMPLATE].async_render(**values),
            self._qos, self._retain
        )

        if self._optimistic:
            self.async_schedule_update_ha_state()
Exemple #7
0
    def rgb_color(self):
        """Return the RGB value."""
        hue, sat, bri, _ = self.device.color

        hue = hue / 65535 * 360
        sat = sat / 65535 * 100
        bri = bri / 65535 * 100

        return color_util.color_hsv_to_RGB(hue, sat, bri)
Exemple #8
0
    def turn_on(self, **kwargs):
        """Turn the specified light on."""
        brightness = kwargs.get(ATTR_BRIGHTNESS)
        colortemp = kwargs.get(ATTR_COLOR_TEMP)
        # pylint: disable=invalid-name
        hs = kwargs.get(ATTR_HS_COLOR)

        if brightness is not None:
            brightness = int(brightness * 100 / 255)
        else:
            if self._brightness is None:
                self._brightness = 100
            brightness = self._brightness

        if colortemp is not None:
            self._colormode = False
            temp_in_k = mired_to_kelvin(colortemp)
            relative_temp = temp_in_k - EUFY_MIN_KELVIN
            temp = int(relative_temp * 100 /
                       (EUFY_MAX_KELVIN - EUFY_MIN_KELVIN))
        else:
            temp = None

        if hs is not None:
            rgb = color_util.color_hsv_to_RGB(
                hs[0], hs[1], brightness / 255 * 100)
            self._colormode = True
        elif self._colormode:
            rgb = color_util.color_hsv_to_RGB(
                self._hs[0], self._hs[1], brightness / 255 * 100)
        else:
            rgb = None

        try:
            self._bulb.set_state(power=True, brightness=brightness,
                                 temperature=temp, colors=rgb)
        except BrokenPipeError:
            self._bulb.connect()
            self._bulb.set_state(power=True, brightness=brightness,
                                 temperature=temp, colors=rgb)
    def turn_on(self, **kwargs):
        """Turn the device on."""
        if ATTR_HS_COLOR in kwargs:
            self._hs_color = kwargs[ATTR_HS_COLOR]
        if ATTR_BRIGHTNESS in kwargs:
            self._brightness = kwargs[ATTR_BRIGHTNESS]
        else:
            self._brightness = 255

        rgb_color = color_util.color_hsv_to_RGB(
            self._hs_color[0], self._hs_color[1], self._brightness / 255 * 100)
        self._stick.set_color(
            red=rgb_color[0], green=rgb_color[1], blue=rgb_color[2])
    def turn_on(self, **kwargs):
        """Instruct the light to turn on and set correct brightness & color."""
        if ATTR_BRIGHTNESS in kwargs:
            self._brightness = kwargs[ATTR_BRIGHTNESS]

        if ATTR_HS_COLOR in kwargs:
            self._hs_color = kwargs[ATTR_HS_COLOR]

        rgb = color_util.color_hsv_to_RGB(
            self._hs_color[0], self._hs_color[1], self._brightness / 255 * 100)
        self._sensehat.clear(*rgb)

        self._is_on = True
        self.schedule_update_ha_state()
Exemple #11
0
    def set_color(self, hue, sat, bri, kel):
        """Set color state values."""
        self._hue = hue
        self._sat = sat
        self._bri = bri
        self._kel = kel

        red, green, blue = color_util.color_hsv_to_RGB(
            hue, convert_16_to_8(sat), convert_16_to_8(bri))

        _LOGGER.debug("set_color: %d %d %d %d [%d %d %d]",
                      hue, sat, bri, kel, red, green, blue)

        self._rgb = [red, green, blue]
Exemple #12
0
    def turn_on(self, **kwargs):
        # turn on and set to chosen color (or all white)
        self._is_sleep = False
        self._dev.sleep(self._is_sleep)
        self._state = not self._is_sleep
        print(kwargs)
        if ATTR_RGB_COLOR in kwargs:
            self._rgb = kwargs[ATTR_RGB_COLOR]
        if ATTR_HS_COLOR in kwargs:
            self._rgb = color_util.color_hsv_to_RGB(kwargs[ATTR_HS_COLOR][0], kwargs[ATTR_HS_COLOR][1], 100)
        self._dev.set_color((self._rgb[0] / 255.0, self._rgb[1] / 255.0, self._rgb[2] / 255.0))

        # inform HA about state update
        self.schedule_update_ha_state()
Exemple #13
0
    async def async_turn_on(self, **kwargs):
        """Turn the light on."""
        brightness = kwargs.get(ATTR_BRIGHTNESS, self.brightness)
        hs_color = kwargs.get(ATTR_HS_COLOR, self.hs_color)
        mireds = kwargs.get(ATTR_COLOR_TEMP, self.color_temp)

        update_brightness = ATTR_BRIGHTNESS in kwargs
        update_color = ATTR_HS_COLOR in kwargs
        update_color_temp = ATTR_COLOR_TEMP in kwargs

        # always only go one path for turning on (avoid conflicting changes
        # and weird effects)
        if self.device.supports_brightness and \
                (update_brightness and not update_color):
            # if we don't need to update the color, try updating brightness
            # directly if supported; don't do it if color also has to be
            # changed, as RGB color implicitly sets the brightness as well
            await self.device.set_brightness(brightness)
        elif self.device.supports_color and \
                (update_brightness or update_color):
            # change RGB color (includes brightness)
            # if brightness or hs_color was not yet set use the default value
            # to calculate RGB from as a fallback
            if brightness is None:
                brightness = DEFAULT_BRIGHTNESS
            if hs_color is None:
                hs_color = DEFAULT_COLOR
            await self.device.set_color(
                color_util.color_hsv_to_RGB(*hs_color, brightness * 100 / 255))
        elif self.device.supports_color_temperature and \
                update_color_temp:
            # change color temperature without ON telegram
            kelvin = int(color_util.color_temperature_mired_to_kelvin(mireds))
            if kelvin > self._max_kelvin:
                kelvin = self._max_kelvin
            elif kelvin < self._min_kelvin:
                kelvin = self._min_kelvin
            await self.device.set_color_temperature(kelvin)
        elif self.device.supports_tunable_white and \
                update_color_temp:
            # calculate relative_ct from Kelvin to fit typical KNX devices
            kelvin = int(color_util.color_temperature_mired_to_kelvin(mireds))
            relative_ct = int(255 * (kelvin - self._min_kelvin) /
                              (self._max_kelvin - self._min_kelvin))
            await self.device.set_tunable_white(relative_ct)
        else:
            # no color/brightness change requested, so just turn it on
            await self.device.set_on()
Exemple #14
0
    def turn_on(self, **kwargs):
        """Instruct the light to turn on."""
        self._piglow.clear()

        if ATTR_BRIGHTNESS in kwargs:
            self._brightness = kwargs[ATTR_BRIGHTNESS]

        if ATTR_HS_COLOR in kwargs:
            self._hs_color = kwargs[ATTR_HS_COLOR]

        rgb = color_util.color_hsv_to_RGB(
            self._hs_color[0], self._hs_color[1], self._brightness / 255 * 100)
        self._piglow.red(rgb[0])
        self._piglow.green(rgb[1])
        self._piglow.blue(rgb[2])
        self._piglow.show()
        self._is_on = True
        self.schedule_update_ha_state()
Exemple #15
0
 async def async_turn_on(self, **kwargs) -> None:
     """Turn the entity on."""
     data = {'key': self._static_info.key, 'state': True}
     if ATTR_HS_COLOR in kwargs:
         hue, sat = kwargs[ATTR_HS_COLOR]
         red, green, blue = color_util.color_hsv_to_RGB(hue, sat, 100)
         data['rgb'] = (red / 255, green / 255, blue / 255)
     if ATTR_FLASH in kwargs:
         data['flash'] = FLASH_LENGTHS[kwargs[ATTR_FLASH]]
     if ATTR_TRANSITION in kwargs:
         data['transition_length'] = kwargs[ATTR_TRANSITION]
     if ATTR_BRIGHTNESS in kwargs:
         data['brightness'] = kwargs[ATTR_BRIGHTNESS] / 255
     if ATTR_COLOR_TEMP in kwargs:
         data['color_temperature'] = kwargs[ATTR_COLOR_TEMP]
     if ATTR_EFFECT in kwargs:
         data['effect'] = kwargs[ATTR_EFFECT]
     if ATTR_WHITE_VALUE in kwargs:
         data['white'] = kwargs[ATTR_WHITE_VALUE] / 255
     await self._client.light_command(**data)
Exemple #16
0
    async def async_turn_on(self, **kwargs):
        """Instruct the light to turn on."""
        default_hs = (0, 0) if self._hs_color is None else self._hs_color
        hue_sat = kwargs.get(ATTR_HS_COLOR, default_hs)

        default_brightness = 0 if self._brightness is None else self._brightness
        brightness = kwargs.get(ATTR_BRIGHTNESS, default_brightness)

        default_white_value = 255 if self._white_value is None else self._white_value
        white_value = kwargs.get(ATTR_WHITE_VALUE, default_white_value)

        if brightness == 0 and white_value == 0 and not kwargs:
            # If the light would be off, and no additional parameters were
            # passed, just turn the light on full brightness.
            brightness = 255
            white_value = 255

        rgb = color_util.color_hsv_to_RGB(*hue_sat, brightness / 255 * 100)

        await self._light.set_color(*rgb, white_value)
Exemple #17
0
 async def async_turn_on(self, **kwargs) -> None:
     """Turn the entity on."""
     data = {"key": self._static_info.key, "state": True}
     if ATTR_HS_COLOR in kwargs:
         hue, sat = kwargs[ATTR_HS_COLOR]
         red, green, blue = color_util.color_hsv_to_RGB(hue, sat, 100)
         data["rgb"] = (red / 255, green / 255, blue / 255)
     if ATTR_FLASH in kwargs:
         data["flash_length"] = FLASH_LENGTHS[kwargs[ATTR_FLASH]]
     if ATTR_TRANSITION in kwargs:
         data["transition_length"] = kwargs[ATTR_TRANSITION]
     if ATTR_BRIGHTNESS in kwargs:
         data["brightness"] = kwargs[ATTR_BRIGHTNESS] / 255
     if ATTR_COLOR_TEMP in kwargs:
         data["color_temperature"] = kwargs[ATTR_COLOR_TEMP]
     if ATTR_EFFECT in kwargs:
         data["effect"] = kwargs[ATTR_EFFECT]
     if ATTR_WHITE_VALUE in kwargs:
         data["white"] = kwargs[ATTR_WHITE_VALUE] / 255
     await self._client.light_command(**data)
Exemple #18
0
    async def async_turn_on(self, **kwargs):
        """Turn the entity on."""
        supported_features = self._supported_features

        attributes = {}

        if ATTR_HS_COLOR in kwargs and supported_features & SUPPORT_COLOR:
            hs_color = kwargs[ATTR_HS_COLOR]
            attributes["color"] = {}

            rgb = color_util.color_hsv_to_RGB(hs_color[0], hs_color[1], 100)
            attributes["color"] = [rgb[0], rgb[1], rgb[2]]

        if ATTR_TRANSITION in kwargs:
            attributes["transition"] = kwargs[ATTR_TRANSITION]

        if ATTR_BRIGHTNESS in kwargs and supported_features & SUPPORT_BRIGHTNESS:
            brightness_normalized = kwargs[ATTR_BRIGHTNESS] / DEFAULT_BRIGHTNESS_MAX
            device_brightness = min(
                round(brightness_normalized * TASMOTA_BRIGHTNESS_MAX),
                TASMOTA_BRIGHTNESS_MAX,
            )
            # Make sure the brightness is not rounded down to 0
            device_brightness = max(device_brightness, 1)
            attributes["brightness"] = device_brightness

        if ATTR_COLOR_TEMP in kwargs and supported_features & SUPPORT_COLOR_TEMP:
            attributes["color_temp"] = int(kwargs[ATTR_COLOR_TEMP])

        if ATTR_EFFECT in kwargs:
            attributes["effect"] = kwargs[ATTR_EFFECT]

        if ATTR_WHITE_VALUE in kwargs:
            white_value_normalized = kwargs[ATTR_WHITE_VALUE] / DEFAULT_BRIGHTNESS_MAX
            device_white_value = min(
                round(white_value_normalized * TASMOTA_BRIGHTNESS_MAX),
                TASMOTA_BRIGHTNESS_MAX,
            )
            attributes["white_value"] = device_white_value

        self._tasmota_entity.set_state(True, attributes)
Exemple #19
0
    def turn_on(self, **kwargs):
        """Instruct the light to turn on.
        You can skip the brightness part if your light does not support
        brightness control.
        """
        if not self._state:
            self._interactor.set_on()
            self._state = True

        if ATTR_BRIGHTNESS in kwargs or ATTR_HS_COLOR in kwargs:
            # Controlling color brightness or color
            self._brightness = kwargs.get(ATTR_BRIGHTNESS, self._brightness)
            self._hs_color = kwargs.get(ATTR_HS_COLOR, self._hs_color)
            rgb = color_util.color_hsv_to_RGB(*self._hs_color,
                                              self._brightness * 100 / 255)
            # TODO: support changing pixel order
            self._interactor.set_color(*rgb)

        if ATTR_WHITE_VALUE in kwargs:
            self._white_value = kwargs.get(ATTR_WHITE_VALUE, self._white_value)
            self._interactor.set_white(self._white_value)
    def turn_on(self, **kwargs) -> None:
        if not self.is_on:
            self._device.turn_on(channel=self._channel_id)

        # Color is taken from either of these 2 values, but not both.
        if ATTR_HS_COLOR in kwargs:
            h, s = kwargs[ATTR_HS_COLOR]
            rgb = color_util.color_hsv_to_RGB(h, s, 100)
            _LOGGER.debug("color change: rgb=%r -- h=%r s=%r" % (rgb, h, s))
            self._device.set_light_color(self._channel_id, rgb=rgb)
        elif ATTR_COLOR_TEMP in kwargs:
            mired = kwargs[ATTR_COLOR_TEMP]
            norm_value = (mired - self.min_mireds) / (self.max_mireds - self.min_mireds)
            temperature = 100 - (norm_value * 100)
            _LOGGER.debug("temperature change: mired=%r meross=%r" % (mired, temperature))
            self._device.set_light_color(self._channel_id, temperature=temperature)

        # Brightness must always be set, so take previous luminance if not explicitly set now.
        if ATTR_BRIGHTNESS in kwargs:
            brightness = kwargs[ATTR_BRIGHTNESS] * 100 / 255
            _LOGGER.debug("    brightness change: %r" % brightness)
            self._device.set_light_color(self._channel_id, luminance=brightness)
Exemple #21
0
    async def async_turn_on(self, **kwargs):
        """Turn the light on."""

        # initialize with current values
        brightness = self.brightness
        hs_color = self.hs_color

        # overwrite values with new settings, if available
        if ATTR_BRIGHTNESS in kwargs:
            brightness = int(kwargs[ATTR_BRIGHTNESS])
        if ATTR_HS_COLOR in kwargs:
            hs_color = kwargs[ATTR_HS_COLOR]

        # fall back to default values, if required
        if brightness is None:
            brightness = DEFAULT_BRIGHTNESS
        if hs_color is None:
            hs_color = DEFAULT_COLOR

        update_brightness = ATTR_BRIGHTNESS in kwargs
        update_color = ATTR_HS_COLOR in kwargs

        # always only go one path for turning on (avoid conflicting changes
        # and weird effects)
        if self.device.supports_brightness and \
                (update_brightness and not update_color):
            # if we don't need to update the color, try updating brightness
            # directly if supported; don't do it if color also has to be changed,
            # as RGB color implicitly sets the brightness as well
            await self.device.set_brightness(brightness)
        elif self.device.supports_color and \
                (update_brightness or update_color):
            # change RGB color (includes brightness)
            await self.device.set_color(
                color_util.color_hsv_to_RGB(*hs_color, brightness * 100 / 255))
        else:
            # no color/brightness change requested, so just turn it on
            await self.device.set_on()
Exemple #22
0
    async def async_turn_on(self, **kwargs):
        """Turn the light on."""
        brightness = int(kwargs[ATTR_BRIGHTNESS]
                         ) if ATTR_BRIGHTNESS in kwargs else self.brightness
        hs_color = kwargs[
            ATTR_HS_COLOR] if ATTR_HS_COLOR in kwargs else self.hs_color

        update_color = ATTR_HS_COLOR in kwargs
        update_brightness = ATTR_BRIGHTNESS in kwargs

        # always only go one path for turning on (avoid conflicting changes and weird effects)
        if self.device.supports_brightness and (update_brightness
                                                and not update_color):
            # if we don't need to update the color, try updating brightness directly if supported
            await self.device.set_brightness(brightness)
        elif self.device.supports_color and (update_brightness
                                             or update_color):
            # change RGB color (includes brightness)
            await self.device.set_color(
                color_util.color_hsv_to_RGB(*hs_color, brightness * 100 / 255))
        else:
            # no color/brightness change, so just turn it on
            await self.device.set_on()
    async def async_turn_on(self, **kwargs):
        """Turn the light on."""
        hs_color = kwargs.get(ATTR_HS_COLOR, self._hs_color)
        brightness = kwargs.get(ATTR_BRIGHTNESS, self._brightness)
        effect = kwargs.get(ATTR_EFFECT)

        if effect is not None:
            colors = await self._api.set_pattern_by_id(self._channel, effect)

            rgb = color_int_to_rgb(colors[0])
            hsv = color_util.color_RGB_to_hsv(*rgb)
            hs_color = hsv[:2]
            brightness = hsv[2] / 100 * 255

        else:
            rgb = color_util.color_hsv_to_RGB(*hs_color, brightness/255*100)
            colors = [color_rgb_to_int(*rgb)]

            await self._api.set_pattern(self._channel, colors)

        self._hs_color = hs_color
        self._brightness = brightness
        self._effect = effect
Exemple #24
0
    async def async_turn_on(self, **kwargs):
        """Turn the light on."""
        hs_color = kwargs.get(ATTR_HS_COLOR, self._hs_color)
        brightness = kwargs.get(ATTR_BRIGHTNESS, self._brightness)
        effect = kwargs.get(ATTR_EFFECT)

        if effect is not None:
            colors = await self._api.set_pattern_by_id(self._channel, effect)

            rgb = color_int_to_rgb(colors[0])
            hsv = color_util.color_RGB_to_hsv(*rgb)
            hs_color = hsv[:2]
            brightness = hsv[2] / 100 * 255

        else:
            rgb = color_util.color_hsv_to_RGB(*hs_color, brightness/255*100)
            colors = [color_rgb_to_int(*rgb)]

            await self._api.set_pattern(self._channel, colors)

        self._hs_color = hs_color
        self._brightness = brightness
        self._effect = effect
Exemple #25
0
    def turn_on(self, **kwargs):
        _LOGGER.debug("%s.turn_on()", self)
        self._clear_enqueue()  # Remove any messages

        if ATTR_EFFECT in kwargs:
            self._effect = kwargs[ATTR_EFFECT]
            self._set_effect(Effect[self._effect].value, 10)

        elif ATTR_HS_COLOR in kwargs:
            hue, saturation = kwargs[ATTR_HS_COLOR]
            self._raw_rgb = color_hsv_to_RGB(hue, saturation, 100)
            _LOGGER.debug("%s set rgb to %s", self, self._raw_rgb)
            to_rgb = self._filter_colour_with_brightness()
            self._fade_colour(to_rgb)

        elif ATTR_BRIGHTNESS in kwargs:
            self._brightness = kwargs[ATTR_BRIGHTNESS]
            to_rgb = self._filter_colour_with_brightness()
            self._fade_colour(to_rgb)

        else:
            self._fade_on()

        self.process_message_queue()
    async def async_turn_on(self, **kwargs):
        """Turn the device on.

        This method is a coroutine.
        """
        should_update = False
        on_command_type = self._config[CONF_ON_COMMAND_TYPE]

        if on_command_type == 'first':
            mqtt.async_publish(
                self.hass, self._topic[CONF_COMMAND_TOPIC],
                self._payload['on'], self._config[CONF_QOS],
                self._config[CONF_RETAIN])
            should_update = True

        # If brightness is being used instead of an on command, make sure
        # there is a brightness input.  Either set the brightness to our
        # saved value or the maximum value if this is the first call
        elif on_command_type == 'brightness':
            if ATTR_BRIGHTNESS not in kwargs:
                kwargs[ATTR_BRIGHTNESS] = self._brightness if \
                                          self._brightness else 255

        if ATTR_HS_COLOR in kwargs and \
           self._topic[CONF_RGB_COMMAND_TOPIC] is not None:

            hs_color = kwargs[ATTR_HS_COLOR]

            # If there's a brightness topic set, we don't want to scale the RGB
            # values given using the brightness.
            if self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
                brightness = 255
            else:
                brightness = kwargs.get(
                    ATTR_BRIGHTNESS, self._brightness if self._brightness else
                    255)
            rgb = color_util.color_hsv_to_RGB(
                hs_color[0], hs_color[1], brightness / 255 * 100)
            tpl = self._templates[CONF_RGB_COMMAND_TEMPLATE]
            if tpl:
                rgb_color_str = tpl.async_render({
                    'red': rgb[0],
                    'green': rgb[1],
                    'blue': rgb[2],
                })
            else:
                rgb_color_str = '{},{},{}'.format(*rgb)

            mqtt.async_publish(
                self.hass, self._topic[CONF_RGB_COMMAND_TOPIC],
                rgb_color_str, self._config[CONF_QOS],
                self._config[CONF_RETAIN])

            if self._optimistic_rgb:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_HS_COLOR in kwargs and \
           self._topic[CONF_HS_COMMAND_TOPIC] is not None:

            hs_color = kwargs[ATTR_HS_COLOR]
            mqtt.async_publish(
                self.hass, self._topic[CONF_HS_COMMAND_TOPIC],
                '{},{}'.format(*hs_color), self._config[CONF_QOS],
                self._config[CONF_RETAIN])

            if self._optimistic_hs:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_HS_COLOR in kwargs and \
           self._topic[CONF_XY_COMMAND_TOPIC] is not None:

            xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
            mqtt.async_publish(
                self.hass, self._topic[CONF_XY_COMMAND_TOPIC],
                '{},{}'.format(*xy_color), self._config[CONF_QOS],
                self._config[CONF_RETAIN])

            if self._optimistic_xy:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_BRIGHTNESS in kwargs and \
           self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
            percent_bright = float(kwargs[ATTR_BRIGHTNESS]) / 255
            brightness_scale = self._config[CONF_BRIGHTNESS_SCALE]
            device_brightness = \
                min(round(percent_bright * brightness_scale), brightness_scale)
            mqtt.async_publish(
                self.hass, self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC],
                device_brightness, self._config[CONF_QOS],
                self._config[CONF_RETAIN])

            if self._optimistic_brightness:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True
        elif ATTR_BRIGHTNESS in kwargs and ATTR_HS_COLOR not in kwargs and\
                self._topic[CONF_RGB_COMMAND_TOPIC] is not None:
            rgb = color_util.color_hsv_to_RGB(
                self._hs[0], self._hs[1], kwargs[ATTR_BRIGHTNESS] / 255 * 100)
            tpl = self._templates[CONF_RGB_COMMAND_TEMPLATE]
            if tpl:
                rgb_color_str = tpl.async_render({
                    'red': rgb[0],
                    'green': rgb[1],
                    'blue': rgb[2],
                })
            else:
                rgb_color_str = '{},{},{}'.format(*rgb)

            mqtt.async_publish(
                self.hass, self._topic[CONF_RGB_COMMAND_TOPIC],
                rgb_color_str, self._config[CONF_QOS],
                self._config[CONF_RETAIN])

            if self._optimistic_brightness:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True

        if ATTR_COLOR_TEMP in kwargs and \
           self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC] is not None:
            color_temp = int(kwargs[ATTR_COLOR_TEMP])
            tpl = self._templates[CONF_COLOR_TEMP_COMMAND_TEMPLATE]

            if tpl:
                color_temp = tpl.async_render({
                    'value': color_temp,
                })

            mqtt.async_publish(
                self.hass, self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC],
                color_temp, self._config[CONF_QOS],
                self._config[CONF_RETAIN])

            if self._optimistic_color_temp:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]
                should_update = True

        if ATTR_EFFECT in kwargs and \
           self._topic[CONF_EFFECT_COMMAND_TOPIC] is not None:
            effect = kwargs[ATTR_EFFECT]
            if effect in self._config.get(CONF_EFFECT_LIST):
                mqtt.async_publish(
                    self.hass, self._topic[CONF_EFFECT_COMMAND_TOPIC],
                    effect, self._config[CONF_QOS],
                    self._config[CONF_RETAIN])

                if self._optimistic_effect:
                    self._effect = kwargs[ATTR_EFFECT]
                    should_update = True

        if ATTR_WHITE_VALUE in kwargs and \
           self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC] is not None:
            percent_white = float(kwargs[ATTR_WHITE_VALUE]) / 255
            white_scale = self._config[CONF_WHITE_VALUE_SCALE]
            device_white_value = \
                min(round(percent_white * white_scale), white_scale)
            mqtt.async_publish(
                self.hass, self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC],
                device_white_value, self._config[CONF_QOS],
                self._config[CONF_RETAIN])

            if self._optimistic_white_value:
                self._white_value = kwargs[ATTR_WHITE_VALUE]
                should_update = True

        if on_command_type == 'last':
            mqtt.async_publish(self.hass, self._topic[CONF_COMMAND_TOPIC],
                               self._payload['on'], self._config[CONF_QOS],
                               self._config[CONF_RETAIN])
            should_update = True

        if self._optimistic:
            # Optimistically assume that the light has changed state.
            self._state = True
            should_update = True

        if should_update:
            self.async_write_ha_state()
Exemple #27
0
    async def async_turn_on(self, **kwargs):
        """Turn the entity on."""
        if ATTR_BRIGHTNESS not in kwargs:
            kwargs[
                ATTR_BRIGHTNESS] = self._brightness if self._brightness else 255

        if (ATTR_HS_COLOR in kwargs
                and self._config.get(CONF_RGB_COMMAND_TOPIC) is not None):
            hs_color = kwargs[ATTR_HS_COLOR]

            if self._config.get(CONF_BRIGHTNESS_COMMAND_TOPIC) is not None:
                brightness = 255
            else:
                brightness = kwargs.get(
                    ATTR_BRIGHTNESS,
                    self._brightness if self._brightness else 255)
            rgb = color_util.color_hsv_to_RGB(hs_color[0], hs_color[1],
                                              brightness / 255 * 100)
            rgb_color_str = ",".join(map(str, rgb))
            async_publish(self.hass, self._config[CONF_RGB_COMMAND_TOPIC],
                          rgb_color_str, 0, False)

        if (ATTR_BRIGHTNESS in kwargs and
                self._config.get(CONF_BRIGHTNESS_COMMAND_TOPIC) is not None):
            brightness_normalized = kwargs[ATTR_BRIGHTNESS] / 255
            brightness_scale = 255
            device_brightness = min(
                round(brightness_normalized * brightness_scale),
                brightness_scale)
            # Make sure the brightness is not rounded down to 0
            device_brightness = max(device_brightness, 1)
            async_publish(
                self.hass,
                self._config[CONF_BRIGHTNESS_COMMAND_TOPIC],
                device_brightness,
                0,
                False,
            )
        elif (ATTR_BRIGHTNESS in kwargs and ATTR_HS_COLOR not in kwargs
              and self._config.get(CONF_RGB_COMMAND_TOPIC) is not None):
            rgb = color_util.color_hsv_to_RGB(
                self._hs[0], self._hs[1], kwargs[ATTR_BRIGHTNESS] / 255 * 100)
            rgb_color_str = ",".join(map(str, rgb))

            async_publish(self.hass, self._config[CONF_RGB_COMMAND_TOPIC],
                          rgb_color_str, 0, False)

        if (ATTR_WHITE_VALUE in kwargs
                and self._config[CONF_WHITE_VALUE_COMMAND_TOPIC] is not None):
            percent_white = float(kwargs[ATTR_WHITE_VALUE]) / 255
            white_scale = 255
            device_white_value = min(round(percent_white * white_scale),
                                     white_scale)
            async_publish(
                self.hass,
                self._config[CONF_WHITE_VALUE_COMMAND_TOPIC],
                device_white_value,
                0,
                False,
            )

        if self._config.get(CONF_COMMAND_TOPIC) is not None:
            async_publish(
                self.hass,
                self._config[CONF_COMMAND_TOPIC],
                kwargs[ATTR_BRIGHTNESS],
                0,
                False,
            )
Exemple #28
0
    async def async_turn_on(self, **kwargs):
        """Turn the device on.

        This method is a coroutine.
        """
        should_update = False

        if self._on_command_type == 'first':
            mqtt.async_publish(
                self.hass, self._topic[CONF_COMMAND_TOPIC],
                self._payload['on'], self._qos, self._retain)
            should_update = True

        # If brightness is being used instead of an on command, make sure
        # there is a brightness input.  Either set the brightness to our
        # saved value or the maximum value if this is the first call
        elif self._on_command_type == 'brightness':
            if ATTR_BRIGHTNESS not in kwargs:
                kwargs[ATTR_BRIGHTNESS] = self._brightness if \
                                          self._brightness else 255

        if ATTR_HS_COLOR in kwargs and \
           self._topic[CONF_RGB_COMMAND_TOPIC] is not None:

            hs_color = kwargs[ATTR_HS_COLOR]
            brightness = kwargs.get(
                ATTR_BRIGHTNESS, self._brightness if self._brightness else 255)
            rgb = color_util.color_hsv_to_RGB(
                hs_color[0], hs_color[1], brightness / 255 * 100)
            tpl = self._templates[CONF_RGB_COMMAND_TEMPLATE]
            if tpl:
                rgb_color_str = tpl.async_render({
                    'red': rgb[0],
                    'green': rgb[1],
                    'blue': rgb[2],
                })
            else:
                rgb_color_str = '{},{},{}'.format(*rgb)

            mqtt.async_publish(
                self.hass, self._topic[CONF_RGB_COMMAND_TOPIC],
                rgb_color_str, self._qos, self._retain)

            if self._optimistic_rgb:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_HS_COLOR in kwargs and \
           self._topic[CONF_XY_COMMAND_TOPIC] is not None:

            xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
            mqtt.async_publish(
                self.hass, self._topic[CONF_XY_COMMAND_TOPIC],
                '{},{}'.format(*xy_color), self._qos,
                self._retain)

            if self._optimistic_xy:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_BRIGHTNESS in kwargs and \
           self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
            percent_bright = float(kwargs[ATTR_BRIGHTNESS]) / 255
            device_brightness = int(percent_bright * self._brightness_scale)
            mqtt.async_publish(
                self.hass, self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC],
                device_brightness, self._qos, self._retain)

            if self._optimistic_brightness:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True

        if ATTR_COLOR_TEMP in kwargs and \
           self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC] is not None:
            color_temp = int(kwargs[ATTR_COLOR_TEMP])
            mqtt.async_publish(
                self.hass, self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC],
                color_temp, self._qos, self._retain)

            if self._optimistic_color_temp:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]
                should_update = True

        if ATTR_EFFECT in kwargs and \
           self._topic[CONF_EFFECT_COMMAND_TOPIC] is not None:
            effect = kwargs[ATTR_EFFECT]
            if effect in self._effect_list:
                mqtt.async_publish(
                    self.hass, self._topic[CONF_EFFECT_COMMAND_TOPIC],
                    effect, self._qos, self._retain)

                if self._optimistic_effect:
                    self._effect = kwargs[ATTR_EFFECT]
                    should_update = True

        if ATTR_WHITE_VALUE in kwargs and \
           self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC] is not None:
            percent_white = float(kwargs[ATTR_WHITE_VALUE]) / 255
            device_white_value = int(percent_white * self._white_value_scale)
            mqtt.async_publish(
                self.hass, self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC],
                device_white_value, self._qos, self._retain)

            if self._optimistic_white_value:
                self._white_value = kwargs[ATTR_WHITE_VALUE]
                should_update = True

        if self._on_command_type == 'last':
            mqtt.async_publish(self.hass, self._topic[CONF_COMMAND_TOPIC],
                               self._payload['on'], self._qos, self._retain)
            should_update = True

        if self._optimistic:
            # Optimistically assume that switch has changed state.
            self._state = True
            should_update = True

        if should_update:
            self.async_schedule_update_ha_state()
def _min_scaled_rgb_brightness(
        rgb: tuple[int, int, int]) -> tuple[int, int, int]:
    """Scale an RGB tuple to minimum brightness."""
    return color_hsv_to_RGB(*color_RGB_to_hsv(*rgb)[:2], 1)
    async def async_turn_on(self, **kwargs):
        """Turn the entity on.

        This method is a coroutine.
        """
        values = {'state': True}
        if self._optimistic:
            self._state = True

        if ATTR_BRIGHTNESS in kwargs:
            values['brightness'] = int(kwargs[ATTR_BRIGHTNESS])

            if self._optimistic:
                self._brightness = kwargs[ATTR_BRIGHTNESS]

        if ATTR_COLOR_TEMP in kwargs:
            values['color_temp'] = int(kwargs[ATTR_COLOR_TEMP])

            if self._optimistic:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]

        if ATTR_HS_COLOR in kwargs:
            hs_color = kwargs[ATTR_HS_COLOR]

            # If there's a brightness topic set, we don't want to scale the RGB
            # values given using the brightness.
            if self._templates[CONF_BRIGHTNESS_TEMPLATE] is not None:
                brightness = 255
            else:
                brightness = kwargs.get(
                    ATTR_BRIGHTNESS, self._brightness if self._brightness else
                    255)
            rgb = color_util.color_hsv_to_RGB(
                hs_color[0], hs_color[1], brightness / 255 * 100)
            values['red'] = rgb[0]
            values['green'] = rgb[1]
            values['blue'] = rgb[2]

            if self._optimistic:
                self._hs = kwargs[ATTR_HS_COLOR]

        if ATTR_WHITE_VALUE in kwargs:
            values['white_value'] = int(kwargs[ATTR_WHITE_VALUE])

            if self._optimistic:
                self._white_value = kwargs[ATTR_WHITE_VALUE]

        if ATTR_EFFECT in kwargs:
            values['effect'] = kwargs.get(ATTR_EFFECT)

        if ATTR_FLASH in kwargs:
            values['flash'] = kwargs.get(ATTR_FLASH)

        if ATTR_TRANSITION in kwargs:
            values['transition'] = int(kwargs[ATTR_TRANSITION])

        mqtt.async_publish(
            self.hass, self._topics[CONF_COMMAND_TOPIC],
            self._templates[CONF_COMMAND_ON_TEMPLATE].async_render(**values),
            self._config[CONF_QOS], self._config[CONF_RETAIN]
        )

        if self._optimistic:
            self.async_write_ha_state()
    async def async_turn_on(self, **kwargs):
        """Turn the device on.

        This method is a coroutine.
        """
        should_update = False

        message = {"state": "ON"}

        if ATTR_HS_COLOR in kwargs and (self._config[CONF_HS]
                                        or self._config[CONF_RGB]
                                        or self._config[CONF_XY]):
            hs_color = kwargs[ATTR_HS_COLOR]
            message["color"] = {}
            if self._config[CONF_RGB]:
                # If there's a brightness topic set, we don't want to scale the
                # RGB values given using the brightness.
                if self._config[CONF_BRIGHTNESS]:
                    brightness = 255
                else:
                    brightness = kwargs.get(ATTR_BRIGHTNESS, 255)
                rgb = color_util.color_hsv_to_RGB(hs_color[0], hs_color[1],
                                                  brightness / 255 * 100)
                message["color"]["r"] = rgb[0]
                message["color"]["g"] = rgb[1]
                message["color"]["b"] = rgb[2]
            if self._config[CONF_XY]:
                xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
                message["color"]["x"] = xy_color[0]
                message["color"]["y"] = xy_color[1]
            if self._config[CONF_HS]:
                message["color"]["h"] = hs_color[0]
                message["color"]["s"] = hs_color[1]

            if self._optimistic:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_FLASH in kwargs:
            flash = kwargs.get(ATTR_FLASH)

            if flash == FLASH_LONG:
                message["flash"] = self._flash_times[CONF_FLASH_TIME_LONG]
            elif flash == FLASH_SHORT:
                message["flash"] = self._flash_times[CONF_FLASH_TIME_SHORT]

        if ATTR_TRANSITION in kwargs:
            message["transition"] = kwargs[ATTR_TRANSITION]

        if ATTR_BRIGHTNESS in kwargs and self._config[CONF_BRIGHTNESS]:
            brightness_normalized = kwargs[
                ATTR_BRIGHTNESS] / DEFAULT_BRIGHTNESS_SCALE
            brightness_scale = self._config[CONF_BRIGHTNESS_SCALE]
            device_brightness = min(
                round(brightness_normalized * brightness_scale),
                brightness_scale)
            # Make sure the brightness is not rounded down to 0
            device_brightness = max(device_brightness, 1)
            message["brightness"] = device_brightness

            if self._optimistic:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True

        if ATTR_COLOR_TEMP in kwargs:
            message["color_temp"] = int(kwargs[ATTR_COLOR_TEMP])

            if self._optimistic:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]
                should_update = True

        if ATTR_EFFECT in kwargs:
            message["effect"] = kwargs[ATTR_EFFECT]

            if self._optimistic:
                self._effect = kwargs[ATTR_EFFECT]
                should_update = True

        if ATTR_WHITE_VALUE in kwargs:
            message["white_value"] = int(kwargs[ATTR_WHITE_VALUE])

            if self._optimistic:
                self._white_value = kwargs[ATTR_WHITE_VALUE]
                should_update = True

        mqtt.async_publish(
            self.hass,
            self._topic[CONF_COMMAND_TOPIC],
            json.dumps(message),
            self._config[CONF_QOS],
            self._config[CONF_RETAIN],
        )

        if self._optimistic:
            # Optimistically assume that the light has changed state.
            self._state = True
            should_update = True

        if should_update:
            self.async_write_ha_state()
Exemple #32
0
    async def async_turn_on(self, **kwargs):  # noqa: C901
        """Turn the device on.

        This method is a coroutine.
        """
        should_update = False
        on_command_type = self._config[CONF_ON_COMMAND_TYPE]

        def publish(topic, payload):
            """Publish an MQTT message."""
            mqtt.async_publish(
                self.hass,
                self._topic[topic],
                payload,
                self._config[CONF_QOS],
                self._config[CONF_RETAIN],
            )

        def scale_rgbx(color, brightness=None):
            """Scale RGBx for brightness."""
            if brightness is None:
                # If there's a brightness topic set, we don't want to scale the RGBx
                # values given using the brightness.
                if self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
                    brightness = 255
                else:
                    brightness = kwargs.get(
                        ATTR_BRIGHTNESS, self._brightness if self._brightness else 255
                    )
            return tuple(int(channel * brightness / 255) for channel in color)

        def render_rgbx(color, template, color_mode):
            """Render RGBx payload."""
            tpl = self._command_templates[template]
            if tpl:
                keys = ["red", "green", "blue"]
                if color_mode == COLOR_MODE_RGBW:
                    keys.append("white")
                elif color_mode == COLOR_MODE_RGBWW:
                    keys.extend(["cold_white", "warm_white"])
                rgb_color_str = tpl(zip(keys, color))
            else:
                rgb_color_str = ",".join(str(channel) for channel in color)
            return rgb_color_str

        def set_optimistic(attribute, value, color_mode=None, condition_attribute=None):
            """Optimistically update a state attribute."""
            if condition_attribute is None:
                condition_attribute = attribute
            if not self._is_optimistic(condition_attribute):
                return False
            if color_mode and self._optimistic_color_mode:
                self._color_mode = color_mode
            setattr(self, f"_{attribute}", value)
            return True

        if on_command_type == "first":
            publish(CONF_COMMAND_TOPIC, self._payload["on"])
            should_update = True

        # If brightness is being used instead of an on command, make sure
        # there is a brightness input.  Either set the brightness to our
        # saved value or the maximum value if this is the first call
        elif on_command_type == "brightness" and ATTR_BRIGHTNESS not in kwargs:
            kwargs[ATTR_BRIGHTNESS] = self._brightness if self._brightness else 255

        hs_color = kwargs.get(ATTR_HS_COLOR)
        if (
            hs_color
            and self._topic[CONF_RGB_COMMAND_TOPIC] is not None
            and self._legacy_mode
        ):
            # Legacy mode: Convert HS to RGB
            rgb = scale_rgbx(color_util.color_hsv_to_RGB(*hs_color, 100))
            rgb_s = render_rgbx(rgb, CONF_RGB_COMMAND_TEMPLATE, COLOR_MODE_RGB)
            publish(CONF_RGB_COMMAND_TOPIC, rgb_s)
            should_update |= set_optimistic(
                ATTR_HS_COLOR, hs_color, condition_attribute=ATTR_RGB_COLOR
            )

        if hs_color and self._topic[CONF_HS_COMMAND_TOPIC] is not None:
            publish(CONF_HS_COMMAND_TOPIC, f"{hs_color[0]},{hs_color[1]}")
            should_update |= set_optimistic(ATTR_HS_COLOR, hs_color, COLOR_MODE_HS)

        if (
            hs_color
            and self._topic[CONF_XY_COMMAND_TOPIC] is not None
            and self._legacy_mode
        ):
            # Legacy mode: Convert HS to XY
            xy_color = color_util.color_hs_to_xy(*hs_color)
            publish(CONF_XY_COMMAND_TOPIC, f"{xy_color[0]},{xy_color[1]}")
            should_update |= set_optimistic(
                ATTR_HS_COLOR, hs_color, condition_attribute=ATTR_XY_COLOR
            )

        if (
            (rgb := kwargs.get(ATTR_RGB_COLOR))
            and self._topic[CONF_RGB_COMMAND_TOPIC] is not None
            and not self._legacy_mode
        ):
            scaled = scale_rgbx(rgb)
            rgb_s = render_rgbx(scaled, CONF_RGB_COMMAND_TEMPLATE, COLOR_MODE_RGB)
            publish(CONF_RGB_COMMAND_TOPIC, rgb_s)
            should_update |= set_optimistic(ATTR_RGB_COLOR, rgb, COLOR_MODE_RGB)
Exemple #33
0
    async def async_turn_on(self, **kwargs):
        """Switch the light on, change brightness, change color."""
        if self._ambient:
            _LOGGER.debug("Switching ambient light on for: %s", self.name)
            try:
                await self.hass.async_add_executor_job(
                    self.device.appliance.set_setting, self._key, True)
            except HomeConnectError as err:
                _LOGGER.error(
                    "Error while trying to turn on ambient light: %s", err)
                return
            if ATTR_BRIGHTNESS in kwargs or ATTR_HS_COLOR in kwargs:
                try:
                    await self.hass.async_add_executor_job(
                        self.device.appliance.set_setting,
                        self._color_key,
                        BSH_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR,
                    )
                except HomeConnectError as err:
                    _LOGGER.error(
                        "Error while trying selecting customcolor: %s", err)
                if self._brightness is not None:
                    brightness = 10 + ceil(self._brightness / 255 * 90)
                    if ATTR_BRIGHTNESS in kwargs:
                        brightness = 10 + ceil(
                            kwargs[ATTR_BRIGHTNESS] / 255 * 90)

                    hs_color = kwargs.get(ATTR_HS_COLOR, self._hs_color)

                    if hs_color is not None:
                        rgb = color_util.color_hsv_to_RGB(
                            *hs_color, brightness)
                        hex_val = color_util.color_rgb_to_hex(
                            rgb[0], rgb[1], rgb[2])
                        try:
                            await self.hass.async_add_executor_job(
                                self.device.appliance.set_setting,
                                self._custom_color_key,
                                f"#{hex_val}",
                            )
                        except HomeConnectError as err:
                            _LOGGER.error(
                                "Error while trying setting the color: %s",
                                err)

        elif ATTR_BRIGHTNESS in kwargs:
            _LOGGER.debug("Changing brightness for: %s", self.name)
            brightness = 10 + ceil(kwargs[ATTR_BRIGHTNESS] / 255 * 90)
            try:
                await self.hass.async_add_executor_job(
                    self.device.appliance.set_setting, self._brightness_key,
                    brightness)
            except HomeConnectError as err:
                _LOGGER.error("Error while trying set the brightness: %s", err)
        else:
            _LOGGER.debug("Switching light on for: %s", self.name)
            try:
                await self.hass.async_add_executor_job(
                    self.device.appliance.set_setting, self._key, True)
            except HomeConnectError as err:
                _LOGGER.error("Error while trying to turn on light: %s", err)

        self.async_entity_update()
Exemple #34
0
    async def async_turn_on(self, **kwargs):
        """Turn the entity on.

        This method is a coroutine.
        """
        values = {"state": True}
        if self._optimistic:
            self._state = True

        if ATTR_BRIGHTNESS in kwargs:
            values["brightness"] = int(kwargs[ATTR_BRIGHTNESS])

            if self._optimistic:
                self._brightness = kwargs[ATTR_BRIGHTNESS]

        if ATTR_COLOR_TEMP in kwargs:
            values["color_temp"] = int(kwargs[ATTR_COLOR_TEMP])

            if self._optimistic:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]

        if ATTR_HS_COLOR in kwargs:
            hs_color = kwargs[ATTR_HS_COLOR]

            # If there's a brightness topic set, we don't want to scale the RGB
            # values given using the brightness.
            if self._templates[CONF_BRIGHTNESS_TEMPLATE] is not None:
                brightness = 255
            else:
                brightness = kwargs.get(
                    ATTR_BRIGHTNESS,
                    self._brightness if self._brightness else 255)
            rgb = color_util.color_hsv_to_RGB(hs_color[0], hs_color[1],
                                              brightness / 255 * 100)
            values["red"] = rgb[0]
            values["green"] = rgb[1]
            values["blue"] = rgb[2]

            if self._optimistic:
                self._hs = kwargs[ATTR_HS_COLOR]

        if ATTR_WHITE_VALUE in kwargs:
            values["white_value"] = int(kwargs[ATTR_WHITE_VALUE])

            if self._optimistic:
                self._white_value = kwargs[ATTR_WHITE_VALUE]

        if ATTR_EFFECT in kwargs:
            values["effect"] = kwargs.get(ATTR_EFFECT)

            if self._optimistic:
                self._effect = kwargs[ATTR_EFFECT]

        if ATTR_FLASH in kwargs:
            values["flash"] = kwargs.get(ATTR_FLASH)

        if ATTR_TRANSITION in kwargs:
            values["transition"] = int(kwargs[ATTR_TRANSITION])

        mqtt.async_publish(
            self.hass,
            self._topics[CONF_COMMAND_TOPIC],
            self._templates[CONF_COMMAND_ON_TEMPLATE].async_render(**values),
            self._config[CONF_QOS],
            self._config[CONF_RETAIN],
        )

        if self._optimistic:
            self.async_write_ha_state()
    async def async_turn_on(self, **kwargs):  # noqa: C901
        """Turn the device on.

        This method is a coroutine.
        """
        should_update = False

        message = {"state": "ON"}

        if ATTR_HS_COLOR in kwargs and (
            self._config[CONF_HS] or self._config[CONF_RGB] or self._config[CONF_XY]
        ):
            hs_color = kwargs[ATTR_HS_COLOR]
            message["color"] = {}
            if self._config[CONF_RGB]:
                # If there's a brightness topic set, we don't want to scale the
                # RGB values given using the brightness.
                if self._config[CONF_BRIGHTNESS]:
                    brightness = 255
                else:
                    brightness = kwargs.get(ATTR_BRIGHTNESS, 255)
                rgb = color_util.color_hsv_to_RGB(
                    hs_color[0], hs_color[1], brightness / 255 * 100
                )
                message["color"]["r"] = rgb[0]
                message["color"]["g"] = rgb[1]
                message["color"]["b"] = rgb[2]
            if self._config[CONF_XY]:
                xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
                message["color"]["x"] = xy_color[0]
                message["color"]["y"] = xy_color[1]
            if self._config[CONF_HS]:
                message["color"]["h"] = hs_color[0]
                message["color"]["s"] = hs_color[1]

            if self._optimistic:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_HS_COLOR in kwargs and self._supports_color_mode(ColorMode.HS):
            hs_color = kwargs[ATTR_HS_COLOR]
            message["color"] = {"h": hs_color[0], "s": hs_color[1]}
            if self._optimistic:
                self._color_mode = ColorMode.HS
                self._hs = hs_color
                should_update = True

        if ATTR_RGB_COLOR in kwargs and self._supports_color_mode(ColorMode.RGB):
            rgb = self._scale_rgbxx(kwargs[ATTR_RGB_COLOR], kwargs)
            message["color"] = {"r": rgb[0], "g": rgb[1], "b": rgb[2]}
            if self._optimistic:
                self._color_mode = ColorMode.RGB
                self._rgb = rgb
                should_update = True

        if ATTR_RGBW_COLOR in kwargs and self._supports_color_mode(ColorMode.RGBW):
            rgb = self._scale_rgbxx(kwargs[ATTR_RGBW_COLOR], kwargs)
            message["color"] = {"r": rgb[0], "g": rgb[1], "b": rgb[2], "w": rgb[3]}
            if self._optimistic:
                self._color_mode = ColorMode.RGBW
                self._rgbw = rgb
                should_update = True

        if ATTR_RGBWW_COLOR in kwargs and self._supports_color_mode(ColorMode.RGBWW):
            rgb = self._scale_rgbxx(kwargs[ATTR_RGBWW_COLOR], kwargs)
            message["color"] = {
                "r": rgb[0],
                "g": rgb[1],
                "b": rgb[2],
                "c": rgb[3],
                "w": rgb[4],
            }
            if self._optimistic:
                self._color_mode = ColorMode.RGBWW
                self._rgbww = rgb
                should_update = True

        if ATTR_XY_COLOR in kwargs and self._supports_color_mode(ColorMode.XY):
            xy = kwargs[ATTR_XY_COLOR]  # pylint: disable=invalid-name
            message["color"] = {"x": xy[0], "y": xy[1]}
            if self._optimistic:
                self._color_mode = ColorMode.XY
                self._xy = xy
                should_update = True

        self._set_flash_and_transition(message, **kwargs)

        if ATTR_BRIGHTNESS in kwargs and self._config[CONF_BRIGHTNESS]:
            brightness_normalized = kwargs[ATTR_BRIGHTNESS] / DEFAULT_BRIGHTNESS_SCALE
            brightness_scale = self._config[CONF_BRIGHTNESS_SCALE]
            device_brightness = min(
                round(brightness_normalized * brightness_scale), brightness_scale
            )
            # Make sure the brightness is not rounded down to 0
            device_brightness = max(device_brightness, 1)
            message["brightness"] = device_brightness

            if self._optimistic:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True

        if ATTR_COLOR_TEMP in kwargs:
            message["color_temp"] = int(kwargs[ATTR_COLOR_TEMP])

            if self._optimistic:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]
                should_update = True

        if ATTR_EFFECT in kwargs:
            message["effect"] = kwargs[ATTR_EFFECT]

            if self._optimistic:
                self._effect = kwargs[ATTR_EFFECT]
                should_update = True

        if ATTR_WHITE_VALUE in kwargs:
            message["white_value"] = int(kwargs[ATTR_WHITE_VALUE])

            if self._optimistic:
                self._white_value = kwargs[ATTR_WHITE_VALUE]
                should_update = True

        await self.async_publish(
            self._topic[CONF_COMMAND_TOPIC],
            json.dumps(message),
            self._config[CONF_QOS],
            self._config[CONF_RETAIN],
            self._config[CONF_ENCODING],
        )

        if self._optimistic:
            # Optimistically assume that the light has changed state.
            self._state = True
            should_update = True

        if should_update:
            self.async_write_ha_state()
Exemple #36
0
    def turn_on(self, **kwargs):
        """Turn on or control the light."""
        dps = {}

        if ATTR_BRIGHTNESS in kwargs:
            brightness = int(kwargs[ATTR_BRIGHTNESS])
            brightness = max(MIN_BRIGHTNESS, brightness)
            brightness = min(MAX_BRIGHTNESS, brightness)
            self._brightness = brightness

        if ATTR_COLOR_TEMP in kwargs and self._min_mireds is not None and self._max_mireds is not None:
            self._mode = MODE_WHITE
            color_temp = int(kwargs[ATTR_COLOR_TEMP])
            color_temp = max(color_temp, self._min_mireds)
            color_temp = min(color_temp, self._max_mireds)
            self._color_temp = color_temp
            self._hs_color = [0, 0]

        if ATTR_HS_COLOR in kwargs:
            self._mode = MODE_COLOR
            self._hs_color = kwargs.get(ATTR_HS_COLOR)

            if self._hs_color[1] < 5:
                self._mode = MODE_WHITE

        if self._mode == MODE_WHITE:
            mireds_range = self._max_mireds - self._min_mireds
            normalised_mireds = self._color_temp - self._min_mireds
            color_temp = int(
                round(255 - normalised_mireds / mireds_range * 255))
            dps = {}
            dps[self._dps_id] = True
            dps[DPS_INDEX_MODE] = self._mode
            dps[DPS_INDEX_BRIGHTNESS] = self._brightness
            dps[DPS_INDEX_COLOURTEMP] = color_temp

            _STATE.info("Setting white mode" + ", brightness = " +
                        str(self._brightness) + ", color_temp = " +
                        str(color_temp))
        else:
            lightness = int(
                round(self._brightness / MAX_BRIGHTNESS * MAX_LIGHTNESS))
            lightness = min(MAX_LIGHTNESS, lightness)
            rgb = color_util.color_hsv_to_RGB(self._hs_color[0],
                                              self._hs_color[1], lightness)

            red = format(int(rgb[0]), "02x")
            green = format(int(rgb[1]), "02x")
            blue = format(int(rgb[2]), "02x")

            h = format(int(self._hs_color[0]), "04x")
            s = format(int(self._hs_color[1]), "02x")
            v = format(lightness, "02x")

            hexvalue = red + green + blue + h + s + v

            dps = {}
            dps[self._dps_id] = True
            dps[DPS_INDEX_MODE] = self._mode
            dps[DPS_INDEX_COLOUR] = hexvalue

            _STATE.info("Setting color mode" + ", hs_colour = " +
                        str(self._hs_color) + ", brightness = " +
                        str(self._brightness) + ", hexvalue = " + hexvalue +
                        ", lightness = " + str(lightness))

        self._device.set_dps_set(dps)
Exemple #37
0
    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn on the light."""
        data: dict[str, Any] = {
            ATTR_ON: True,
            ATTR_SEGMENT_ID: self._segment,
        }

        if ATTR_COLOR_TEMP in kwargs:
            mireds = color_util.color_temperature_kelvin_to_mired(
                kwargs[ATTR_COLOR_TEMP]
            )
            data[ATTR_COLOR_PRIMARY] = tuple(
                map(int, color_util.color_temperature_to_rgb(mireds))
            )

        if ATTR_HS_COLOR in kwargs:
            hue, sat = kwargs[ATTR_HS_COLOR]
            data[ATTR_COLOR_PRIMARY] = color_util.color_hsv_to_RGB(hue, sat, 100)

        if ATTR_TRANSITION in kwargs:
            # WLED uses 100ms per unit, so 10 = 1 second.
            data[ATTR_TRANSITION] = round(kwargs[ATTR_TRANSITION] * 10)

        if ATTR_BRIGHTNESS in kwargs:
            data[ATTR_BRIGHTNESS] = kwargs[ATTR_BRIGHTNESS]

        if ATTR_EFFECT in kwargs:
            data[ATTR_EFFECT] = kwargs[ATTR_EFFECT]

        # Support for RGBW strips, adds white value
        if self._rgbw and any(
            x in (ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_WHITE_VALUE) for x in kwargs
        ):
            # WLED cannot just accept a white value, it needs the color.
            # We use the last know color in case just the white value changes.
            if all(x not in (ATTR_COLOR_TEMP, ATTR_HS_COLOR) for x in kwargs):
                hue, sat = self.hs_color
                data[ATTR_COLOR_PRIMARY] = color_util.color_hsv_to_RGB(hue, sat, 100)

            # On a RGBW strip, when the color is pure white, disable the RGB LEDs in
            # WLED by setting RGB to 0,0,0
            if data[ATTR_COLOR_PRIMARY] == (255, 255, 255):
                data[ATTR_COLOR_PRIMARY] = (0, 0, 0)

            # Add requested or last known white value
            if ATTR_WHITE_VALUE in kwargs:
                data[ATTR_COLOR_PRIMARY] += (kwargs[ATTR_WHITE_VALUE],)
            else:
                data[ATTR_COLOR_PRIMARY] += (self.white_value,)

        # When only 1 segment is present, switch along the master, and use
        # the master for power/brightness control.
        if len(self.coordinator.data.state.segments) == 1:
            master_data = {ATTR_ON: True}
            if ATTR_BRIGHTNESS in data:
                master_data[ATTR_BRIGHTNESS] = data[ATTR_BRIGHTNESS]
                data[ATTR_BRIGHTNESS] = 255

            if ATTR_TRANSITION in data:
                master_data[ATTR_TRANSITION] = data[ATTR_TRANSITION]
                del data[ATTR_TRANSITION]

            await self.coordinator.wled.segment(**data)
            await self.coordinator.wled.master(**master_data)
            return

        await self.coordinator.wled.segment(**data)
Exemple #38
0
    def rgb_color(self):
        """Return the RGB value."""
        hue, sat, bri, _ = self.device.color

        return color_util.color_hsv_to_RGB(
            hue, convert_16_to_8(sat), convert_16_to_8(bri))
Exemple #39
0
    def rgb_color(self):
        """Return the RGB value."""
        hue, sat, bri, _ = self.device.color

        return color_util.color_hsv_to_RGB(hue, convert_16_to_8(sat),
                                           convert_16_to_8(bri))
Exemple #40
0
         round(brightness_normalized * brightness_scale), brightness_scale
     )
     # Make sure the brightness is not rounded down to 0
     device_brightness = max(device_brightness, 1)
     publish(CONF_BRIGHTNESS_COMMAND_TOPIC, device_brightness)
     should_update |= set_optimistic(ATTR_BRIGHTNESS, kwargs[ATTR_BRIGHTNESS])
 elif (
     ATTR_BRIGHTNESS in kwargs
     and ATTR_HS_COLOR not in kwargs
     and self._topic[CONF_RGB_COMMAND_TOPIC] is not None
     and self._legacy_mode
 ):
     # Legacy mode
     hs_color = self._hs_color if self._hs_color is not None else (0, 0)
     brightness = kwargs[ATTR_BRIGHTNESS]
     rgb = scale_rgbx(color_util.color_hsv_to_RGB(*hs_color, 100), brightness)
     rgb_s = render_rgbx(rgb, CONF_RGB_COMMAND_TEMPLATE, COLOR_MODE_RGB)
     publish(CONF_RGB_COMMAND_TOPIC, rgb_s)
     should_update |= set_optimistic(ATTR_BRIGHTNESS, kwargs[ATTR_BRIGHTNESS])
 elif (
     ATTR_BRIGHTNESS in kwargs
     and ATTR_RGB_COLOR not in kwargs
     and self._topic[CONF_RGB_COMMAND_TOPIC] is not None
     and not self._legacy_mode
 ):
     rgb_color = self._rgb_color if self._rgb_color is not None else (255,) * 3
     rgb = scale_rgbx(rgb_color, kwargs[ATTR_BRIGHTNESS])
     rgb_s = render_rgbx(rgb, CONF_RGB_COMMAND_TEMPLATE, COLOR_MODE_RGB)
     publish(CONF_RGB_COMMAND_TOPIC, rgb_s)
     should_update |= set_optimistic(ATTR_BRIGHTNESS, kwargs[ATTR_BRIGHTNESS])
 elif (
    def async_turn_on(self, **kwargs):
        """Turn the device on.

        This method is a coroutine.
        """
        should_update = False

        message = {'state': 'ON'}

        if ATTR_HS_COLOR in kwargs and (self._rgb or self._xy):
            hs_color = kwargs[ATTR_HS_COLOR]
            message['color'] = {}
            if self._rgb:
                brightness = kwargs.get(
                    ATTR_BRIGHTNESS,
                    self._brightness if self._brightness else 255)
                rgb = color_util.color_hsv_to_RGB(
                    hs_color[0], hs_color[1], brightness / 255 * 100)
                message['color']['r'] = rgb[0]
                message['color']['g'] = rgb[1]
                message['color']['b'] = rgb[2]
            if self._xy:
                xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
                message['color']['x'] = xy_color[0]
                message['color']['y'] = xy_color[1]

            if self._optimistic:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_FLASH in kwargs:
            flash = kwargs.get(ATTR_FLASH)

            if flash == FLASH_LONG:
                message['flash'] = self._flash_times[CONF_FLASH_TIME_LONG]
            elif flash == FLASH_SHORT:
                message['flash'] = self._flash_times[CONF_FLASH_TIME_SHORT]

        if ATTR_TRANSITION in kwargs:
            message['transition'] = int(kwargs[ATTR_TRANSITION])

        if ATTR_BRIGHTNESS in kwargs:
            message['brightness'] = int(kwargs[ATTR_BRIGHTNESS] /
                                        float(DEFAULT_BRIGHTNESS_SCALE) *
                                        self._brightness_scale)

            if self._optimistic:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True

        if ATTR_COLOR_TEMP in kwargs:
            message['color_temp'] = int(kwargs[ATTR_COLOR_TEMP])

            if self._optimistic:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]
                should_update = True

        if ATTR_EFFECT in kwargs:
            message['effect'] = kwargs[ATTR_EFFECT]

            if self._optimistic:
                self._effect = kwargs[ATTR_EFFECT]
                should_update = True

        if ATTR_WHITE_VALUE in kwargs:
            message['white_value'] = int(kwargs[ATTR_WHITE_VALUE])

            if self._optimistic:
                self._white_value = kwargs[ATTR_WHITE_VALUE]
                should_update = True

        mqtt.async_publish(
            self.hass, self._topic[CONF_COMMAND_TOPIC], json.dumps(message),
            self._qos, self._retain)

        if self._optimistic:
            # Optimistically assume that the light has changed state.
            self._state = True
            should_update = True

        if should_update:
            self.async_schedule_update_ha_state()
    async def async_turn_on(self, **kwargs):
        """Turn the device on.
        This method is a coroutine.
        """
        should_update = False

        pre = SEPA_NAMESPACE.replace('?x',
                                     self._predicates[CONF_STATE_PREDICATE])
        obj = "\"" + self._payload['on'] + "\""
        data = self._sparql.replace('?s', self._subject).replace('?p',
                                                                 pre).replace(
                                                                     '?o', obj)

        if not sepa_update(self._update_url, data):
            _LOGGER.error("Failed sepa_update")
        should_update = True

        if ATTR_HS_COLOR in kwargs and \
           self._predicates[CONF_RGB_PREDICATE] is not None:

            hs_color = kwargs[ATTR_HS_COLOR]
            brightness = kwargs.get(
                ATTR_BRIGHTNESS, self._brightness if self._brightness else 255)
            rgb = color_util.color_hsv_to_RGB(hs_color[0], hs_color[1],
                                              brightness / 255 * 100)

            rgb_color_str = '{},{},{}'.format(*rgb)
            rgb_color_str = "\"" + rgb_color_str + "\""

            pre = SEPA_NAMESPACE.replace('?x',
                                         self._predicates[CONF_RGB_PREDICATE])
            obj = rgb_color_str
            data = self._sparql.replace('?s', self._subject).replace(
                '?p', pre).replace('?o', obj)

            if not sepa_update(self._update_url, data):
                _LOGGER.error("Failed sepa_update")

            self._hs = kwargs[ATTR_HS_COLOR]
            should_update = True

        if ATTR_HS_COLOR in kwargs and \
           self._predicates[CONF_XY_PREDICATE] is not None:

            xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
            xy_color_str = '{},{}'.format(*xy_color)
            xy_color_str = "\"" + xy_color_str + "\""

            pre = SEPA_NAMESPACE.replace('?x',
                                         self._predicates[CONF_XY_PREDICATE])
            obj = xy_color_str
            data = self._sparql.replace('?s', self._subject).replace(
                '?p', pre).replace('?o', obj)

            if not sepa_update(self._update_url, data):
                _LOGGER.error("Failed sepa_update")

            self._hs = kwargs[ATTR_HS_COLOR]
            should_update = True

        if ATTR_BRIGHTNESS in kwargs and \
           self._predicates[CONF_BRIGHTNESS_PREDICATE] is not None:
            percent_bright = float(kwargs[ATTR_BRIGHTNESS]) / 255
            device_brightness = int(percent_bright * self._brightness_scale)
            device_brightness_str = "\"" + str(device_brightness) + "\""

            pre = SEPA_NAMESPACE.replace(
                '?x', self._predicates[CONF_BRIGHTNESS_PREDICATE])
            obj = device_brightness_str
            data = self._sparql.replace('?s', self._subject).replace(
                '?p', pre).replace('?o', obj)

            if not sepa_update(self._update_url, data):
                _LOGGER.error("Failed sepa_update")

            self._brightness = kwargs[ATTR_BRIGHTNESS]
            should_update = True

        if ATTR_COLOR_TEMP in kwargs and \
           self._predicates[CONF_COLOR_TEMP_PREDICATE] is not None:
            color_temp = int(kwargs[ATTR_COLOR_TEMP])
            color_temp_str = "\"" + str(color_temp) + "\""

            pre = SEPA_NAMESPACE.replace(
                '?x', self._predicates[CONF_COLOR_TEMP_PREDICATE])
            obj = color_temp_str
            data = self._sparql.replace('?s', self._subject).replace(
                '?p', pre).replace('?o', obj)

            if not sepa_update(self._update_url, data):
                _LOGGER.error("Failed sepa_update")

            self._color_temp = kwargs[ATTR_COLOR_TEMP]
            should_update = True

        if ATTR_EFFECT in kwargs and \
           self._predicates[CONF_EFFECT_PREDICATE] is not None:
            effect = kwargs[ATTR_EFFECT]
            if effect in self._effect_list:

                pre = SEPA_NAMESPACE.replace(
                    '?x', self._predicates[CONF_EFFECT_PREDICATE])
                obj = effect
                data = self._sparql.replace('?s', self._subject).replace(
                    '?p', pre).replace('?o', obj)

                if not sepa_update(self._update_url, data):
                    _LOGGER.error("Failed sepa_update")

                self._effect = kwargs[ATTR_EFFECT]
                should_update = True

        if ATTR_WHITE_VALUE in kwargs and \
           self._predicates[CONF_WHITE_VALUE_PREDICATE] is not None:
            percent_white = float(kwargs[ATTR_WHITE_VALUE]) / 255
            device_white_value = int(percent_white * self._white_value_scale)
            device_white_value_str = "\"" + str(device_white_value) + "\""

            pre = SEPA_NAMESPACE.replace(
                '?x', self._predicates[CONF_WHITE_VALUE_PREDICATE])
            obj = device_white_value_str
            data = self._sparql.replace('?s', self._subject).replace(
                '?x', pre).replace('?o', obj)

            if not sepa_update(self._update_url, data):
                _LOGGER.error("Failed sepa_update")

            self._white_value = kwargs[ATTR_WHITE_VALUE]
            should_update = True

        # Optimistically assume that switch has changed state.
        self._state = True
        should_update = True

        if should_update:
            self.async_schedule_update_ha_state()
Exemple #43
0
    async def async_turn_on(self, **kwargs):
        """Turn on or control the light."""
        states = {}
        states[self._dp_id] = True
        features = self.supported_features
        if ATTR_BRIGHTNESS in kwargs and (features & SUPPORT_BRIGHTNESS):
            brightness = map_range(
                int(kwargs[ATTR_BRIGHTNESS]),
                0,
                255,
                self._lower_brightness,
                self._upper_brightness,
            )
            if self._is_white_mode:
                states[self._config.get(CONF_BRIGHTNESS)] = brightness

            else:
                if self.__is_color_rgb_encoded():
                    rgb = color_util.color_hsv_to_RGB(
                        self._hs[0],
                        self._hs[1],
                        int(brightness * 100 / self._upper_brightness),
                    )
                    color = "{:02x}{:02x}{:02x}{:04x}{:02x}{:02x}".format(
                        round(rgb[0]),
                        round(rgb[1]),
                        round(rgb[2]),
                        round(self._hs[0]),
                        round(self._hs[1] * 255 / 100),
                        brightness,
                    )
                else:
                    color = "{:04x}{:04x}{:04x}".format(
                        round(self._hs[0]), round(self._hs[1] * 10.0),
                        brightness)
                states[self._config.get(CONF_COLOR)] = color

        if ATTR_HS_COLOR in kwargs and (features & SUPPORT_COLOR):
            hs = kwargs[ATTR_HS_COLOR]
            if self.__is_color_rgb_encoded():
                rgb = color_util.color_hsv_to_RGB(
                    hs[0], hs[1],
                    int(self._brightness * 100 / self._upper_brightness))
                color = "{:02x}{:02x}{:02x}{:04x}{:02x}{:02x}".format(
                    round(rgb[0]),
                    round(rgb[1]),
                    round(rgb[2]),
                    round(hs[0]),
                    round(hs[1] * 255 / 100),
                    self._brightness,
                )
            else:
                color = "{:04x}{:04x}{:04x}".format(round(hs[0]),
                                                    round(hs[1] * 10.0),
                                                    self._brightness)
            states[self._config.get(CONF_COLOR)] = color
            if self._is_white_mode:
                states[self._config.get(CONF_COLOR_MODE)] = "colour"

        if ATTR_COLOR_TEMP in kwargs and (features & SUPPORT_COLOR_TEMP):
            color_temp = int(self._upper_color_temp -
                             (self._upper_color_temp /
                              (self._max_mired - self._min_mired)) *
                             (int(kwargs[ATTR_COLOR_TEMP]) - self._min_mired))
            if not self._is_white_mode:
                states[self._config.get(CONF_COLOR_MODE)] = "white"
                states[self._config.get(CONF_BRIGHTNESS)] = self._brightness
            states[self._config.get(CONF_COLOR_TEMP)] = color_temp

        await self._device.set_dps(states)
Exemple #44
0
    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn on the light."""
        data = {ATTR_ON: True, ATTR_SEGMENT_ID: self._segment}

        if ATTR_COLOR_TEMP in kwargs:
            mireds = color_util.color_temperature_kelvin_to_mired(
                kwargs[ATTR_COLOR_TEMP]
            )
            data[ATTR_COLOR_PRIMARY] = tuple(
                map(int, color_util.color_temperature_to_rgb(mireds))
            )

        if ATTR_HS_COLOR in kwargs:
            hue, sat = kwargs[ATTR_HS_COLOR]
            data[ATTR_COLOR_PRIMARY] = color_util.color_hsv_to_RGB(hue, sat, 100)

        if ATTR_TRANSITION in kwargs:
            data[ATTR_TRANSITION] = kwargs[ATTR_TRANSITION]

        if ATTR_BRIGHTNESS in kwargs:
            data[ATTR_BRIGHTNESS] = kwargs[ATTR_BRIGHTNESS]

        if ATTR_EFFECT in kwargs:
            data[ATTR_EFFECT] = kwargs[ATTR_EFFECT]

        # Support for RGBW strips, adds white value
        if self._rgbw and any(
            x in (ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_WHITE_VALUE) for x in kwargs
        ):
            # WLED cannot just accept a white value, it needs the color.
            # We use the last know color in case just the white value changes.
            if not any(x in (ATTR_COLOR_TEMP, ATTR_HS_COLOR) for x in kwargs):
                hue, sat = self._color
                data[ATTR_COLOR_PRIMARY] = color_util.color_hsv_to_RGB(hue, sat, 100)

            # Add requested or last known white value
            if ATTR_WHITE_VALUE in kwargs:
                data[ATTR_COLOR_PRIMARY] += (kwargs[ATTR_WHITE_VALUE],)
            else:
                data[ATTR_COLOR_PRIMARY] += (self._white_value,)

        try:
            await self.wled.light(**data)

            self._state = True

            if ATTR_BRIGHTNESS in kwargs:
                self._brightness = kwargs[ATTR_BRIGHTNESS]

            if ATTR_EFFECT in kwargs:
                self._effect = kwargs[ATTR_EFFECT]

            if ATTR_HS_COLOR in kwargs:
                self._color = kwargs[ATTR_HS_COLOR]

            if ATTR_COLOR_TEMP in kwargs:
                self._color = color_util.color_temperature_to_hs(mireds)

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

        except WLEDError:
            _LOGGER.error("An error occurred while turning on WLED light.")
            self._available = False
        self.async_schedule_update_ha_state()
Exemple #45
0
    async def async_turn_on(self, **kwargs):
        """Turn the device on.

        This method is a coroutine.
        """
        should_update = False
        on_command_type = self._config[CONF_ON_COMMAND_TYPE]

        if on_command_type == "first":
            mqtt.async_publish(
                self.hass,
                self._topic[CONF_COMMAND_TOPIC],
                self._payload["on"],
                self._config[CONF_QOS],
                self._config[CONF_RETAIN],
            )
            should_update = True

        # If brightness is being used instead of an on command, make sure
        # there is a brightness input.  Either set the brightness to our
        # saved value or the maximum value if this is the first call
        elif on_command_type == "brightness":
            if ATTR_BRIGHTNESS not in kwargs:
                kwargs[
                    ATTR_BRIGHTNESS] = self._brightness if self._brightness else 255

        if ATTR_HS_COLOR in kwargs and self._topic[
                CONF_RGB_COMMAND_TOPIC] is not None:

            hs_color = kwargs[ATTR_HS_COLOR]

            # If there's a brightness topic set, we don't want to scale the RGB
            # values given using the brightness.
            if self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
                brightness = 255
            else:
                brightness = kwargs.get(
                    ATTR_BRIGHTNESS,
                    self._brightness if self._brightness else 255)
            rgb = color_util.color_hsv_to_RGB(hs_color[0], hs_color[1],
                                              brightness / 255 * 100)
            tpl = self._command_templates[CONF_RGB_COMMAND_TEMPLATE]
            if tpl:
                rgb_color_str = tpl({
                    "red": rgb[0],
                    "green": rgb[1],
                    "blue": rgb[2]
                })
            else:
                rgb_color_str = f"{rgb[0]},{rgb[1]},{rgb[2]}"

            mqtt.async_publish(
                self.hass,
                self._topic[CONF_RGB_COMMAND_TOPIC],
                rgb_color_str,
                self._config[CONF_QOS],
                self._config[CONF_RETAIN],
            )

            if self._optimistic_rgb:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_HS_COLOR in kwargs and self._topic[
                CONF_HS_COMMAND_TOPIC] is not None:

            hs_color = kwargs[ATTR_HS_COLOR]
            mqtt.async_publish(
                self.hass,
                self._topic[CONF_HS_COMMAND_TOPIC],
                f"{hs_color[0]},{hs_color[1]}",
                self._config[CONF_QOS],
                self._config[CONF_RETAIN],
            )

            if self._optimistic_hs:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_HS_COLOR in kwargs and self._topic[
                CONF_XY_COMMAND_TOPIC] is not None:

            xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
            mqtt.async_publish(
                self.hass,
                self._topic[CONF_XY_COMMAND_TOPIC],
                f"{xy_color[0]},{xy_color[1]}",
                self._config[CONF_QOS],
                self._config[CONF_RETAIN],
            )

            if self._optimistic_xy:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if (ATTR_BRIGHTNESS in kwargs
                and self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None):
            brightness_normalized = kwargs[ATTR_BRIGHTNESS] / 255
            brightness_scale = self._config[CONF_BRIGHTNESS_SCALE]
            device_brightness = min(
                round(brightness_normalized * brightness_scale),
                brightness_scale)
            # Make sure the brightness is not rounded down to 0
            device_brightness = max(device_brightness, 1)
            mqtt.async_publish(
                self.hass,
                self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC],
                device_brightness,
                self._config[CONF_QOS],
                self._config[CONF_RETAIN],
            )

            if self._optimistic_brightness:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True
        elif (ATTR_BRIGHTNESS in kwargs and ATTR_HS_COLOR not in kwargs
              and self._topic[CONF_RGB_COMMAND_TOPIC] is not None):
            hs_color = self._hs if self._hs is not None else (0, 0)
            rgb = color_util.color_hsv_to_RGB(
                hs_color[0], hs_color[1], kwargs[ATTR_BRIGHTNESS] / 255 * 100)
            tpl = self._command_templates[CONF_RGB_COMMAND_TEMPLATE]
            if tpl:
                rgb_color_str = tpl({
                    "red": rgb[0],
                    "green": rgb[1],
                    "blue": rgb[2]
                })
            else:
                rgb_color_str = f"{rgb[0]},{rgb[1]},{rgb[2]}"

            mqtt.async_publish(
                self.hass,
                self._topic[CONF_RGB_COMMAND_TOPIC],
                rgb_color_str,
                self._config[CONF_QOS],
                self._config[CONF_RETAIN],
            )

            if self._optimistic_brightness:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True

        if (ATTR_COLOR_TEMP in kwargs
                and self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC] is not None):
            color_temp = int(kwargs[ATTR_COLOR_TEMP])
            tpl = self._command_templates[CONF_COLOR_TEMP_COMMAND_TEMPLATE]

            if tpl:
                color_temp = tpl({"value": color_temp})

            mqtt.async_publish(
                self.hass,
                self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC],
                color_temp,
                self._config[CONF_QOS],
                self._config[CONF_RETAIN],
            )

            if self._optimistic_color_temp:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]
                should_update = True

        if ATTR_EFFECT in kwargs and self._topic[
                CONF_EFFECT_COMMAND_TOPIC] is not None:
            effect = kwargs[ATTR_EFFECT]
            if effect in self._config.get(CONF_EFFECT_LIST):
                mqtt.async_publish(
                    self.hass,
                    self._topic[CONF_EFFECT_COMMAND_TOPIC],
                    effect,
                    self._config[CONF_QOS],
                    self._config[CONF_RETAIN],
                )

                if self._optimistic_effect:
                    self._effect = kwargs[ATTR_EFFECT]
                    should_update = True

        if (ATTR_WHITE_VALUE in kwargs
                and self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC] is not None):
            percent_white = float(kwargs[ATTR_WHITE_VALUE]) / 255
            white_scale = self._config[CONF_WHITE_VALUE_SCALE]
            device_white_value = min(round(percent_white * white_scale),
                                     white_scale)
            mqtt.async_publish(
                self.hass,
                self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC],
                device_white_value,
                self._config[CONF_QOS],
                self._config[CONF_RETAIN],
            )

            if self._optimistic_white_value:
                self._white_value = kwargs[ATTR_WHITE_VALUE]
                should_update = True

        if on_command_type == "last":
            mqtt.async_publish(
                self.hass,
                self._topic[CONF_COMMAND_TOPIC],
                self._payload["on"],
                self._config[CONF_QOS],
                self._config[CONF_RETAIN],
            )
            should_update = True

        if self._optimistic:
            # Optimistically assume that the light has changed state.
            self._state = True
            should_update = True

        if should_update:
            self.async_write_ha_state()
Exemple #46
0
    async def async_turn_on(self, **kwargs):
        """Turn the device on.

        This method is a coroutine.
        """
        should_update = False

        message = {'state': 'ON'}

        if ATTR_HS_COLOR in kwargs and (self._hs_support or self._rgb
                                        or self._xy):
            hs_color = kwargs[ATTR_HS_COLOR]
            message['color'] = {}
            if self._rgb:
                # If there's a brightness topic set, we don't want to scale the
                # RGB values given using the brightness.
                if self._brightness is not None:
                    brightness = 255
                else:
                    brightness = kwargs.get(
                        ATTR_BRIGHTNESS,
                        self._brightness if self._brightness else 255)
                rgb = color_util.color_hsv_to_RGB(hs_color[0], hs_color[1],
                                                  brightness / 255 * 100)
                message['color']['r'] = rgb[0]
                message['color']['g'] = rgb[1]
                message['color']['b'] = rgb[2]
            if self._xy:
                xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
                message['color']['x'] = xy_color[0]
                message['color']['y'] = xy_color[1]
            if self._hs_support:
                message['color']['h'] = hs_color[0]
                message['color']['s'] = hs_color[1]

            if self._optimistic:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_FLASH in kwargs:
            flash = kwargs.get(ATTR_FLASH)

            if flash == FLASH_LONG:
                message['flash'] = self._flash_times[CONF_FLASH_TIME_LONG]
            elif flash == FLASH_SHORT:
                message['flash'] = self._flash_times[CONF_FLASH_TIME_SHORT]

        if ATTR_TRANSITION in kwargs:
            message['transition'] = int(kwargs[ATTR_TRANSITION])

        if ATTR_BRIGHTNESS in kwargs:
            message['brightness'] = int(kwargs[ATTR_BRIGHTNESS] /
                                        float(DEFAULT_BRIGHTNESS_SCALE) *
                                        self._brightness_scale)

            if self._optimistic:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True

        if ATTR_COLOR_TEMP in kwargs:
            message['color_temp'] = int(kwargs[ATTR_COLOR_TEMP])

            if self._optimistic:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]
                should_update = True

        if ATTR_EFFECT in kwargs:
            message['effect'] = kwargs[ATTR_EFFECT]

            if self._optimistic:
                self._effect = kwargs[ATTR_EFFECT]
                should_update = True

        if ATTR_WHITE_VALUE in kwargs:
            message['white_value'] = int(kwargs[ATTR_WHITE_VALUE])

            if self._optimistic:
                self._white_value = kwargs[ATTR_WHITE_VALUE]
                should_update = True

        mqtt.async_publish(self.hass, self._topic[CONF_COMMAND_TOPIC],
                           json.dumps(message), self._qos, self._retain)

        if self._optimistic:
            # Optimistically assume that the light has changed state.
            self._state = True
            should_update = True

        if should_update:
            self.async_schedule_update_ha_state()
Exemple #47
0
    async def async_turn_on(self, **kwargs):
        """Switch the light on, change brightness, change color."""
        if self._ambient:
            if ATTR_BRIGHTNESS in kwargs or ATTR_HS_COLOR in kwargs:
                try:
                    await self.hass.async_add_executor_job(
                        self.device.appliance.set_setting,
                        self._colorkey,
                        BSH_AMBIENTLIGHTCOLOR_CUSTOMCOLOR,
                    )
                except HomeConnectError as err:
                    _LOGGER.error(
                        "Error while trying selecting customcolor: %s", err)
                if self._brightness != None:
                    brightness = 10 + ceil(self._brightness / 255 * 90)
                    if ATTR_BRIGHTNESS in kwargs:
                        brightness = 10 + ceil(
                            kwargs[ATTR_BRIGHTNESS] / 255 * 90)

                    hs_color = self._hs_color
                    if ATTR_HS_COLOR in kwargs:
                        hs_color = kwargs[ATTR_HS_COLOR]

                    if hs_color != None:
                        rgb = color_util.color_hsv_to_RGB(
                            *hs_color, brightness)
                        hex = color_util.color_rgb_to_hex(
                            rgb[0], rgb[1], rgb[2])
                        try:
                            await self.hass.async_add_executor_job(
                                self.device.appliance.set_setting,
                                self._customcolorkey,
                                "#" + hex,
                            )
                        except HomeConnectError as err:
                            _LOGGER.error(
                                "Error while trying setting the color: %s",
                                err)
                            self._state = False
            else:
                _LOGGER.debug("Tried to switch light on for: %s", self.name)
                try:
                    await self.hass.async_add_executor_job(
                        self.device.appliance.set_setting,
                        self._key,
                        True,
                    )
                except HomeConnectError as err:
                    _LOGGER.error(
                        "Error while trying to turn on ambient light: %s", err)
                    self._state = False

        elif ATTR_BRIGHTNESS in kwargs:
            _LOGGER.debug("Tried to change brightness for: %s", self.name)
            """Convert Home Assistant brightness (0-255) to Home Connect brightness (10-100)."""
            brightness = 10 + ceil(kwargs[ATTR_BRIGHTNESS] / 255 * 90)
            try:
                await self.hass.async_add_executor_job(
                    self.device.appliance.set_setting,
                    self._brightnesskey,
                    brightness,
                )
            except HomeConnectError as err:
                _LOGGER.error("Error while trying set the brightness: %s", err)
                self._state = False
                self._brightness = None
        else:
            _LOGGER.debug("Tried to switch light on for: %s", self.name)
            try:
                await self.hass.async_add_executor_job(
                    self.device.appliance.set_setting,
                    self._key,
                    True,
                )
            except HomeConnectError as err:
                _LOGGER.error("Error while trying to turn on light: %s", err)
                self._state = False

        self.async_entity_update()
Exemple #48
0
    async def async_turn_on(self, **kwargs):
        """Turn the device on.

        This method is a coroutine.
        """
        should_update = False
        on_command_type = self._config.get(CONF_ON_COMMAND_TYPE)

        if on_command_type == 'first':
            mqtt.async_publish(
                self.hass, self._topic[CONF_COMMAND_TOPIC],
                self._payload['on'], self._config.get(CONF_QOS),
                self._config.get(CONF_RETAIN))
            should_update = True

        # If brightness is being used instead of an on command, make sure
        # there is a brightness input.  Either set the brightness to our
        # saved value or the maximum value if this is the first call
        elif on_command_type == 'brightness':
            if ATTR_BRIGHTNESS not in kwargs:
                kwargs[ATTR_BRIGHTNESS] = self._brightness if \
                                          self._brightness else 255

        if ATTR_HS_COLOR in kwargs and \
           self._topic[CONF_RGB_COMMAND_TOPIC] is not None:

            hs_color = kwargs[ATTR_HS_COLOR]

            # If there's a brightness topic set, we don't want to scale the RGB
            # values given using the brightness.
            if self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
                brightness = 255
            else:
                brightness = kwargs.get(
                    ATTR_BRIGHTNESS, self._brightness if self._brightness else
                    255)
            rgb = color_util.color_hsv_to_RGB(
                hs_color[0], hs_color[1], brightness / 255 * 100)
            tpl = self._templates[CONF_RGB_COMMAND_TEMPLATE]
            if tpl:
                rgb_color_str = tpl.async_render({
                    'red': rgb[0],
                    'green': rgb[1],
                    'blue': rgb[2],
                })
            else:
                rgb_color_str = '{},{},{}'.format(*rgb)

            mqtt.async_publish(
                self.hass, self._topic[CONF_RGB_COMMAND_TOPIC],
                rgb_color_str, self._config.get(CONF_QOS),
                self._config.get(CONF_RETAIN))

            if self._optimistic_rgb:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_HS_COLOR in kwargs and \
           self._topic[CONF_HS_COMMAND_TOPIC] is not None:

            hs_color = kwargs[ATTR_HS_COLOR]
            mqtt.async_publish(
                self.hass, self._topic[CONF_HS_COMMAND_TOPIC],
                '{},{}'.format(*hs_color), self._config.get(CONF_QOS),
                self._config.get(CONF_RETAIN))

            if self._optimistic_hs:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_HS_COLOR in kwargs and \
           self._topic[CONF_XY_COMMAND_TOPIC] is not None:

            xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
            mqtt.async_publish(
                self.hass, self._topic[CONF_XY_COMMAND_TOPIC],
                '{},{}'.format(*xy_color), self._config.get(CONF_QOS),
                self._config.get(CONF_RETAIN))

            if self._optimistic_xy:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_BRIGHTNESS in kwargs and \
           self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC] is not None:
            percent_bright = float(kwargs[ATTR_BRIGHTNESS]) / 255
            brightness_scale = self._config.get(CONF_BRIGHTNESS_SCALE)
            device_brightness = \
                min(round(percent_bright * brightness_scale), brightness_scale)
            mqtt.async_publish(
                self.hass, self._topic[CONF_BRIGHTNESS_COMMAND_TOPIC],
                device_brightness, self._config.get(CONF_QOS),
                self._config.get(CONF_RETAIN))

            if self._optimistic_brightness:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True
        elif ATTR_BRIGHTNESS in kwargs and ATTR_HS_COLOR not in kwargs and\
                self._topic[CONF_RGB_COMMAND_TOPIC] is not None:
            rgb = color_util.color_hsv_to_RGB(
                self._hs[0], self._hs[1], kwargs[ATTR_BRIGHTNESS] / 255 * 100)
            tpl = self._templates[CONF_RGB_COMMAND_TEMPLATE]
            if tpl:
                rgb_color_str = tpl.async_render({
                    'red': rgb[0],
                    'green': rgb[1],
                    'blue': rgb[2],
                })
            else:
                rgb_color_str = '{},{},{}'.format(*rgb)

            mqtt.async_publish(
                self.hass, self._topic[CONF_RGB_COMMAND_TOPIC],
                rgb_color_str, self._config.get(CONF_QOS),
                self._config.get(CONF_RETAIN))

            if self._optimistic_brightness:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True

        if ATTR_COLOR_TEMP in kwargs and \
           self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC] is not None:
            color_temp = int(kwargs[ATTR_COLOR_TEMP])
            tpl = self._templates[CONF_COLOR_TEMP_COMMAND_TEMPLATE]

            if tpl:
                color_temp = tpl.async_render({
                    'value': color_temp,
                })

            mqtt.async_publish(
                self.hass, self._topic[CONF_COLOR_TEMP_COMMAND_TOPIC],
                color_temp, self._config.get(CONF_QOS),
                self._config.get(CONF_RETAIN))

            if self._optimistic_color_temp:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]
                should_update = True

        if ATTR_EFFECT in kwargs and \
           self._topic[CONF_EFFECT_COMMAND_TOPIC] is not None:
            effect = kwargs[ATTR_EFFECT]
            if effect in self._config.get(CONF_EFFECT_LIST):
                mqtt.async_publish(
                    self.hass, self._topic[CONF_EFFECT_COMMAND_TOPIC],
                    effect, self._config.get(CONF_QOS),
                    self._config.get(CONF_RETAIN))

                if self._optimistic_effect:
                    self._effect = kwargs[ATTR_EFFECT]
                    should_update = True

        if ATTR_WHITE_VALUE in kwargs and \
           self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC] is not None:
            percent_white = float(kwargs[ATTR_WHITE_VALUE]) / 255
            white_scale = self._config.get(CONF_WHITE_VALUE_SCALE)
            device_white_value = \
                min(round(percent_white * white_scale), white_scale)
            mqtt.async_publish(
                self.hass, self._topic[CONF_WHITE_VALUE_COMMAND_TOPIC],
                device_white_value, self._config.get(CONF_QOS),
                self._config.get(CONF_RETAIN))

            if self._optimistic_white_value:
                self._white_value = kwargs[ATTR_WHITE_VALUE]
                should_update = True

        if on_command_type == 'last':
            mqtt.async_publish(self.hass, self._topic[CONF_COMMAND_TOPIC],
                               self._payload['on'], self._config.get(CONF_QOS),
                               self._config.get(CONF_RETAIN))
            should_update = True

        if self._optimistic:
            # Optimistically assume that the light has changed state.
            self._state = True
            should_update = True

        if should_update:
            self.async_schedule_update_ha_state()
Exemple #49
0
            publish(CONF_COMMAND_TOPIC, self._payload["on"])
            should_update = True

        # If brightness is being used instead of an on command, make sure
        # there is a brightness input.  Either set the brightness to our
        # saved value or the maximum value if this is the first call
        elif (on_command_type == "brightness" and ATTR_BRIGHTNESS not in kwargs
              and ATTR_WHITE not in kwargs):
            kwargs[
                ATTR_BRIGHTNESS] = self._brightness if self._brightness else 255

        hs_color = kwargs.get(ATTR_HS_COLOR)
        if (hs_color and self._topic[CONF_RGB_COMMAND_TOPIC] is not None
                and self._legacy_mode):
            # Legacy mode: Convert HS to RGB
            rgb = scale_rgbx(color_util.color_hsv_to_RGB(*hs_color, 100))
            rgb_s = render_rgbx(rgb, CONF_RGB_COMMAND_TEMPLATE, COLOR_MODE_RGB)
            publish(CONF_RGB_COMMAND_TOPIC, rgb_s)
            should_update |= set_optimistic(ATTR_HS_COLOR,
                                            hs_color,
                                            condition_attribute=ATTR_RGB_COLOR)

        if hs_color and self._topic[CONF_HS_COMMAND_TOPIC] is not None:
            publish(CONF_HS_COMMAND_TOPIC, f"{hs_color[0]},{hs_color[1]}")
            should_update |= set_optimistic(ATTR_HS_COLOR, hs_color,
                                            COLOR_MODE_HS)

        if (hs_color and self._topic[CONF_XY_COMMAND_TOPIC] is not None
                and self._legacy_mode):
            # Legacy mode: Convert HS to XY
            xy_color = color_util.color_hs_to_xy(*hs_color)
Exemple #50
0
    async def async_turn_on(self, **kwargs):
        """Turn on or control the light."""
        states = {}
        if not self.is_on:
            states[self._dp_id] = True
        features = self.supported_features
        brightness = None
        if ATTR_EFFECT in kwargs and (features & SUPPORT_EFFECT):
            scene = self._scenes.get(kwargs[ATTR_EFFECT])
            if scene is not None:
                if scene.startswith(MODE_SCENE):
                    states[self._config.get(CONF_COLOR_MODE)] = scene
                else:
                    states[self._config.get(CONF_COLOR_MODE)] = MODE_SCENE
                    states[self._config.get(CONF_SCENE)] = scene
            elif kwargs[ATTR_EFFECT] == SCENE_MUSIC:
                states[self._config.get(CONF_COLOR_MODE)] = MODE_MUSIC

        if ATTR_BRIGHTNESS in kwargs and (features & SUPPORT_BRIGHTNESS):
            brightness = map_range(
                int(kwargs[ATTR_BRIGHTNESS]),
                0,
                255,
                self._lower_brightness,
                self._upper_brightness,
            )
            if self.is_white_mode:
                states[self._config.get(CONF_BRIGHTNESS)] = brightness
            else:
                if self.__is_color_rgb_encoded():
                    rgb = color_util.color_hsv_to_RGB(
                        self._hs[0],
                        self._hs[1],
                        int(brightness * 100 / self._upper_brightness),
                    )
                    color = "{:02x}{:02x}{:02x}{:04x}{:02x}{:02x}".format(
                        round(rgb[0]),
                        round(rgb[1]),
                        round(rgb[2]),
                        round(self._hs[0]),
                        round(self._hs[1] * 255 / 100),
                        brightness,
                    )
                else:
                    color = "{:04x}{:04x}{:04x}".format(
                        round(self._hs[0]), round(self._hs[1] * 10.0),
                        brightness)
                states[self._config.get(CONF_COLOR)] = color
                states[self._config.get(CONF_COLOR_MODE)] = MODE_COLOR

        if ATTR_HS_COLOR in kwargs and (features & SUPPORT_COLOR):
            if brightness is None:
                brightness = self._brightness
            hs = kwargs[ATTR_HS_COLOR]
            if hs[1] == 0 and self.has_config(CONF_BRIGHTNESS):
                states[self._config.get(CONF_BRIGHTNESS)] = brightness
                states[self._config.get(CONF_COLOR_MODE)] = MODE_WHITE
            else:
                if self.__is_color_rgb_encoded():
                    rgb = color_util.color_hsv_to_RGB(
                        hs[0], hs[1],
                        int(brightness * 100 / self._upper_brightness))
                    color = "{:02x}{:02x}{:02x}{:04x}{:02x}{:02x}".format(
                        round(rgb[0]),
                        round(rgb[1]),
                        round(rgb[2]),
                        round(hs[0]),
                        round(hs[1] * 255 / 100),
                        brightness,
                    )
                else:
                    color = "{:04x}{:04x}{:04x}".format(
                        round(hs[0]), round(hs[1] * 10.0), brightness)
                states[self._config.get(CONF_COLOR)] = color
                states[self._config.get(CONF_COLOR_MODE)] = MODE_COLOR

        if ATTR_COLOR_TEMP in kwargs and (features & SUPPORT_COLOR_TEMP):
            if brightness is None:
                brightness = self._brightness
            color_temp = int(self._upper_color_temp -
                             (self._upper_color_temp /
                              (self._max_mired - self._min_mired)) *
                             (int(kwargs[ATTR_COLOR_TEMP]) - self._min_mired))
            states[self._config.get(CONF_COLOR_MODE)] = MODE_WHITE
            states[self._config.get(CONF_BRIGHTNESS)] = brightness
            states[self._config.get(CONF_COLOR_TEMP)] = color_temp
        await self._device.set_dps(states)
Exemple #51
0
    def turn_on(self, **kwargs):
        """Turn Tuya switch on."""
        if not self._state:
            self._device.set_status(True)

        if ATTR_HS_COLOR in kwargs:
            hs_color = kwargs.get(ATTR_HS_COLOR)
            brightness = kwargs.get(
                ATTR_BRIGHTNESS, self._brightness if self._brightness else 255)
            rgb = color_util.color_hsv_to_RGB(hs_color[0], hs_color[1],
                                              brightness / 500 * 100)
            try:
                if rgb[0] < 240 or rgb[1] < 240 or rgb[2] < 240:
                    self._device.set_colour(rgb[0], rgb[1], rgb[2])
                    self._color_mode = True
                    self._hs_color = hs_color
                    self._brightness = brightness
                    self._rgbcolor = [rgb[0], rgb[1], rgb[2]]
                else:
                    self._device.set_white(
                        25 if int(brightness / 500 * 255) < 25 else int(
                            brightness / 500 * 255),
                        int((self._color_temp / 500) * 255))
                    self._color_mode = False
                    self._hs_color = hs_color
                    self._rgbcolor = [rgb[0], rgb[1], rgb[2]]

            except ConnectionError as e:
                pass

        if ATTR_BRIGHTNESS in kwargs:
            brightness = kwargs.get(ATTR_BRIGHTNESS)
            if self._color_mode:
                rgb = color_util.color_hsv_to_RGB(self._hs_color[0],
                                                  self._hs_color[1],
                                                  brightness / 500 * 100)
                try:
                    self._device.set_colour(rgb[0], rgb[1], rgb[2])
                    self._brightness = brightness
                    self._rgbcolor = [rgb[0], rgb[1], rgb[2]]
                except ConnectionError as e:
                    pass
            else:
                try:
                    self._device.set_white(
                        25 if int(brightness / 500 * 255) < 25 else int(
                            brightness / 500 * 255),
                        int((self._color_temp / 500) * 255))
                    self._brightness = brightness
                except ConnectionError as e:
                    pass

        if ATTR_COLOR_TEMP in kwargs:
            color_temp = kwargs.get(ATTR_COLOR_TEMP)
            try:
                self._device.set_white(
                    25 if int(self._brightness / 500 * 255) < 25 else int(
                        self._brightness / 500 * 255),
                    int((color_temp / 500) * 255))
                self._color_mode = False
                self._color_temp = color_temp
            except ConnectionError as e:
                pass