示例#1
0
def query_response_light(
        entity: Entity, config: Config, units: UnitSystem) -> dict:
    """Convert a light entity to a QUERY response."""
    response = {}  # type: Dict[str, Any]

    brightness = entity.attributes.get(light.ATTR_BRIGHTNESS)
    if brightness is not None:
        response['brightness'] = int(100 * (brightness / 255))

    supported_features = entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
    if supported_features & \
       (light.SUPPORT_COLOR_TEMP | light.SUPPORT_RGB_COLOR):
        response['color'] = {}

        if entity.attributes.get(light.ATTR_COLOR_TEMP) is not None:
            response['color']['temperature'] = \
                int(round(color.color_temperature_mired_to_kelvin(
                    entity.attributes.get(light.ATTR_COLOR_TEMP))))

        if entity.attributes.get(light.ATTR_COLOR_NAME) is not None:
            response['color']['name'] = \
                entity.attributes.get(light.ATTR_COLOR_NAME)

        if entity.attributes.get(light.ATTR_RGB_COLOR) is not None:
            color_rgb = entity.attributes.get(light.ATTR_RGB_COLOR)
            if color_rgb is not None:
                response['color']['spectrumRGB'] = \
                    int(color.color_rgb_to_hex(
                        color_rgb[0], color_rgb[1], color_rgb[2]), 16)

    return response
示例#2
0
    def query_attributes(self):
        """Return color spectrum query attributes."""
        response = {}

        color_hs = self.state.attributes.get(light.ATTR_HS_COLOR)
        if color_hs is not None:
            response['color'] = {
                'spectrumRGB': int(color_util.color_rgb_to_hex(
                    *color_util.color_hs_to_RGB(*color_hs)), 16),
            }

        return response
示例#3
0
    def query_attributes(self):
        """Return color spectrum query attributes."""
        response = {}

        color_hs = self.state.attributes.get(light.ATTR_HS_COLOR)
        if color_hs is not None:
            response['color'] = {
                'spectrumRGB': int(color_util.color_rgb_to_hex(
                    *color_util.color_hs_to_RGB(*color_hs)), 16),
            }

        return response
示例#4
0
    def query_attributes(self):
        """Return color spectrum query attributes."""
        response = {}

        # No need to handle XY color because light component will always
        # convert XY to RGB if possible (which is when brightness is available)
        color_rgb = self.state.attributes.get(light.ATTR_RGB_COLOR)
        if color_rgb is not None:
            response['color'] = {
                'spectrumRGB': int(color_util.color_rgb_to_hex(
                    color_rgb[0], color_rgb[1], color_rgb[2]), 16),
            }

        return response
示例#5
0
    def query_attributes(self):
        """Return color spectrum query attributes."""
        response = {}

        # No need to handle XY color because light component will always
        # convert XY to RGB if possible (which is when brightness is available)
        color_rgb = self.state.attributes.get(light.ATTR_RGB_COLOR)
        if color_rgb is not None:
            response['color'] = {
                'spectrumRGB':
                int(
                    color_util.color_rgb_to_hex(color_rgb[0], color_rgb[1],
                                                color_rgb[2]), 16),
            }

        return response
示例#6
0
    def turn_on(self, **kwargs) -> None:
        """Turn the bulb on."""
        self._state = True
        if self._setting == 'up':
            requests.get(self._host + "/cgi-bin/wakeup?silent=1")

        elif self._setting == 'earLeft':
            self._brightness = kwargs.get(ATTR_BRIGHTNESS)
            otherBrightness = self._hass.states.get(
                'light.' + self._name + "_earRight").attributes['brightness']
            requests.get(self._host + "/cgi-bin/ears?left=" +
                         str(round(self._brightness / 255 * 16)) + "&right=" +
                         str(round(otherBrightness / 255 * 16)) + "&noreset=1")

        elif self._setting == 'earRight':
            self._brightness = kwargs.get(ATTR_BRIGHTNESS)
            otherBrightness = self._hass.states.get(
                'light.' + self._name + "_earLeft").attributes['brightness']
            requests.get(self._host + "/cgi-bin/ears?left=" +
                         str(round(otherBrightness / 255 * 16)) + "&right=" +
                         str(round(self._brightness / 255 * 16)) +
                         "&noreset=1")

        elif self._setting == 'ledInfo':
            brightness = kwargs.get(ATTR_BRIGHTNESS)
            if brightness is not None:
                self._brightness = brightness

            colorAttr = kwargs.get(ATTR_HS_COLOR)
            if colorAttr is not None:
                self._color = colorAttr

            colorRGB = color.color_hs_to_RGB(self._color[0], self._color[1])
            colorData = color.color_rgb_to_hex(colorRGB[0], colorRGB[1],
                                               colorRGB[2])

            if self._brightness < 15:
                requests.get(self._host + "/cgi-bin/leds?color=" +
                             str(colorData))
            else:
                requests.get(self._host + "/cgi-bin/leds?pulse=1&color=" +
                             str(colorData) + "&speed=" +
                             str(round(self._brightness / 255 * 2000)) +
                             "&color2=000000")
        else:
            pass
示例#7
0
    async def async_turn_on(self, **kwargs):
        """Turn the light on."""

        rgbw = kwargs.get(ATTR_RGBW_COLOR)
        brightness = kwargs.get(ATTR_BRIGHTNESS)

        feature = self._feature
        value = feature.sensible_on_value

        if brightness is not None:
            value = feature.apply_brightness(value, brightness)

        if rgbw is not None:
            value = feature.apply_white(value, rgbw[3])
            value = feature.apply_color(value, color_rgb_to_hex(*rgbw[0:3]))

        try:
            await self._feature.async_on(value)
        except BadOnValueError as ex:
            _LOGGER.error("Turning on '%s' failed: Bad value %s (%s)",
                          self.name, value, ex)
示例#8
0
    def turn_on(self, **kwargs):
        """
        Instruct the light to turn on.

        After adding "self._light_data.hexcolor is not None"
        for ATTR_RGB_COLOR, this also supports Philips Hue bulbs.
        """
        if ATTR_BRIGHTNESS in kwargs:
            self._api(self._light_control.set_dimmer(kwargs[ATTR_BRIGHTNESS]))
        else:
            self._api(self._light_control.set_state(True))

        if ATTR_RGB_COLOR in kwargs and self._light_data.hex_color is not None:
            self._api(self._light.light_control.set_hex_color(
                color_util.color_rgb_to_hex(*kwargs[ATTR_RGB_COLOR])))

        elif ATTR_COLOR_TEMP in kwargs and \
                self._light_data.hex_color is not None and self._ok_temps:
            kelvin = color_util.color_temperature_mired_to_kelvin(
                kwargs[ATTR_COLOR_TEMP])
            self._api(self._light_control.set_kelvin_color(kelvin))
示例#9
0
    def turn_on(self, **kwargs):
        """
        Instruct the light to turn on.

        After adding "self._light_data.hexcolor is not None"
        for ATTR_RGB_COLOR, this also supports Philips Hue bulbs.
        """
        if ATTR_BRIGHTNESS in kwargs:
            self._light_control.set_dimmer(kwargs[ATTR_BRIGHTNESS])
        else:
            self._light_control.set_state(True)

        if ATTR_RGB_COLOR in kwargs and self._light_data.hex_color is not None:
            self._light.light_control.set_hex_color(
                color_util.color_rgb_to_hex(*kwargs[ATTR_RGB_COLOR]))

        elif ATTR_COLOR_TEMP in kwargs and \
                self._light_data.hex_color is not None and self._ok_temps:
            kelvin = color_util.color_temperature_mired_to_kelvin(
                kwargs[ATTR_COLOR_TEMP])
            # find closest allowed kelvin temp from user input
            kelvin = min(self._ok_temps.keys(), key=lambda x: abs(x - kelvin))
            self._light_control.set_hex_color(self._ok_temps[kelvin])
示例#10
0
文件: light.py 项目: testventure/wyze
    def turn_on(self, **kwargs: Any) -> None:
        _LOGGER.debug(kwargs)
        pids = []
        if kwargs.get(ATTR_BRIGHTNESS) is not None:
            _LOGGER.debug("Setting brightness")
            self._brightness = self.translate(kwargs.get(ATTR_BRIGHTNESS), 1,
                                              255, 1, 100)

            pids.append(
                self._client.create_pid_pair(PropertyIDs.BRIGHTNESS,
                                             str(int(self._brightness))))
        if kwargs.get(ATTR_COLOR_TEMP) is not None:
            _LOGGER.debug("Setting color temp")
            self._color_temp = self.translate(kwargs.get(ATTR_COLOR_TEMP), 500,
                                              140, 2700, 6500)

            pids.append(
                self._client.create_pid_pair(PropertyIDs.COLOR_TEMP,
                                             str(int(self._color_temp))))
        if kwargs.get(ATTR_HS_COLOR) is not None:
            _LOGGER.debug("Setting color")
            self._color = color_util.color_rgb_to_hex(
                *color_util.color_hs_to_RGB(*kwargs.get(ATTR_HS_COLOR)))

            pids.append(
                self._client.create_pid_pair(PropertyIDs.COLOR, self._color))

        _LOGGER.debug("Turning on light")
        try:
            self._client.turn_on(self._device, pids)
        except AccessTokenError:
            self._client.reauthenticate()
            self._client.turn_on(self._device, pids)

        self._on = True
        self._just_updated = True
示例#11
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()
示例#12
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()
示例#13
0
文件: test_color.py 项目: rikroe/core
def test_color_rgb_to_hex():
    """Test color_rgb_to_hex."""
    assert color_util.color_rgb_to_hex(255, 255, 255) == "ffffff"
    assert color_util.color_rgb_to_hex(0, 0, 0) == "000000"
    assert color_util.color_rgb_to_hex(51, 153, 255) == "3399ff"
    assert color_util.color_rgb_to_hex(255, 67.9204190, 0) == "ff4400"
示例#14
0
 def hs_to_rgbhex(self):
     rgb = color_util.color_hs_to_RGB(*self._hs)
     rgbhex = color_util.color_rgb_to_hex(*rgb)
     return rgbhex
示例#15
0
def query_device(entity: Entity, config: Config, units: UnitSystem) -> dict:
    """Take an entity and return a properly formatted device object."""
    def celsius(deg: Optional[float]) -> Optional[float]:
        """Convert a float to Celsius and rounds to one decimal place."""
        if deg is None:
            return None
        return round(METRIC_SYSTEM.temperature(deg, units.temperature_unit), 1)

    if entity.domain == sensor.DOMAIN:
        entity_config = config.entity_config.get(entity.entity_id, {})
        google_domain = entity_config.get(CONF_TYPE)

        if google_domain == climate.DOMAIN:
            # check if we have a string value to convert it to number
            value = entity.state
            if isinstance(entity.state, str):
                try:
                    value = float(value)
                except ValueError:
                    value = None

            if value is None:
                raise SmartHomeError(
                    ERROR_NOT_SUPPORTED,
                    "Invalid value {} for the climate sensor"
                    .format(entity.state)
                )

            # detect if we report temperature or humidity
            unit_of_measurement = entity.attributes.get(
                ATTR_UNIT_OF_MEASUREMENT,
                units.temperature_unit
            )
            if unit_of_measurement in [TEMP_FAHRENHEIT, TEMP_CELSIUS]:
                value = celsius(value)
                attr = 'thermostatTemperatureAmbient'
            elif unit_of_measurement == '%':
                attr = 'thermostatHumidityAmbient'
            else:
                raise SmartHomeError(
                    ERROR_NOT_SUPPORTED,
                    "Unit {} is not supported by the climate sensor"
                    .format(unit_of_measurement)
                )

            return {attr: value}

        raise SmartHomeError(
            ERROR_NOT_SUPPORTED,
            "Sensor type {} is not supported".format(google_domain)
        )

    if entity.domain == climate.DOMAIN:
        mode = entity.attributes.get(climate.ATTR_OPERATION_MODE).lower()
        if mode not in CLIMATE_SUPPORTED_MODES:
            mode = 'heat'
        response = {
            'thermostatMode': mode,
            'thermostatTemperatureSetpoint':
            celsius(entity.attributes.get(climate.ATTR_TEMPERATURE)),
            'thermostatTemperatureAmbient':
            celsius(entity.attributes.get(climate.ATTR_CURRENT_TEMPERATURE)),
            'thermostatTemperatureSetpointHigh':
            celsius(entity.attributes.get(climate.ATTR_TARGET_TEMP_HIGH)),
            'thermostatTemperatureSetpointLow':
            celsius(entity.attributes.get(climate.ATTR_TARGET_TEMP_LOW)),
            'thermostatHumidityAmbient':
            entity.attributes.get(climate.ATTR_CURRENT_HUMIDITY),
        }
        return {k: v for k, v in response.items() if v is not None}

    final_state = entity.state != STATE_OFF
    final_brightness = entity.attributes.get(light.ATTR_BRIGHTNESS, 255
                                             if final_state else 0)

    if entity.domain == media_player.DOMAIN:
        level = entity.attributes.get(media_player.ATTR_MEDIA_VOLUME_LEVEL, 1.0
                                      if final_state else 0.0)
        # Convert 0.0-1.0 to 0-255
        final_brightness = round(min(1.0, level) * 255)

    if final_brightness is None:
        final_brightness = 255 if final_state else 0

    final_brightness = 100 * (final_brightness / 255)

    query_response = {
        "on": final_state,
        "online": True,
        "brightness": int(final_brightness)
    }

    supported_features = entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
    if supported_features & \
       (light.SUPPORT_COLOR_TEMP | light.SUPPORT_RGB_COLOR):
        query_response["color"] = {}

        if entity.attributes.get(light.ATTR_COLOR_TEMP) is not None:
            query_response["color"]["temperature"] = \
                int(round(color.color_temperature_mired_to_kelvin(
                    entity.attributes.get(light.ATTR_COLOR_TEMP))))

        if entity.attributes.get(light.ATTR_COLOR_NAME) is not None:
            query_response["color"]["name"] = \
                entity.attributes.get(light.ATTR_COLOR_NAME)

        if entity.attributes.get(light.ATTR_RGB_COLOR) is not None:
            color_rgb = entity.attributes.get(light.ATTR_RGB_COLOR)
            if color_rgb is not None:
                query_response["color"]["spectrumRGB"] = \
                    int(color.color_rgb_to_hex(
                        color_rgb[0], color_rgb[1], color_rgb[2]), 16)

    return query_response
示例#16
0
 def test_color_rgb_to_hex(self):
     """Test color_rgb_to_hex."""
     assert color_util.color_rgb_to_hex(255, 255, 255) == 'ffffff'
     assert color_util.color_rgb_to_hex(0, 0, 0) == '000000'
     assert color_util.color_rgb_to_hex(51, 153, 255) == '3399ff'
     assert color_util.color_rgb_to_hex(255, 67.9204190, 0) == 'ff4400'
示例#17
0
 def test_color_rgb_to_hex(self):
     """Test color_rgb_to_hex."""
     assert color_util.color_rgb_to_hex(255, 255, 255) == 'ffffff'
     assert color_util.color_rgb_to_hex(0, 0, 0) == '000000'
     assert color_util.color_rgb_to_hex(51, 153, 255) == '3399ff'
     assert color_util.color_rgb_to_hex(255, 67.9204190, 0) == 'ff4400'
示例#18
0
def query_device(entity: Entity, units: UnitSystem) -> dict:
    """Take an entity and return a properly formatted device object."""
    def celsius(deg: Optional[float]) -> Optional[float]:
        """Convert a float to Celsius and rounds to one decimal place."""
        if deg is None:
            return None
        return round(METRIC_SYSTEM.temperature(deg, units.temperature_unit), 1)
    if entity.domain == climate.DOMAIN:
        mode = entity.attributes.get(climate.ATTR_OPERATION_MODE).lower()
        if mode not in CLIMATE_SUPPORTED_MODES:
            mode = 'on'
        response = {
            'thermostatMode': mode,
            'thermostatTemperatureSetpoint':
            celsius(entity.attributes.get(climate.ATTR_TEMPERATURE)),
            'thermostatTemperatureAmbient':
            celsius(entity.attributes.get(climate.ATTR_CURRENT_TEMPERATURE)),
            'thermostatTemperatureSetpointHigh':
            celsius(entity.attributes.get(climate.ATTR_TARGET_TEMP_HIGH)),
            'thermostatTemperatureSetpointLow':
            celsius(entity.attributes.get(climate.ATTR_TARGET_TEMP_LOW)),
            'thermostatHumidityAmbient':
            entity.attributes.get(climate.ATTR_CURRENT_HUMIDITY),
        }
        return {k: v for k, v in response.items() if v is not None}

    final_state = entity.state != STATE_OFF
    final_brightness = entity.attributes.get(light.ATTR_BRIGHTNESS, 255
                                             if final_state else 0)

    if entity.domain == media_player.DOMAIN:
        level = entity.attributes.get(media_player.ATTR_MEDIA_VOLUME_LEVEL, 1.0
                                      if final_state else 0.0)
        # Convert 0.0-1.0 to 0-255
        final_brightness = round(min(1.0, level) * 255)

    if final_brightness is None:
        final_brightness = 255 if final_state else 0

    final_brightness = 100 * (final_brightness / 255)

    query_response = {
        "on": final_state,
        "online": True,
        "brightness": int(final_brightness)
    }

    supported_features = entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
    if supported_features & \
       (light.SUPPORT_COLOR_TEMP | light.SUPPORT_RGB_COLOR):
        query_response["color"] = {}

        if entity.attributes.get(light.ATTR_COLOR_TEMP) is not None:
            query_response["color"]["temperature"] = \
                int(round(color.color_temperature_mired_to_kelvin(
                    entity.attributes.get(light.ATTR_COLOR_TEMP))))

        if entity.attributes.get(light.ATTR_COLOR_NAME) is not None:
            query_response["color"]["name"] = \
                entity.attributes.get(light.ATTR_COLOR_NAME)

        if entity.attributes.get(light.ATTR_RGB_COLOR) is not None:
            color_rgb = entity.attributes.get(light.ATTR_RGB_COLOR)
            if color_rgb is not None:
                query_response["color"]["spectrumRGB"] = \
                    int(color.color_rgb_to_hex(
                        color_rgb[0], color_rgb[1], color_rgb[2]), 16)

    return query_response
示例#19
0
 def hs_to_rgbhex(self, hs):
     rgb = color_util.color_hs_to_RGB(*hs)
     return color_util.color_rgb_to_hex(*rgb)
示例#20
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()
示例#21
0
def query_device(entity: Entity, units: UnitSystem) -> dict:
    """Take an entity and return a properly formatted device object."""
    def celsius(deg: Optional[float]) -> Optional[float]:
        """Convert a float to Celsius and rounds to one decimal place."""
        if deg is None:
            return None
        return round(METRIC_SYSTEM.temperature(deg, units.temperature_unit), 1)

    if entity.domain == climate.DOMAIN:
        mode = entity.attributes.get(climate.ATTR_OPERATION_MODE).lower()
        if mode not in CLIMATE_SUPPORTED_MODES:
            mode = 'on'
        response = {
            'thermostatMode':
            mode,
            'thermostatTemperatureSetpoint':
            celsius(entity.attributes.get(climate.ATTR_TEMPERATURE)),
            'thermostatTemperatureAmbient':
            celsius(entity.attributes.get(climate.ATTR_CURRENT_TEMPERATURE)),
            'thermostatTemperatureSetpointHigh':
            celsius(entity.attributes.get(climate.ATTR_TARGET_TEMP_HIGH)),
            'thermostatTemperatureSetpointLow':
            celsius(entity.attributes.get(climate.ATTR_TARGET_TEMP_LOW)),
            'thermostatHumidityAmbient':
            entity.attributes.get(climate.ATTR_CURRENT_HUMIDITY),
        }
        return {k: v for k, v in response.items() if v is not None}

    final_state = entity.state != STATE_OFF
    final_brightness = entity.attributes.get(light.ATTR_BRIGHTNESS,
                                             255 if final_state else 0)

    if entity.domain == media_player.DOMAIN:
        level = entity.attributes.get(media_player.ATTR_MEDIA_VOLUME_LEVEL,
                                      1.0 if final_state else 0.0)
        # Convert 0.0-1.0 to 0-255
        final_brightness = round(min(1.0, level) * 255)

    if final_brightness is None:
        final_brightness = 255 if final_state else 0

    final_brightness = 100 * (final_brightness / 255)

    query_response = {
        "on": final_state,
        "online": True,
        "brightness": int(final_brightness)
    }

    supported_features = entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
    if supported_features & \
       (light.SUPPORT_COLOR_TEMP | light.SUPPORT_RGB_COLOR):
        query_response["color"] = {}

        if entity.attributes.get(light.ATTR_COLOR_TEMP) is not None:
            query_response["color"]["temperature"] = \
                int(round(color.color_temperature_mired_to_kelvin(
                    entity.attributes.get(light.ATTR_COLOR_TEMP))))

        if entity.attributes.get(light.ATTR_COLOR_NAME) is not None:
            query_response["color"]["name"] = \
                entity.attributes.get(light.ATTR_COLOR_NAME)

        if entity.attributes.get(light.ATTR_RGB_COLOR) is not None:
            color_rgb = entity.attributes.get(light.ATTR_RGB_COLOR)
            if color_rgb is not None:
                query_response["color"]["spectrumRGB"] = \
                    int(color.color_rgb_to_hex(
                        color_rgb[0], color_rgb[1], color_rgb[2]), 16)

    return query_response
示例#22
0
def query_device(entity: Entity, config: Config, units: UnitSystem) -> dict:
    """Take an entity and return a properly formatted device object."""
    def celsius(deg: Optional[float]) -> Optional[float]:
        """Convert a float to Celsius and rounds to one decimal place."""
        if deg is None:
            return None
        return round(METRIC_SYSTEM.temperature(deg, units.temperature_unit), 1)

    if entity.domain == sensor.DOMAIN:
        entity_config = config.entity_config.get(entity.entity_id, {})
        google_domain = entity_config.get(CONF_TYPE)

        if google_domain == climate.DOMAIN:
            # check if we have a string value to convert it to number
            value = entity.state
            if isinstance(entity.state, str):
                try:
                    value = float(value)
                except ValueError:
                    value = None

            if value is None:
                raise SmartHomeError(
                    ERROR_NOT_SUPPORTED,
                    "Invalid value {} for the climate sensor".format(
                        entity.state))

            # detect if we report temperature or humidity
            unit_of_measurement = entity.attributes.get(
                ATTR_UNIT_OF_MEASUREMENT, units.temperature_unit)
            if unit_of_measurement in [TEMP_FAHRENHEIT, TEMP_CELSIUS]:
                value = celsius(value)
                attr = 'thermostatTemperatureAmbient'
            elif unit_of_measurement == '%':
                attr = 'thermostatHumidityAmbient'
            else:
                raise SmartHomeError(
                    ERROR_NOT_SUPPORTED,
                    "Unit {} is not supported by the climate sensor".format(
                        unit_of_measurement))

            return {attr: value}

        raise SmartHomeError(
            ERROR_NOT_SUPPORTED,
            "Sensor type {} is not supported".format(google_domain))

    if entity.domain == climate.DOMAIN:
        mode = entity.attributes.get(climate.ATTR_OPERATION_MODE).lower()
        if mode not in CLIMATE_SUPPORTED_MODES:
            mode = 'heat'
        response = {
            'thermostatMode':
            mode,
            'thermostatTemperatureSetpoint':
            celsius(entity.attributes.get(climate.ATTR_TEMPERATURE)),
            'thermostatTemperatureAmbient':
            celsius(entity.attributes.get(climate.ATTR_CURRENT_TEMPERATURE)),
            'thermostatTemperatureSetpointHigh':
            celsius(entity.attributes.get(climate.ATTR_TARGET_TEMP_HIGH)),
            'thermostatTemperatureSetpointLow':
            celsius(entity.attributes.get(climate.ATTR_TARGET_TEMP_LOW)),
            'thermostatHumidityAmbient':
            entity.attributes.get(climate.ATTR_CURRENT_HUMIDITY),
        }
        return {k: v for k, v in response.items() if v is not None}

    final_state = entity.state != STATE_OFF
    final_brightness = entity.attributes.get(light.ATTR_BRIGHTNESS,
                                             255 if final_state else 0)

    if entity.domain == media_player.DOMAIN:
        level = entity.attributes.get(media_player.ATTR_MEDIA_VOLUME_LEVEL,
                                      1.0 if final_state else 0.0)
        # Convert 0.0-1.0 to 0-255
        final_brightness = round(min(1.0, level) * 255)

    if final_brightness is None:
        final_brightness = 255 if final_state else 0

    final_brightness = 100 * (final_brightness / 255)

    query_response = {
        "on": final_state,
        "online": True,
        "brightness": int(final_brightness)
    }

    supported_features = entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
    if supported_features & \
       (light.SUPPORT_COLOR_TEMP | light.SUPPORT_RGB_COLOR):
        query_response["color"] = {}

        if entity.attributes.get(light.ATTR_COLOR_TEMP) is not None:
            query_response["color"]["temperature"] = \
                int(round(color.color_temperature_mired_to_kelvin(
                    entity.attributes.get(light.ATTR_COLOR_TEMP))))

        if entity.attributes.get(light.ATTR_COLOR_NAME) is not None:
            query_response["color"]["name"] = \
                entity.attributes.get(light.ATTR_COLOR_NAME)

        if entity.attributes.get(light.ATTR_RGB_COLOR) is not None:
            color_rgb = entity.attributes.get(light.ATTR_RGB_COLOR)
            if color_rgb is not None:
                query_response["color"]["spectrumRGB"] = \
                    int(color.color_rgb_to_hex(
                        color_rgb[0], color_rgb[1], color_rgb[2]), 16)

    return query_response