def _observe_update(self, tradfri_device): """Receive new state data for this light.""" self._refresh(tradfri_device) self._rgb_color = color_util.rgb_hex_to_rgb_list( self._light_data.hex_color_inferred ) self.async_schedule_update_ha_state()
class BleBoxLightEntity(BleBoxEntity, LightEntity): """Representation of BleBox lights.""" def __init__(self, feature): """Initialize a BleBox light.""" super().__init__(feature) self._attr_supported_color_modes = {self.color_mode} @property def is_on(self) -> bool: """Return if light is on.""" return self._feature.is_on @property def brightness(self): """Return the name.""" return self._feature.brightness @property def color_mode(self): """Return the color mode.""" if self._feature.supports_white and self._feature.supports_color: return ColorMode.RGBW if self._feature.supports_brightness: return ColorMode.BRIGHTNESS return ColorMode.ONOFF @property def rgbw_color(self): """Return the hue and saturation.""" if (rgbw_hex := self._feature.rgbw_hex) is None: return None return tuple(rgb_hex_to_rgb_list(rgbw_hex)[0:4])
def _observe_update(self, tradfri_device): """Receive new state data for this light.""" self._refresh(tradfri_device) rgb = color_util.rgb_hex_to_rgb_list( self._light_data.hex_color_inferred) self._hs_color = color_util.color_RGB_to_hs(*rgb) self.async_schedule_update_ha_state()
def _async_update_rgb_or_w(self): """Update the controller with values from RGB or RGBW child.""" value = self._values[self.value_type] color_list = rgb_hex_to_rgb_list(value) if len(color_list) > 3: self._white = color_list.pop() self._hs = color_util.color_RGB_to_hs(*color_list)
async def async_update(self): """Update the light's status.""" if self.device.appliance.status.get(self._key, {}).get(ATTR_VALUE) is True: self._state = True elif self.device.appliance.status.get(self._key, {}).get(ATTR_VALUE) is False: self._state = False else: self._state = None _LOGGER.debug("Updated, new light state: %s", self._state) if self._ambient: color = self.device.appliance.status.get(self._custom_color_key, {}) if not color: self._hs_color = None self._brightness = None else: colorvalue = color.get(ATTR_VALUE)[1:] rgb = color_util.rgb_hex_to_rgb_list(colorvalue) hsv = color_util.color_RGB_to_hsv(rgb[0], rgb[1], rgb[2]) self._hs_color = [hsv[0], hsv[1]] self._brightness = ceil((hsv[2] - 10) * 255 / 90) _LOGGER.debug("Updated, new brightness: %s", self._brightness) else: brightness = self.device.appliance.status.get(self._brightness_key, {}) if brightness is None: self._brightness = None else: self._brightness = ceil((brightness.get(ATTR_VALUE) - 10) * 255 / 90) _LOGGER.debug("Updated, new brightness: %s", self._brightness)
def rgbw_color(self): """Return the hue and saturation.""" rgbw_hex = self._feature.rgbw_hex if rgbw_hex is None: return None return tuple(rgb_hex_to_rgb_list(rgbw_hex)[0:4])
def _update_rgb_or_w(self): """Update the controller with values from RGB or RGBW child.""" value = self._values[self.value_type] color_list = rgb_hex_to_rgb_list(value) if len(color_list) > 3: self._white = color_list.pop() self._hs = color_util.color_RGB_to_hs(*color_list)
def _observe_update(self, tradfri_device): """Receive new state data for this light.""" self._refresh(tradfri_device) self._rgb_color = color_util.rgb_hex_to_rgb_list( self._light_data.hex_color_inferred ) self.hass.async_add_job(self.async_update_ha_state())
async def execute(self, command, data, params, challenge): """Execute a color temperature command.""" if "temperature" in params["color"]: temp = color_util.color_temperature_kelvin_to_mired( params["color"]["temperature"]) min_temp = self.state.attributes[light.ATTR_MIN_MIREDS] max_temp = self.state.attributes[light.ATTR_MAX_MIREDS] if temp < min_temp or temp > max_temp: raise SmartHomeError( ERR_VALUE_OUT_OF_RANGE, "Temperature should be between {} and {}".format( min_temp, max_temp), ) await self.hass.services.async_call( light.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_COLOR_TEMP: temp }, blocking=True, context=data.context, ) elif "spectrumRGB" in params["color"]: # Convert integer to hex format and left pad with 0's till length 6 hex_value = "{0:06x}".format(params["color"]["spectrumRGB"]) color = color_util.color_RGB_to_hs( *color_util.rgb_hex_to_rgb_list(hex_value)) await self.hass.services.async_call( light.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_HS_COLOR: color }, blocking=True, context=data.context, ) elif "spectrumHSV" in params["color"]: color = params["color"]["spectrumHSV"] saturation = color["saturation"] * 100 brightness = color["value"] * 255 await self.hass.services.async_call( light.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_HS_COLOR: [color["hue"], saturation], light.ATTR_BRIGHTNESS: brightness, }, blocking=True, context=data.context, )
def update(self): """Fetch new state data for this light.""" self._light.update() # Handle Hue lights paired with the gatway if self._light_data.hex_color is not None: self._rgb_color = color_util.rgb_hex_to_rgb_list( self._light_data.hex_color)
def hs_color(self): """Return the hue and saturation.""" rgbw_hex = self._feature.rgbw_hex if rgbw_hex is None: return None rgb = rgb_hex_to_rgb_list(rgbw_hex)[0:3] return color_RGB_to_hs(*rgb)
def update(self): """Fetch new state data for this light.""" self._light.update() # Handle Hue lights paired with the gateway # hex_color is 0 when bulb is unreachable if self._light_data.hex_color not in (None, '0'): self._rgb_color = color_util.rgb_hex_to_rgb_list( self._light_data.hex_color)
async def execute(self, hass, command, params): """Execute a color spectrum command.""" # Convert integer to hex format and left pad with 0's till length 6 hex_value = "{0:06x}".format(params['color']['spectrumRGB']) color = color_util.rgb_hex_to_rgb_list(hex_value) await hass.services.async_call(light.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_RGB_COLOR: color }, blocking=True)
def _update_rgb_or_w(self): """Update the controller with values from RGB or RGBW child.""" set_req = self.gateway.const.SetReq value = self._values[self.value_type] color_list = rgb_hex_to_rgb_list(value) if set_req.V_LIGHT not in self._values and set_req.V_DIMMER not in self._values: self._state = max(color_list) > 0 if len(color_list) > 3: self._white = color_list.pop() self._rgb = color_list
async def execute(self, command, params): """Execute a color spectrum command.""" # Convert integer to hex format and left pad with 0's till length 6 hex_value = "{0:06x}".format(params['color']['spectrumRGB']) color = color_util.color_RGB_to_hs( *color_util.rgb_hex_to_rgb_list(hex_value)) await self.hass.services.async_call(light.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_HS_COLOR: color }, blocking=True)
def _observe_update(self, tradfri_device): """Receive new state data for this light.""" self._refresh(tradfri_device) # Handle Hue lights paired with the gateway # hex_color is 0 when bulb is unreachable if self._light_data.hex_color not in (None, '0'): self._rgb_color = color_util.rgb_hex_to_rgb_list( self._light_data.hex_color) self.hass.async_add_job(self.async_update_ha_state())
def _update_rgb_or_w(self): """Update the controller with values from RGB or RGBW child.""" set_req = self.gateway.const.SetReq value = self._values[self.value_type] color_list = rgb_hex_to_rgb_list(value) if set_req.V_LIGHT not in self._values and \ set_req.V_DIMMER not in self._values: self._state = max(color_list) > 0 if len(color_list) > 3: self._white = color_list.pop() self._rgb = color_list
def update(self): """Fetch new state data for this light.""" from pytradfri import RequestTimeout try: self._light.update() except RequestTimeout: _LOGGER.warning("Tradfri update request timed out") # Handle Hue lights paired with the gateway # hex_color is 0 when bulb is unreachable if self._light_data.hex_color not in (None, '0'): self._rgb_color = color_util.rgb_hex_to_rgb_list( self._light_data.hex_color)
def update(self): """Fetch new state data for this light.""" from pytradfri import RequestTimeout try: self._api(self._light.update()) except RequestTimeout as exception: _LOGGER.warning("Tradfri update request timed out: %s", exception) # Handle Hue lights paired with the gateway # hex_color is 0 when bulb is unreachable if self._light_data.hex_color not in (None, '0'): self._rgb_color = color_util.rgb_hex_to_rgb_list( self._light_data.hex_color)
async def async_update(self): """Update light's status.""" # get all messages of this appliance stored in status status = self._device.appliance.status # check if a message has been received already if self._key not in status: self._state = None elif "value" not in status[self._key]: self._state = None else: # Functional or ambient lighting if self._key in ["BSH.Common.Setting.AmbientLightEnabled", "Cooking.Common.Setting.Lighting"]: self._state = status[self._key].get("value") == "true" # Functional lighting if self._key == "Cooking.Common.Setting.Lighting": # Brightness brightness = self._device.appliance.status.get("Cooking.Common.Setting.LightingBrightness", {}) if brightness is not None and brightness.get("value") is not None: self._brightness = ceil((brightness.get("value") - 10) * 255 / 90) else: self._brightness = None # Ambient lighting elif self._key == "BSH.Common.Setting.AmbientLightEnabled": # Brightness brightness = self._device.appliance.status.get("BSH.Common.Setting.AmbientLightBrightness", {}) if brightness is not None and brightness.get("value") is not None: self._brightness = ceil((brightness.get("value") - 10) * 255 / 90) else: self._brightness = None # Hue, saturation and brightness for custom color color = self._device.appliance.status.get("BSH.Common.Setting.AmbientLightCustomColor", {}) if color is not None and color.get("value") is not None: colorvalue = color.get("value")[1:] rgb = color_util.rgb_hex_to_rgb_list(colorvalue) hsv = color_util.color_RGB_to_hsv(rgb[0], rgb[1], rgb[2]) self._hs_color = [hsv[0], hsv[1]] self._brightness = ceil((hsv[2] - 10) * 255 / 90) else: self._hs_color = None self._brightness = None
def test_rgb_hex_to_rgb_list(): """Test rgb_hex_to_rgb_list.""" assert [255, 255, 255] == color_util.rgb_hex_to_rgb_list("ffffff") assert [0, 0, 0] == color_util.rgb_hex_to_rgb_list("000000") assert [255, 255, 255, 255] == color_util.rgb_hex_to_rgb_list("ffffffff") assert [0, 0, 0, 0] == color_util.rgb_hex_to_rgb_list("00000000") assert [51, 153, 255] == color_util.rgb_hex_to_rgb_list("3399ff") assert [51, 153, 255, 0] == color_util.rgb_hex_to_rgb_list("3399ff00")
async def execute(self, command, data, params, challenge): """Execute a color temperature command.""" if 'temperature' in params['color']: temp = color_util.color_temperature_kelvin_to_mired( params['color']['temperature']) min_temp = self.state.attributes[light.ATTR_MIN_MIREDS] max_temp = self.state.attributes[light.ATTR_MAX_MIREDS] if temp < min_temp or temp > max_temp: raise SmartHomeError( ERR_VALUE_OUT_OF_RANGE, "Temperature should be between {} and {}".format(min_temp, max_temp)) await self.hass.services.async_call( light.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_COLOR_TEMP: temp, }, blocking=True, context=data.context) elif 'spectrumRGB' in params['color']: # Convert integer to hex format and left pad with 0's till length 6 hex_value = "{0:06x}".format(params['color']['spectrumRGB']) color = color_util.color_RGB_to_hs( *color_util.rgb_hex_to_rgb_list(hex_value)) await self.hass.services.async_call( light.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_HS_COLOR: color }, blocking=True, context=data.context) elif 'spectrumHSV' in params['color']: color = params['color']['spectrumHSV'] saturation = color['saturation'] * 100 brightness = color['value'] * 255 await self.hass.services.async_call( light.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_HS_COLOR: [color['hue'], saturation], light.ATTR_BRIGHTNESS: brightness }, blocking=True, context=data.context)
def _update_rgb_or_w(self): """Update the controller with values from RGB or RGBW child.""" set_req = self.gateway.const.SetReq value = self._values[self.value_type] if len(value) != 6 and len(value) != 8: _LOGGER.error("Wrong value %s for %s", value, set_req(self.value_type).name) return color_list = rgb_hex_to_rgb_list(value) if set_req.V_LIGHT not in self._values and \ set_req.V_DIMMER not in self._values: self._state = max(color_list) > 0 if len(color_list) > 3: if set_req.V_RGBW != self.value_type: _LOGGER.error("Wrong value %s for %s", value, set_req(self.value_type).name) return self._white = color_list.pop() self._rgb = color_list
def _update_rgb_or_w(self): """Update the controller with values from RGB or RGBW child.""" set_req = self.gateway.const.SetReq value = self._values[self.value_type] if len(value) != 6 and len(value) != 8: _LOGGER.error( "Wrong value %s for %s", value, set_req(self.value_type).name) return color_list = rgb_hex_to_rgb_list(value) if set_req.V_LIGHT not in self._values and \ set_req.V_DIMMER not in self._values: self._state = max(color_list) > 0 if len(color_list) > 3: if set_req.V_RGBW != self.value_type: _LOGGER.error( "Wrong value %s for %s", value, set_req(self.value_type).name) return self._white = color_list.pop() self._rgb = color_list
def update(self, data: dict = None): """ update attribue in data """ for key, value in data.items(): if key == CHIP_TEMPERATURE: self._chip_temperature = value if key == HW_VER: self._hw_ver = value if key == FW_VER or key == 'back_version': self._fw_ver = value if key == LQI: self._lqi = value if self._attr in data: self._state = data[self._attr] == 1 if ATTR_BRIGHTNESS in data: self._brightness = data[ATTR_BRIGHTNESS] / 100.0 * 255.0 if ATTR_COLOR_TEMP in data: self._color_temp = data[ATTR_COLOR_TEMP] if ATTR_RGB_COLOR in data: self._rgb_color = data[ATTR_RGB_COLOR] if ATTR_HS_COLOR in data: if self.device['type'] == 'zigbee': if isinstance(data[ATTR_HS_COLOR], int): value = hex(data[ATTR_HS_COLOR] & 0xFFFFFF).replace( '0x', '') else: value = data[ATTR_HS_COLOR].replace('0x', '') else: value = data[ATTR_HS_COLOR] * 3 rgb = color_util.rgb_hex_to_rgb_list(value) if len(rgb) > 3: self._white = rgb.pop() if len(rgb) > 3: self._brightness = rgb.pop() self._hs = color_util.color_RGB_to_hs(*rgb) self.schedule_update_ha_state()
def test_rgb_hex_to_rgb_list(self): """Test rgb_hex_to_rgb_list.""" self.assertEqual([255, 255, 255], color_util.rgb_hex_to_rgb_list('ffffff')) self.assertEqual([0, 0, 0], color_util.rgb_hex_to_rgb_list('000000')) self.assertEqual([255, 255, 255, 255], color_util.rgb_hex_to_rgb_list('ffffffff')) self.assertEqual([0, 0, 0, 0], color_util.rgb_hex_to_rgb_list('00000000')) self.assertEqual([51, 153, 255], color_util.rgb_hex_to_rgb_list('3399ff')) self.assertEqual([51, 153, 255, 0], color_util.rgb_hex_to_rgb_list('3399ff00'))
def test_rgb_hex_to_rgb_list(self): """Test rgb_hex_to_rgb_list.""" assert [255, 255, 255] == \ color_util.rgb_hex_to_rgb_list('ffffff') assert [0, 0, 0] == \ color_util.rgb_hex_to_rgb_list('000000') assert [255, 255, 255, 255] == \ color_util.rgb_hex_to_rgb_list('ffffffff') assert [0, 0, 0, 0] == \ color_util.rgb_hex_to_rgb_list('00000000') assert [51, 153, 255] == \ color_util.rgb_hex_to_rgb_list('3399ff') assert [51, 153, 255, 0] == \ color_util.rgb_hex_to_rgb_list('3399ff00')
def _async_update_rgb_or_w(self) -> None: """Update the controller with values from RGBW child.""" value = self._values[self.value_type] self._attr_rgbw_color = cast(tuple[int, int, int, int], tuple(rgb_hex_to_rgb_list(value)))
def rgbhex_to_hs(self, rgbhex): rgb = color_util.rgb_hex_to_rgb_list(rgbhex) return color_util.color_RGB_to_hs(*rgb)
def rgbhex_to_hs(self): rgbhex = self._kettler._rgb rgb = color_util.rgb_hex_to_rgb_list(rgbhex) self._hs = color_util.color_RGB_to_hs(*rgb)
def determine_service( entity_id: str, command: str, params: dict, units: UnitSystem) -> Tuple[str, dict]: """ Determine service and service_data. Attempt to return a tuple of service and service_data based on the entity and action requested. """ _LOGGER.debug("Handling command %s with data %s", command, params) domain = entity_id.split('.')[0] service_data = {ATTR_ENTITY_ID: entity_id} # type: Dict[str, Any] # special media_player handling if domain == media_player.DOMAIN and command == COMMAND_BRIGHTNESS: brightness = params.get('brightness', 0) service_data[media_player.ATTR_MEDIA_VOLUME_LEVEL] = brightness / 100 return (media_player.SERVICE_VOLUME_SET, service_data) # special cover handling if domain == cover.DOMAIN: if command == COMMAND_BRIGHTNESS: service_data['position'] = params.get('brightness', 0) return (cover.SERVICE_SET_COVER_POSITION, service_data) if command == COMMAND_ONOFF and params.get('on') is True: return (cover.SERVICE_OPEN_COVER, service_data) return (cover.SERVICE_CLOSE_COVER, service_data) # special climate handling if domain == climate.DOMAIN: if command == COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT: service_data['temperature'] = units.temperature( params.get('thermostatTemperatureSetpoint', 25), TEMP_CELSIUS) return (climate.SERVICE_SET_TEMPERATURE, service_data) if command == COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE: service_data['target_temp_high'] = units.temperature( params.get('thermostatTemperatureSetpointHigh', 25), TEMP_CELSIUS) service_data['target_temp_low'] = units.temperature( params.get('thermostatTemperatureSetpointLow', 18), TEMP_CELSIUS) return (climate.SERVICE_SET_TEMPERATURE, service_data) if command == COMMAND_THERMOSTAT_SET_MODE: service_data['operation_mode'] = params.get( 'thermostatMode', 'off') return (climate.SERVICE_SET_OPERATION_MODE, service_data) if command == COMMAND_BRIGHTNESS: brightness = params.get('brightness') service_data['brightness'] = int(brightness / 100 * 255) return (SERVICE_TURN_ON, service_data) if command == COMMAND_COLOR: color_data = params.get('color') if color_data is not None: if color_data.get('temperature', 0) > 0: service_data[light.ATTR_KELVIN] = color_data.get('temperature') return (SERVICE_TURN_ON, service_data) if color_data.get('spectrumRGB', 0) > 0: # blue is 255 so pad up to 6 chars hex_value = \ ('%0x' % int(color_data.get('spectrumRGB'))).zfill(6) service_data[light.ATTR_RGB_COLOR] = \ color.rgb_hex_to_rgb_list(hex_value) return (SERVICE_TURN_ON, service_data) if command == COMMAND_ACTIVATESCENE: return (SERVICE_TURN_ON, service_data) if COMMAND_ONOFF == command: if params.get('on') is True: return (SERVICE_TURN_ON, service_data) return (SERVICE_TURN_OFF, service_data) return (None, service_data)
def hs_color(self): return color_util.color_RGB_to_hs(*color_util.rgb_hex_to_rgb_list(self._color))
def determine_service(entity_id: str, command: str, params: dict, units: UnitSystem) -> Tuple[str, dict]: """ Determine service and service_data. Attempt to return a tuple of service and service_data based on the entity and action requested. """ _LOGGER.debug("Handling command %s with data %s", command, params) domain = entity_id.split('.')[0] service_data = {ATTR_ENTITY_ID: entity_id} # type: Dict[str, Any] # special media_player handling if domain == media_player.DOMAIN and command == COMMAND_BRIGHTNESS: brightness = params.get('brightness', 0) service_data[media_player.ATTR_MEDIA_VOLUME_LEVEL] = brightness / 100 return (media_player.SERVICE_VOLUME_SET, service_data) # special cover handling if domain == cover.DOMAIN: if command == COMMAND_BRIGHTNESS: service_data['position'] = params.get('brightness', 0) return (cover.SERVICE_SET_COVER_POSITION, service_data) if command == COMMAND_ONOFF and params.get('on') is True: return (cover.SERVICE_OPEN_COVER, service_data) return (cover.SERVICE_CLOSE_COVER, service_data) # special climate handling if domain == climate.DOMAIN: if command == COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT: service_data['temperature'] = units.temperature( params.get('thermostatTemperatureSetpoint', 25), TEMP_CELSIUS) return (climate.SERVICE_SET_TEMPERATURE, service_data) if command == COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE: service_data['target_temp_high'] = units.temperature( params.get('thermostatTemperatureSetpointHigh', 25), TEMP_CELSIUS) service_data['target_temp_low'] = units.temperature( params.get('thermostatTemperatureSetpointLow', 18), TEMP_CELSIUS) return (climate.SERVICE_SET_TEMPERATURE, service_data) if command == COMMAND_THERMOSTAT_SET_MODE: service_data['operation_mode'] = params.get( 'thermostatMode', 'off') return (climate.SERVICE_SET_OPERATION_MODE, service_data) if command == COMMAND_BRIGHTNESS: brightness = params.get('brightness') service_data['brightness'] = int(brightness / 100 * 255) return (SERVICE_TURN_ON, service_data) if command == COMMAND_COLOR: color_data = params.get('color') if color_data is not None: if color_data.get('temperature', 0) > 0: service_data[light.ATTR_KELVIN] = color_data.get('temperature') return (SERVICE_TURN_ON, service_data) if color_data.get('spectrumRGB', 0) > 0: # blue is 255 so pad up to 6 chars hex_value = \ ('%0x' % int(color_data.get('spectrumRGB'))).zfill(6) service_data[light.ATTR_RGB_COLOR] = \ color.rgb_hex_to_rgb_list(hex_value) return (SERVICE_TURN_ON, service_data) if command == COMMAND_ACTIVATESCENE: return (SERVICE_TURN_ON, service_data) if COMMAND_ONOFF == command: if params.get('on') is True: return (SERVICE_TURN_ON, service_data) return (SERVICE_TURN_OFF, service_data) return (None, service_data)
def rgb_received(topic, payload, qos): """Handle new MQTT messages for RGB.""" self._rgb = rgb_hex_to_rgb_list(templates[CONF_RGB](payload)) self.async_schedule_update_ha_state()