Пример #1
0
 def calc_rgb(self):
     if self.is_sleep():
         _LOGGER.debug(self._name + " in Sleep mode")
         return color_temperature_to_rgb(
             self._attributes['sleep_colortemp'])
     else:
         return color_temperature_to_rgb(self._cl.data['colortemp'])
Пример #2
0
    def flux_update(self, now=None):
        """Update all the lights using flux."""
        if now is None:
            now = dt_now()
        sunset = next_setting(self.hass, SUN).replace(day=now.day,
                                                      month=now.month,
                                                      year=now.year)
        start_time = self.find_start_time(now)
        stop_time = now.replace(hour=self._stop_time.hour,
                                minute=self._stop_time.minute,
                                second=0)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Nightime
            time_state = 'night'
            if now < stop_time and now > start_time:
                now_time = now
            else:
                now_time = stop_time
            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            night_length = int(stop_time.timestamp() - sunset.timestamp())
            seconds_from_sunset = int(now_time.timestamp() -
                                      sunset.timestamp())
            percentage_complete = seconds_from_sunset / night_length
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        x_val, y_val, b_val = color_RGB_to_xy(*color_temperature_to_rgb(temp))
        brightness = self._brightness if self._brightness else b_val
        if self._mode == MODE_XY:
            set_lights_xy(self.hass, self._lights, x_val,
                          y_val, brightness)
            _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%%"
                         " of %s cycle complete at %s", x_val, y_val,
                         brightness, round(
                             percentage_complete * 100), time_state,
                         as_local(now))
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            mired = max(HASS_COLOR_MIN, min(mired, HASS_COLOR_MAX))
            set_lights_temp(self.hass, self._lights, mired, brightness)
            _LOGGER.info("Lights updated to mired:%s brightness:%s, %s%%"
                         " of %s cycle complete at %s", mired, brightness,
                         round(percentage_complete * 100),
                         time_state, as_local(now))
Пример #3
0
    def _status_cb(self, _):
        _LOGGER.debug("Got notification from the lamp")
        from yeelightbt import LampMode
        if not self._dev.color:
            _LOGGER.error("no color available -> device not connected")
            return  # notification not yet there..
        self._brightness = 255 * (int(self._dev.brightness) / 100)
        self._available = self._dev.available
        self._state = self._dev.is_on

        if self._dev.mode == LampMode.White:
            self._ct = int(kelvin_to_mired(self._dev.temperature))
            self._color_temp = self._ct
            # when in white mode, rgb is not set so we calculate it ourselves
            self._rgb = color_temperature_to_rgb(self._dev.temperature)
        else:
            if self._dev.temperature > 0:
                self._ct = int(kelvin_to_mired(self._dev.temperature))
            else:
                self._ct = int(kelvin_to_mired(2400))
            self._rgb = self._dev.color

        _LOGGER.debug("available: %s state: %s rgb: %s ct: %s",
                      self._available, self._state, self._rgb, self._ct)


        self._is_updating = False
        self.schedule_update_ha_state()
Пример #4
0
    def update_sensor(self):
        if self._cl.data is not None:
            self._state = self._cl.data['percent']
            self._hs_color = self._cl.data['hs_color']
            self._attributes = self._cl.data
            min_brightness = 30
            max_brightness = 100
            brightness = int(((max_brightness - min_brightness) *
                              ((100 + self._cl.data['percent']) / 100)) +
                             (min_brightness / 100) * 254)
            ct = color_temperature_kelvin_to_mired(self._cl.data['colortemp'])
            rgb = color_temperature_to_rgb(self._cl.data['colortemp'])
            _LOGGER.debug("RGB values: " + str(rgb))
            xy = color_RGB_to_xy(rgb[0], rgb[1], rgb[2])

            url = "http://" + hue_gateway + "/api/" + key + "/scenes/"
            r = requests.get(url).json()

            scenes = []
            for val in r:
                name = r[val]['name']
                if re.match(r"Circadian", name):
                    scenes.append(val)

            for val in scenes:
                update_scene_lights(val, brightness, xy[0], xy[1], ct)
Пример #5
0
 def set_state(self, **kwargs):
     """Turn the light on."""
     self._set_ramp(**kwargs)
     if ATTR_BRIGHTNESS in kwargs:
         # TODO: is_dimmable test fails for GROUP load types
         # and self._vantage_device.is_dimmable:
         brightness = kwargs[ATTR_BRIGHTNESS]
         self._set_level(brightness)
     if ATTR_RGB_COLOR in kwargs:
         _LOGGER.debug("%s set via ATTR_RGB_COLOR", self)
         self._vantage_device.rgb = kwargs[ATTR_RGB_COLOR]
     elif ATTR_HS_COLOR in kwargs:
         _LOGGER.debug("%s set via ATTR_HS_COLOR", self)
         hs_color = kwargs[ATTR_HS_COLOR]
         rgb = color_hs_to_RGB(*hs_color)
         self._vantage_device.rgb = [*rgb]
     elif ATTR_COLOR_TEMP in kwargs:
         _LOGGER.debug("%s set via ATTR_COLOR_TEMP - %s", self,
                       kwargs[ATTR_COLOR_TEMP])
         # Color temp in HA is in mireds:
         # https://en.wikipedia.org/wiki/Mired
         # M = 1000000/KELVIN_TEMP
         kelvin = int(
             color_temperature_mired_to_kelvin(kwargs[ATTR_COLOR_TEMP]))
         _LOGGER.debug("%s vantage color temp kelvin = %s", self, kelvin)
         if self._vantage_device._dmx_color:
             # do conversion
             rgb = color_temperature_to_rgb(kelvin)
             self._vantage_device.rgb = [*rgb]
         elif self._vantage_device._load_type == "DW":
             rgb = self.color_temperature_to_dw_27k41k(kelvin)
             self._vantage_device.rgb = [*rgb]
         self._vantage_device.color_temp = kelvin
     self.schedule_update_ha_state()
Пример #6
0
    def get_settings(
        self, is_sleep
    ) -> Dict[str, Union[float, Tuple[float, float], Tuple[float, float,
                                                           float]]]:
        """Get all light settings.

        Calculating all values takes <0.5ms.
        """
        percent = self.calc_percent()
        brightness_pct = self.calc_brightness_pct(percent, is_sleep)
        color_temp_kelvin = self.calc_color_temp_kelvin(percent, is_sleep)
        color_temp_mired: float = color_temperature_kelvin_to_mired(
            color_temp_kelvin)
        rgb_color: Tuple[float, float,
                         float] = color_temperature_to_rgb(color_temp_kelvin)
        xy_color: Tuple[float, float] = color_RGB_to_xy(*rgb_color)
        hs_color: Tuple[float, float] = color_xy_to_hs(*xy_color)
        return {
            "brightness_pct": brightness_pct,
            "color_temp_kelvin": color_temp_kelvin,
            "color_temp_mired": color_temp_mired,
            "rgb_color": rgb_color,
            "xy_color": xy_color,
            "hs_color": hs_color,
        }
Пример #7
0
    def flux_update(self, now=None):
        """Update all the lights using flux."""
        if now is None:
            now = dt_now()
        sunset = next_setting(self.hass, SUN).replace(day=now.day,
                                                      month=now.month,
                                                      year=now.year)
        start_time = self.find_start_time(now)
        stop_time = now.replace(hour=self._stop_time.hour,
                                minute=self._stop_time.minute,
                                second=0)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Nightime
            time_state = 'night'
            if now < stop_time and now > start_time:
                now_time = now
            else:
                now_time = stop_time
            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            night_length = int(stop_time.timestamp() - sunset.timestamp())
            seconds_from_sunset = int(now_time.timestamp() -
                                      sunset.timestamp())
            percentage_complete = seconds_from_sunset / night_length
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        x_val, y_val, b_val = color_RGB_to_xy(*color_temperature_to_rgb(temp))
        brightness = self._brightness if self._brightness else b_val
        if self._disable_brightness_adjust:
            brightness = None
        if self._mode == MODE_XY:
            set_lights_xy(self.hass, self._lights, x_val,
                          y_val, brightness)
            _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%%"
                         " of %s cycle complete at %s", x_val, y_val,
                         brightness, round(
                             percentage_complete * 100), time_state, now)
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            mired = max(HASS_COLOR_MIN, min(mired, HASS_COLOR_MAX))
            set_lights_temp(self.hass, self._lights, mired, brightness)
            _LOGGER.info("Lights updated to mired:%s brightness:%s, %s%%"
                         " of %s cycle complete at %s", mired, brightness,
                         round(percentage_complete * 100), time_state, now)
Пример #8
0
    def test_should_return_pure_white_at_6600(self):
        """
        Function should return red=255, blue=255, green=255 when given 6600K.

        6600K is considered "pure white" light.
        This is just a rough estimate because the formula itself is a "best
        guess" approach.
        """
        rgb = color_util.color_temperature_to_rgb(6600)
        self.assertEqual((255, 255, 255), rgb)
Пример #9
0
def test_should_return_pure_white_at_6600():
    """
    Function should return red=255, blue=255, green=255 when given 6600K.

    6600K is considered "pure white" light.
    This is just a rough estimate because the formula itself is a "best
    guess" approach.
    """
    rgb = color_util.color_temperature_to_rgb(6600)
    assert (255, 255, 255) == rgb
Пример #10
0
 async def _update_attrs(self):
     """Update Adaptive Values."""
     # Setting all values because this method takes <0.5ms to execute.
     self._percent = self._calc_percent()
     self._brightness = self._calc_brightness()
     self._color_temp_kelvin = self._calc_color_temp_kelvin()
     self._color_temp_mired = color_temperature_kelvin_to_mired(
         self._color_temp_kelvin)
     self._rgb_color = color_temperature_to_rgb(self._color_temp_kelvin)
     self._xy_color = color_RGB_to_xy(*self._rgb_color)
     self._hs_color = color_xy_to_hs(*self._xy_color)
     self.async_write_ha_state()
     _LOGGER.debug("'_update_attrs' called for %s", self._name)
Пример #11
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
        if self._rgbw and any(x in (ATTR_COLOR_TEMP, ATTR_HS_COLOR)
                              for x in kwargs):
            data[ATTR_COLOR_PRIMARY] = color_util.color_rgb_to_rgbw(
                *data[ATTR_COLOR_PRIMARY])

        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)

        except WLEDError:
            _LOGGER.error("An error occurred while turning on WLED light.")
            self._available = False
        self.async_schedule_update_ha_state()
Пример #12
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:
            # 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, )

        await self.coordinator.wled.light(**data)
Пример #13
0
    async def async_turn_on(self, **kwargs: Any) -> None:
        options = []
        if kwargs.get(ATTR_BRIGHTNESS) is not None:
            _LOGGER.debug("Setting brightness")
            brightness = round((kwargs.get(ATTR_BRIGHTNESS) / 255) * 100)

            options.append(
                create_pid_pair(PropertyIDs.BRIGHTNESS, str(brightness)))

            _LOGGER.debug("Setting brightness to %s" % brightness)
            _LOGGER.debug("Options: %s" % options)

            self._bulb.brightness = brightness
        if kwargs.get(ATTR_COLOR_TEMP) is not None:
            _LOGGER.debug("Setting color temp")
            color_temp = color_util.color_temperature_mired_to_kelvin(
                kwargs.get(ATTR_COLOR_TEMP))

            options.append(
                create_pid_pair(PropertyIDs.COLOR_TEMP, str(color_temp)))

            self._bulb.color_temp = color_temp
            self._bulb.color = color_util.color_rgb_to_hex(
                *color_util.color_temperature_to_rgb(color_temp))
        if (kwargs.get(ATTR_HS_COLOR) is not None
                and (self._device_type is DeviceTypes.MESH_LIGHT
                     or self._device_type is DeviceTypes.LIGHTSTRIP)):
            _LOGGER.debug("Setting color")
            color = color_util.color_rgb_to_hex(*color_util.color_hs_to_RGB(
                *kwargs.get(ATTR_HS_COLOR)))

            options.append(create_pid_pair(PropertyIDs.COLOR, str(color)))

            self._bulb.color = color

        _LOGGER.debug("Turning on light")
        loop = asyncio.get_event_loop()
        loop.create_task(self._bulb_service.turn_on(self._bulb, options))

        self._bulb.on = True
        self._just_updated = True
        self.async_schedule_update_ha_state()
Пример #14
0
    def _get_rgb_from_properties(self):
        rgb = self._properties.get("rgb", None)
        color_mode = self._properties.get("color_mode", None)
        if not rgb or not color_mode:
            return rgb

        color_mode = int(color_mode)
        if color_mode == 2:  # color temperature
            return color_temperature_to_rgb(self.color_temp)
        if color_mode == 3:  # hsv
            hue = self._properties.get("hue")
            sat = self._properties.get("sat")
            val = self._properties.get("bright")
            return colorsys.hsv_to_rgb(hue, sat, val)

        rgb = int(rgb)
        blue = rgb & 0xff
        green = (rgb >> 8) & 0xff
        red = (rgb >> 16) & 0xff

        return red, green, blue
Пример #15
0
    def _get_rgb_from_properties(self):
        rgb = self._properties.get('rgb', None)
        color_mode = self._properties.get('color_mode', None)
        if not rgb or not color_mode:
            return rgb

        color_mode = int(color_mode)
        if color_mode == 2:  # color temperature
            return color_temperature_to_rgb(self.color_temp)
        if color_mode == 3:  # hsv
            hue = int(self._properties.get('hue'))
            sat = int(self._properties.get('sat'))
            val = int(self._properties.get('bright'))
            return hsv_to_rgb((hue, sat, val))

        rgb = int(rgb)
        blue = rgb & 0xff
        green = (rgb >> 8) & 0xff
        red = (rgb >> 16) & 0xff

        return red, green, blue
Пример #16
0
    def _get_rgb_from_properties(self):
        rgb = self._properties.get("rgb", None)
        color_mode = self._properties.get("color_mode", None)
        if not rgb or not color_mode:
            return rgb

        color_mode = int(color_mode)
        if color_mode == 2:  # color temperature
            return color_temperature_to_rgb(self.color_temp)
        if color_mode == 3:  # hsv
            hue = self._properties.get("hue")
            sat = self._properties.get("sat")
            val = self._properties.get("bright")
            return colorsys.hsv_to_rgb(hue, sat, val)

        rgb = int(rgb)
        blue = rgb & 0xff
        green = (rgb >> 8) & 0xff
        red = (rgb >> 16) & 0xff

        return red, green, blue
Пример #17
0
    def _get_rgb_from_properties(self):
        rgb = self._properties.get('rgb', None)
        color_mode = self._properties.get('color_mode', None)
        if not rgb or not color_mode:
            return rgb

        color_mode = int(color_mode)
        if color_mode == 2:  # color temperature
            return color_temperature_to_rgb(self.color_temp)
        if color_mode == 3:  # hsv
            hue = int(self._properties.get('hue'))
            sat = int(self._properties.get('sat'))
            val = int(self._properties.get('bright'))
            return hsv_to_rgb((hue, sat, val))

        rgb = int(rgb)
        blue = rgb & 0xff
        green = (rgb >> 8) & 0xff
        red = (rgb >> 16) & 0xff

        return red, green, blue
Пример #18
0
    async def async_flux_update(self, utcnow=None):
        """Update all the lights using flux."""
        if utcnow is None:
            utcnow = dt_utcnow()

        now = as_local(utcnow)

        sunset = get_astral_event_date(self.hass, SUN_EVENT_SUNSET, now.date())
        start_time = self.find_start_time(now)
        stop_time = self.find_stop_time(now)

        if stop_time <= start_time:
            # stop_time does not happen in the same day as start_time
            if start_time < now:
                # stop time is tomorrow
                stop_time += datetime.timedelta(days=1)
        elif now < start_time:
            # stop_time was yesterday since the new start_time is not reached
            stop_time -= datetime.timedelta(days=1)

        if start_time < now < sunset:
            # Daytime
            time_state = "day"
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Night time
            time_state = "night"

            if now < stop_time:
                if stop_time < start_time and stop_time.day == sunset.day:
                    # we need to use yesterday's sunset time
                    sunset_time = sunset - datetime.timedelta(days=1)
                else:
                    sunset_time = sunset

                night_length = int(stop_time.timestamp() -
                                   sunset_time.timestamp())
                seconds_from_sunset = int(now.timestamp() -
                                          sunset_time.timestamp())
                percentage_complete = seconds_from_sunset / night_length
            else:
                percentage_complete = 1

            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        rgb = color_temperature_to_rgb(temp)
        x_val, y_val, b_val = color_RGB_to_xy_brightness(*rgb)
        brightness = self._brightness if self._brightness else b_val
        if self._disable_brightness_adjust:
            brightness = None
        if self._mode == MODE_XY:
            await async_set_lights_xy(self.hass, self._lights, x_val, y_val,
                                      brightness, self._transition)
            _LOGGER.debug(
                "Lights updated to x:%s y:%s brightness:%s, %s%% "
                "of %s cycle complete at %s",
                x_val,
                y_val,
                brightness,
                round(percentage_complete * 100),
                time_state,
                now,
            )
        elif self._mode == MODE_RGB:
            await async_set_lights_rgb(self.hass, self._lights, rgb,
                                       self._transition)
            _LOGGER.debug(
                "Lights updated to rgb:%s, %s%% of %s cycle complete at %s",
                rgb,
                round(percentage_complete * 100),
                time_state,
                now,
            )
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            await async_set_lights_temp(self.hass, self._lights, mired,
                                        brightness, self._transition)
            _LOGGER.debug(
                "Lights updated to mired:%s brightness:%s, %s%% "
                "of %s cycle complete at %s",
                mired,
                brightness,
                round(percentage_complete * 100),
                time_state,
                now,
            )
Пример #19
0
def test_color_above_6600_should_have_more_blue_than_red_or_green():
    """Function should return a higher blue value for blue-ish light."""
    rgb = color_util.color_temperature_to_rgb(6700)
    assert rgb[2] > rgb[1]
    assert rgb[2] > rgb[0]
Пример #20
0
def test_color_below_6600_should_have_more_red_than_blue_or_green():
    """Function should return a higher red value for red-ish light."""
    rgb = color_util.color_temperature_to_rgb(6500)
    assert rgb[0] > rgb[1]
    assert rgb[0] > rgb[2]
Пример #21
0
def test_returns_same_value_for_any_two_temperatures_above_40000():
    """Function should return same value for 40001K and 999999K."""
    rgb_1 = color_util.color_temperature_to_rgb(40001)
    rgb_2 = color_util.color_temperature_to_rgb(999999)
    assert rgb_1 == rgb_2
Пример #22
0
    def flux_force_update(self, call=None, entity=None):
        """Forced update of given or all the lights using flux."""
        now = dt_now()

        if call is None:
            if entity is None:
                entity_id = self._lights
            else:
                entity_id = entity
        else:
            entity_id = call.data.get("entity_id", self._lights)

        _LOGGER.info("Flux forced update for %s",
            entity_id)


        sunset = get_astral_event_date(self.hass, 'sunset', now.date())
        start_time = self.find_start_time(now)
        stop_time = now.replace(
            hour=self._stop_time.hour, minute=self._stop_time.minute,
            second=0)

        if stop_time <= start_time:
            # stop_time does not happen in the same day as start_time
            if start_time < now:
                # stop time is tomorrow
                stop_time += datetime.timedelta(days=1)
        elif now < start_time:
            # stop_time was yesterday since the new start_time is not reached
            stop_time -= datetime.timedelta(days=1)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Nightime
            time_state = 'night'

            if now < stop_time:
                if stop_time < start_time and stop_time.day == sunset.day:
                    # we need to use yesterday's sunset time
                    sunset_time = sunset - datetime.timedelta(days=1)
                else:
                    sunset_time = sunset

                # pylint: disable=no-member
                night_length = int(stop_time.timestamp() -
                                   sunset_time.timestamp())
                seconds_from_sunset = int(now.timestamp() -
                                          sunset_time.timestamp())
                percentage_complete = seconds_from_sunset / night_length
            else:
                percentage_complete = 1

            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        rgb = color_temperature_to_rgb(temp)
        x_val, y_val, b_val = color_RGB_to_xy(*rgb)
        brightness = self._brightness if self._brightness else b_val
        
        if self._mode == MODE_XY:
            _LOGGER.debug("Trying to force update of %s to XY %s, %s", entity_id, x_val, y_val)
            force_light_xy(self.hass, entity_id, x_val,
                          y_val, brightness)
            new_color_xy = set_lights_xy(self.hass, self._lights, x_val,
                              y_val, brightness, self._transition, self._last_color)
            _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%% "
                         "of %s cycle complete at %s", x_val, y_val,
                         brightness, round(
                             percentage_complete * 100), time_state, now)
            self._last_color = new_color_xy
        elif self._mode == MODE_RGB:
            force_light_rgb(self.hass, entity_id, rgb)
            new_color_rgb = set_lights_rgb(self.hass, self._lights, rgb, self._transition, self._last_color)
            _LOGGER.info("Lights updated to rgb:%s, %s%% "
                         "of %s cycle complete at %s", rgb,
                         round(percentage_complete * 100), time_state, now)
            self._last_color = new_color_rgb
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            _LOGGER.debug("Trying to force update of %s to mired %s", entity_id, mired)
            force_light_temp(self.hass, entity_id, mired, brightness)
            new_colortemp = set_lights_temp(self.hass, self._lights, mired, brightness,
                            self._transition, self._last_color)
            _LOGGER.info("Lights updated from %s to mired:%s brightness:%s, %s%% "
                         "of %s cycle complete at %s", self._last_color, mired, brightness,
                         round(percentage_complete * 100), time_state, now)
            self._last_color = new_colortemp
Пример #23
0
    def flux_update(self, now=None):
        """Update all the lights using flux."""
        if now is None:
            now = dt_now()

        sunset = get_astral_event_date(self.hass, 'sunset', now.date())
        start_time = self.find_start_time(now)
        stop_time = self.find_stop_time(now)

        if stop_time <= start_time:
            # stop_time does not happen in the same day as start_time
            if start_time < now:
                # stop time is tomorrow
                stop_time += datetime.timedelta(days=1)
        elif now < start_time:
            # stop_time was yesterday since the new start_time is not reached
            stop_time -= datetime.timedelta(days=1)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Night time
            time_state = 'night'

            if now < stop_time:
                if stop_time < start_time and stop_time.day == sunset.day:
                    # we need to use yesterday's sunset time
                    sunset_time = sunset - datetime.timedelta(days=1)
                else:
                    sunset_time = sunset

                # pylint: disable=no-member
                night_length = int(stop_time.timestamp() -
                                   sunset_time.timestamp())
                seconds_from_sunset = int(now.timestamp() -
                                          sunset_time.timestamp())
                percentage_complete = seconds_from_sunset / night_length
            else:
                percentage_complete = 1

            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        rgb = color_temperature_to_rgb(temp)
        x_val, y_val, b_val = color_RGB_to_xy_brightness(*rgb)
        brightness = self._brightness if self._brightness else b_val
        if self._disable_brightness_adjust:
            brightness = None
        if self._mode == MODE_XY:
            set_lights_xy(self.hass, self._lights, x_val,
                          y_val, brightness, self._transition)
            _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%% "
                         "of %s cycle complete at %s", x_val, y_val,
                         brightness, round(
                             percentage_complete * 100), time_state, now)
        elif self._mode == MODE_RGB:
            set_lights_rgb(self.hass, self._lights, rgb, self._transition)
            _LOGGER.info("Lights updated to rgb:%s, %s%% "
                         "of %s cycle complete at %s", rgb,
                         round(percentage_complete * 100), time_state, now)
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            set_lights_temp(self.hass, self._lights, mired, brightness,
                            self._transition)
            _LOGGER.info("Lights updated to mired:%s brightness:%s, %s%% "
                         "of %s cycle complete at %s", mired, brightness,
                         round(percentage_complete * 100), time_state, now)
Пример #24
0
def test_returns_same_value_for_any_two_temperatures_below_1000():
    """Function should return same value for 999 Kelvin and 0 Kelvin."""
    rgb_1 = color_util.color_temperature_to_rgb(999)
    rgb_2 = color_util.color_temperature_to_rgb(0)
    assert rgb_1 == rgb_2
Пример #25
0
 def test_color_below_6600_should_have_more_red_than_blue_or_green(self):
     """Function should return a higher red value for red-ish light."""
     rgb = color_util.color_temperature_to_rgb(6500)
     self.assertGreater(rgb[0], rgb[1])
     self.assertGreater(rgb[0], rgb[2])
Пример #26
0
 def calc_rgb(self):
     return color_temperature_to_rgb(self.data['colortemp'])
Пример #27
0
 def calc_rgb(self):
     return color_temperature_to_rgb(self._color_temperature)
Пример #28
0
 def test_color_above_6600_should_have_more_blue_than_red_or_green(self):
     """Function should return a higher blue value for blue-ish light."""
     rgb = color_util.color_temperature_to_rgb(6700)
     self.assertGreater(rgb[2], rgb[1])
     self.assertGreater(rgb[2], rgb[0])
Пример #29
0
 def test_returns_same_value_for_any_two_temperatures_above_40000(self):
     """Function should return same value for 40001K and 999999K."""
     rgb_1 = color_util.color_temperature_to_rgb(40001)
     rgb_2 = color_util.color_temperature_to_rgb(999999)
     self.assertEqual(rgb_1, rgb_2)
Пример #30
0
 def test_returns_same_value_for_any_two_temperatures_below_1000(self):
     """Function should return same value for 999 Kelvin and 0 Kelvin."""
     rgb_1 = color_util.color_temperature_to_rgb(999)
     rgb_2 = color_util.color_temperature_to_rgb(0)
     self.assertEqual(rgb_1, rgb_2)
Пример #31
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()
Пример #32
0
def ct_to_rgb(temp):
    """Convert color temperature (mireds) to RGB."""
    colorlist = list(
        color_temperature_to_rgb(color_temperature_mired_to_kelvin(temp)))
    return [int(val) for val in colorlist]
Пример #33
0
    def flux_update(self, now=None):
        """Update all the lights using flux."""
        if now is None:
            now = dt_now()

        sunset = get_astral_event_date(self.hass, 'sunset', now.date())
        start_time = self.find_start_time(now)
        stop_time = now.replace(hour=self._stop_time.hour,
                                minute=self._stop_time.minute,
                                second=0)

        if stop_time <= start_time:
            # stop_time does not happen in the same day as start_time
            if start_time < now:
                # stop time is tomorrow
                stop_time += datetime.timedelta(days=1)
        elif now < start_time:
            # stop_time was yesterday since the new start_time is not reached
            stop_time -= datetime.timedelta(days=1)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Nightime
            time_state = 'night'

            if now < stop_time:
                if stop_time < start_time and stop_time.day == sunset.day:
                    # we need to use yesterday's sunset time
                    sunset_time = sunset - datetime.timedelta(days=1)
                else:
                    sunset_time = sunset

                # pylint: disable=no-member
                night_length = int(stop_time.timestamp() -
                                   sunset_time.timestamp())
                seconds_from_sunset = int(now.timestamp() -
                                          sunset_time.timestamp())
                percentage_complete = seconds_from_sunset / night_length
            else:
                percentage_complete = 1

            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        rgb = color_temperature_to_rgb(temp)
        x_val, y_val, b_val = color_RGB_to_xy(*rgb)
        brightness = self._brightness if self._brightness else b_val
        if self._disable_brightness_adjust:
            brightness = None
        if self._mode == MODE_XY:
            set_lights_xy(self.hass, self._lights, x_val, y_val, brightness)
            _LOGGER.info(
                "Lights updated to x:%s y:%s brightness:%s, %s%% "
                "of %s cycle complete at %s", x_val, y_val, brightness,
                round(percentage_complete * 100), time_state, now)
        elif self._mode == MODE_RGB:
            set_lights_rgb(self.hass, self._lights, rgb)
            _LOGGER.info(
                "Lights updated to rgb:%s, %s%% "
                "of %s cycle complete at %s", rgb,
                round(percentage_complete * 100), time_state, now)
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            set_lights_temp(self.hass, self._lights, mired, brightness)
            _LOGGER.info(
                "Lights updated to mired:%s brightness:%s, %s%% "
                "of %s cycle complete at %s", mired, brightness,
                round(percentage_complete * 100), time_state, now)
Пример #34
0
    async def async_turn_on(self, **kwargs: Any) -> None:
        options = []

        if kwargs.get(ATTR_BRIGHTNESS) is not None:
            brightness = round((kwargs.get(ATTR_BRIGHTNESS) / 255) * 100)

            options.append(create_pid_pair(PropertyIDs.BRIGHTNESS, str(brightness)))

            _LOGGER.debug("Setting brightness to %s" % brightness)
            _LOGGER.debug("Options: %s" % options)

            self._bulb.brightness = brightness

        if self._bulb.sun_match:  # Turn off sun match if we're changing anything other than brightness
            if any([kwargs.get(ATTR_COLOR_TEMP, kwargs.get(ATTR_HS_COLOR))]):
                options.append(create_pid_pair(PropertyIDs.SUN_MATCH, str(0)))
                self._bulb.sun_match = False
                _LOGGER.debug("Turning off sun match")

        if kwargs.get(ATTR_COLOR_TEMP) is not None:
            _LOGGER.debug("Setting color temp")
            color_temp = color_util.color_temperature_mired_to_kelvin(kwargs.get(ATTR_COLOR_TEMP))

            options.append(create_pid_pair(PropertyIDs.COLOR_TEMP, str(color_temp)))

            if self._device_type in [DeviceTypes.MESH_LIGHT, DeviceTypes.LIGHTSTRIP]:
                options.append(create_pid_pair(PropertyIDs.COLOR_MODE, str(2)))  # Put bulb in White Mode
                self._bulb.color_mode = '2'

            self._bulb.color_temp = color_temp
            self._bulb.color = color_util.color_rgb_to_hex(*color_util.color_temperature_to_rgb(color_temp))

        if (
            kwargs.get(ATTR_HS_COLOR) is not None
            and (
                self._device_type is DeviceTypes.MESH_LIGHT
                or self._device_type is DeviceTypes.LIGHTSTRIP
            )
        ):
            _LOGGER.debug("Setting color")
            color = color_util.color_rgb_to_hex(*color_util.color_hs_to_RGB(*kwargs.get(ATTR_HS_COLOR)))

            options.extend(
                [
                    create_pid_pair(PropertyIDs.COLOR, str(color)),
                    create_pid_pair(PropertyIDs.COLOR_MODE, str(1))  # Put bulb in Color Mode
                ]
            )

            self._bulb.color = color
            self._bulb.color_mode = '1'

        if (
            kwargs.get(ATTR_EFFECT) == EFFECT_MUSIC_MODE
            and self._device_type is DeviceTypes.LIGHTSTRIP
        ):
            _LOGGER.debug("Setting Music Mode")
            options.append(create_pid_pair(PropertyIDs.COLOR_MODE, str(3)))
            self._bulb.color_mode = '3'

        if kwargs.get(ATTR_EFFECT) == EFFECT_SUN_MATCH:
            _LOGGER.debug("Setting Sun Match")
            options.append(create_pid_pair(PropertyIDs.SUN_MATCH, str(1)))
            self._bulb.sun_match = True

        _LOGGER.debug("Turning on light")
        self._local_control = self._config_entry.options.get(BULB_LOCAL_CONTROL)
        loop = asyncio.get_event_loop()
        loop.create_task(self._bulb_service.turn_on(self._bulb, self._local_control, options))

        self._bulb.on = True
        self._just_updated = True
        self.async_schedule_update_ha_state()
Пример #35
0
 def calc_rgb(self):
     if self.is_sleep():
         _LOGGER.debug(self._name + " in Sleep mode")
         return color_temperature_to_rgb(self._sleep_colortemp)
     else:
         return color_temperature_to_rgb(self._cl.data["colortemp"])