response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Set up the Dovado component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Dovado component.""" hass.data[DOMAIN] = DovadoData( dovado.Dovado( config[DOMAIN][CONF_USERNAME], config[DOMAIN][CONF_PASSWORD], config[DOMAIN].get(CONF_HOST), config[DOMAIN].get(CONF_PORT), ) ) return True
Return a /dev/serial/by-id match for given device if available.
def get_serial_by_id(dev_path: str) -> str: """Return a /dev/serial/by-id match for given device if available.""" by_id = "/dev/serial/by-id" if not os.path.isdir(by_id): return dev_path for path in (entry.path for entry in os.scandir(by_id) if entry.is_symlink()): if os.path.realpath(path) == dev_path: return path return dev_path
Create a new MBUS Entity.
def create_mbus_entity( mbus: int, mtype: int, telegram: dict[str, DSMRObject] ) -> DSMRSensorEntityDescription | None: """Create a new MBUS Entity.""" if ( mtype == 3 and ( obis_reference := getattr( obis_references, f"BELGIUM_MBUS{mbus}_METER_READING2" ) ) in telegram ): return DSMRSensorEntityDescription( key=f"mbus{mbus}_gas_reading", translation_key="gas_meter_reading", obis_reference=obis_reference, is_gas=True, device_class=SensorDeviceClass.GAS, state_class=SensorStateClass.TOTAL_INCREASING, ) if ( mtype == 7 and ( obis_reference := getattr( obis_references, f"BELGIUM_MBUS{mbus}_METER_READING1" ) ) in telegram ): return DSMRSensorEntityDescription( key=f"mbus{mbus}_water_reading", translation_key="water_meter_reading", obis_reference=obis_reference, is_water=True, device_class=SensorDeviceClass.WATER, state_class=SensorStateClass.TOTAL_INCREASING, ) return None
Get native unit of measurement from telegram,.
def device_class_and_uom( telegram: dict[str, DSMRObject], entity_description: DSMRSensorEntityDescription, ) -> tuple[SensorDeviceClass | None, str | None]: """Get native unit of measurement from telegram,.""" dsmr_object = telegram[entity_description.obis_reference] uom: str | None = getattr(dsmr_object, "unit") or None with suppress(ValueError): if entity_description.device_class == SensorDeviceClass.GAS and ( enery_uom := UnitOfEnergy(str(uom)) ): return (SensorDeviceClass.ENERGY, enery_uom) if uom in UNIT_CONVERSION: return (entity_description.device_class, UNIT_CONVERSION[uom]) return (entity_description.device_class, uom)
Rename old gas sensor to mbus variant.
def rename_old_gas_to_mbus( hass: HomeAssistant, entry: ConfigEntry, mbus_device_id: str ) -> None: """Rename old gas sensor to mbus variant.""" dev_reg = dr.async_get(hass) device_entry_v1 = dev_reg.async_get_device(identifiers={(DOMAIN, entry.entry_id)}) if device_entry_v1 is not None: device_id = device_entry_v1.id ent_reg = er.async_get(hass) entries = er.async_entries_for_device(ent_reg, device_id) for entity in entries: if entity.unique_id.endswith("belgium_5min_gas_meter_reading"): try: ent_reg.async_update_entity( entity.entity_id, new_unique_id=mbus_device_id, device_id=mbus_device_id, ) except ValueError: LOGGER.debug( "Skip migration of %s because it already exists", entity.entity_id, ) else: LOGGER.debug( "Migrated entity %s from unique id %s to %s", entity.entity_id, entity.unique_id, mbus_device_id, ) # Cleanup old device dev_entities = er.async_entries_for_device( ent_reg, device_id, include_disabled_entities=True ) if not dev_entities: dev_reg.async_remove_device(device_id)
Create MBUS Entities.
def create_mbus_entities( hass: HomeAssistant, telegram: dict[str, DSMRObject], entry: ConfigEntry ) -> list[DSMREntity]: """Create MBUS Entities.""" entities = [] for idx in range(1, 5): if ( device_type := getattr(obis_references, f"BELGIUM_MBUS{idx}_DEVICE_TYPE") ) not in telegram: continue if (type_ := int(telegram[device_type].value)) not in (3, 7): continue if ( identifier := getattr( obis_references, f"BELGIUM_MBUS{idx}_EQUIPMENT_IDENTIFIER", ) ) in telegram: serial_ = telegram[identifier].value rename_old_gas_to_mbus(hass, entry, serial_) else: serial_ = "" if description := create_mbus_entity(idx, type_, telegram): entities.append( DSMREntity( description, entry, telegram, *device_class_and_uom(telegram, description), # type: ignore[arg-type] serial_, idx, ) ) return entities
Migrate DSMR entity entries. - Migrates unique ID for sensors based on entity description name to key.
def async_migrate_entity_entry( config_entry: ConfigEntry, entity_entry: er.RegistryEntry ) -> dict[str, Any] | None: """Migrate DSMR entity entries. - Migrates unique ID for sensors based on entity description name to key. """ # Replace names with keys in unique ID for old, new in ( ("Power_Consumption", "current_electricity_usage"), ("Power_Production", "current_electricity_delivery"), ("Power_Tariff", "electricity_active_tariff"), ("Energy_Consumption_(tarif_1)", "electricity_used_tariff_1"), ("Energy_Consumption_(tarif_2)", "electricity_used_tariff_2"), ("Energy_Production_(tarif_1)", "electricity_delivered_tariff_1"), ("Energy_Production_(tarif_2)", "electricity_delivered_tariff_2"), ("Power_Consumption_Phase_L1", "instantaneous_active_power_l1_positive"), ("Power_Consumption_Phase_L3", "instantaneous_active_power_l3_positive"), ("Power_Consumption_Phase_L2", "instantaneous_active_power_l2_positive"), ("Power_Production_Phase_L1", "instantaneous_active_power_l1_negative"), ("Power_Production_Phase_L2", "instantaneous_active_power_l2_negative"), ("Power_Production_Phase_L3", "instantaneous_active_power_l3_negative"), ("Short_Power_Failure_Count", "short_power_failure_count"), ("Long_Power_Failure_Count", "long_power_failure_count"), ("Voltage_Sags_Phase_L1", "voltage_sag_l1_count"), ("Voltage_Sags_Phase_L2", "voltage_sag_l2_count"), ("Voltage_Sags_Phase_L3", "voltage_sag_l3_count"), ("Voltage_Swells_Phase_L1", "voltage_swell_l1_count"), ("Voltage_Swells_Phase_L2", "voltage_swell_l2_count"), ("Voltage_Swells_Phase_L3", "voltage_swell_l3_count"), ("Voltage_Phase_L1", "instantaneous_voltage_l1"), ("Voltage_Phase_L2", "instantaneous_voltage_l2"), ("Voltage_Phase_L3", "instantaneous_voltage_l3"), ("Current_Phase_L1", "instantaneous_current_l1"), ("Current_Phase_L2", "instantaneous_current_l2"), ("Current_Phase_L3", "instantaneous_current_l3"), ("Max_power_per_phase", "belgium_max_power_per_phase"), ("Max_current_per_phase", "belgium_max_current_per_phase"), ("Energy_Consumption_(total)", "electricity_imported_total"), ("Energy_Production_(total)", "electricity_exported_total"), ): if entity_entry.unique_id.endswith(old): return {"new_unique_id": entity_entry.unique_id.replace(old, new)} # Replace unique ID for gas sensors, based on DSMR version old = "Gas_Consumption" if entity_entry.unique_id.endswith(old): dsmr_version = config_entry.data[CONF_DSMR_VERSION] if dsmr_version in {"4", "5", "5L"}: return { "new_unique_id": entity_entry.unique_id.replace( old, "hourly_gas_meter_reading" ) } if dsmr_version == "5B": return { "new_unique_id": entity_entry.unique_id.replace( old, "belgium_5min_gas_meter_reading" ) } if dsmr_version == "2.2": return { "new_unique_id": entity_entry.unique_id.replace( old, "gas_meter_reading" ) } # No migration needed return None
Transform DSMR version value to right format.
def dsmr_transform(value): """Transform DSMR version value to right format.""" if value.isdigit(): return float(value) / 10 return value
Transform tariff from number to description.
def tariff_transform(value): """Transform tariff from number to description.""" if value == "1": return "low" return "high"
Set up the DTE energy bridge sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the DTE energy bridge sensor.""" name = config[CONF_NAME] ip_address = config[CONF_IP_ADDRESS] version = config[CONF_VERSION] add_entities([DteEnergyBridgeSensor(ip_address, name, version)], True)
Get the time in minutes from a timestamp. The timestamp should be in the format day/month/year hour/minute/second
def due_in_minutes(timestamp): """Get the time in minutes from a timestamp. The timestamp should be in the format day/month/year hour/minute/second """ diff = datetime.strptime(timestamp, "%d/%m/%Y %H:%M:%S") - dt_util.now().replace( tzinfo=None ) return str(int(diff.total_seconds() / 60))
Set up the Dublin public transport sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Dublin public transport sensor.""" name = config[CONF_NAME] stop = config[CONF_STOP_ID] route = config[CONF_ROUTE] data = PublicTransportData(stop, route) add_entities([DublinPublicTransportSensor(data, stop, route, name)], True)
Add a listener that fires repetitively at every timedelta interval.
def async_track_time_interval_backoff( hass: HomeAssistant, action: Callable[[datetime], Coroutine[Any, Any, bool]], intervals: Sequence[timedelta], ) -> CALLBACK_TYPE: """Add a listener that fires repetitively at every timedelta interval.""" remove: CALLBACK_TYPE | None = None failed = 0 async def interval_listener(now: datetime) -> None: """Handle elapsed intervals with backoff.""" nonlocal failed, remove try: failed += 1 if await action(now): failed = 0 finally: delay = intervals[failed] if failed < len(intervals) else intervals[-1] remove = async_call_later( hass, delay.total_seconds(), interval_listener_job ) interval_listener_job = HassJob(interval_listener, cancel_on_shutdown=True) hass.async_run_hass_job(interval_listener_job, dt_util.utcnow()) def remove_listener() -> None: """Remove interval listener.""" if remove: remove() return remove_listener
Catch command exceptions.
def api_call( func: Callable[Concatenate[_T, _P], Awaitable[None]], ) -> Callable[Concatenate[_T, _P], Coroutine[Any, Any, None]]: """Catch command exceptions.""" @wraps(func) async def cmd_wrapper(self: _T, *args: _P.args, **kwargs: _P.kwargs) -> None: """Wrap all command methods.""" try: await func(self, *args, **kwargs) except OSError as exc: raise HomeAssistantError( f"Error calling {func.__name__} on entity {self.entity_id}" ) from exc return cmd_wrapper
Extract longitude and latitude from a device tracker.
def get_position_data( hass: HomeAssistant, registry_id: str ) -> tuple[float, float] | None: """Extract longitude and latitude from a device tracker.""" registry = er.async_get(hass) registry_entry = registry.async_get(registry_id) if registry_entry is None: raise EntityNotFoundError(f"Failed to find registry entry {registry_id}") entity = hass.states.get(registry_entry.entity_id) if entity is None: raise EntityNotFoundError(f"Failed to find entity {registry_entry.entity_id}") latitude = entity.attributes.get(ATTR_LATITUDE) if not latitude: raise AttributeError( f"Failed to find attribute '{ATTR_LATITUDE}' in {registry_entry.entity_id}", ATTR_LATITUDE, ) longitude = entity.attributes.get(ATTR_LONGITUDE) if not longitude: raise AttributeError( f"Failed to find attribute '{ATTR_LONGITUDE}' in {registry_entry.entity_id}", ATTR_LONGITUDE, ) return (latitude, longitude)
Set up the Dweet sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Dweet sensor.""" name = config.get(CONF_NAME) device = config.get(CONF_DEVICE) value_template = config.get(CONF_VALUE_TEMPLATE) unit = config.get(CONF_UNIT_OF_MEASUREMENT) if value_template is not None: value_template.hass = hass try: content = json.dumps(dweepy.get_latest_dweet_for(device)[0]["content"]) except dweepy.DweepyError: _LOGGER.error("Device/thing %s could not be found", device) return if value_template.render_with_possible_json_value(content) == "": _LOGGER.error("%s was not found", value_template) return dweet = DweetData(device) add_entities([DweetSensor(hass, dweet, name, value_template, unit)], True)
Set up the Dweet.io component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Dweet.io component.""" conf = config[DOMAIN] name = conf.get(CONF_NAME) whitelist = conf.get(CONF_WHITELIST) json_body = {} def dweet_event_listener(event): """Listen for new messages on the bus and sends them to Dweet.io.""" state = event.data.get("new_state") if ( state is None or state.state in (STATE_UNKNOWN, "") or state.entity_id not in whitelist ): return try: _state = state_helper.state_as_number(state) except ValueError: _state = state.state json_body[state.attributes.get(ATTR_FRIENDLY_NAME)] = _state send_data(name, json_body) hass.bus.listen(EVENT_STATE_CHANGED, dweet_event_listener) return True
Send the collected data to Dweet.io.
def send_data(name, msg): """Send the collected data to Dweet.io.""" try: dweepy.dweet_for(name, msg) except dweepy.DweepyError: _LOGGER.error("Error saving data to Dweet.io: %s", msg)
Create the initial converted map with just the basic key:value pairs updated.
def convert_with_map(config, conf_map): """Create the initial converted map with just the basic key:value pairs updated.""" result = {} for conf in conf_map: if conf in config: result[conf_map[conf]] = config[conf] return result
Convert the config for a channel.
def convert_channel(config: dict[str, Any]) -> dict[str, Any]: """Convert the config for a channel.""" my_map = { CONF_NAME: dyn_const.CONF_NAME, CONF_FADE: dyn_const.CONF_FADE, CONF_TYPE: dyn_const.CONF_CHANNEL_TYPE, } return convert_with_map(config, my_map)
Convert the config for a preset.
def convert_preset(config: dict[str, Any]) -> dict[str, Any]: """Convert the config for a preset.""" my_map = { CONF_NAME: dyn_const.CONF_NAME, CONF_FADE: dyn_const.CONF_FADE, CONF_LEVEL: dyn_const.CONF_LEVEL, } return convert_with_map(config, my_map)
Convert the config for an area.
def convert_area(config: dict[str, Any]) -> dict[str, Any]: """Convert the config for an area.""" my_map = { CONF_NAME: dyn_const.CONF_NAME, CONF_FADE: dyn_const.CONF_FADE, CONF_NO_DEFAULT: dyn_const.CONF_NO_DEFAULT, CONF_ROOM_ON: dyn_const.CONF_ROOM_ON, CONF_ROOM_OFF: dyn_const.CONF_ROOM_OFF, CONF_CHANNEL_COVER: dyn_const.CONF_CHANNEL_COVER, CONF_DEVICE_CLASS: dyn_const.CONF_DEVICE_CLASS, CONF_OPEN_PRESET: dyn_const.CONF_OPEN_PRESET, CONF_CLOSE_PRESET: dyn_const.CONF_CLOSE_PRESET, CONF_STOP_PRESET: dyn_const.CONF_STOP_PRESET, CONF_DURATION: dyn_const.CONF_DURATION, CONF_TILT_TIME: dyn_const.CONF_TILT_TIME, } result = convert_with_map(config, my_map) if CONF_CHANNEL in config: result[dyn_const.CONF_CHANNEL] = { channel: convert_channel(channel_conf) for (channel, channel_conf) in config[CONF_CHANNEL].items() } if CONF_PRESET in config: result[dyn_const.CONF_PRESET] = { preset: convert_preset(preset_conf) for (preset, preset_conf) in config[CONF_PRESET].items() } if CONF_TEMPLATE in config: result[dyn_const.CONF_TEMPLATE] = TEMPLATE_MAP[config[CONF_TEMPLATE]] return result
Convert the config for the platform defaults.
def convert_default(config: dict[str, Any]) -> dict[str, Any]: """Convert the config for the platform defaults.""" return convert_with_map(config, {CONF_FADE: dyn_const.CONF_FADE})
Convert the config for a template.
def convert_template(config: dict[str, Any]) -> dict[str, Any]: """Convert the config for a template.""" my_map = { CONF_ROOM_ON: dyn_const.CONF_ROOM_ON, CONF_ROOM_OFF: dyn_const.CONF_ROOM_OFF, CONF_CHANNEL_COVER: dyn_const.CONF_CHANNEL_COVER, CONF_DEVICE_CLASS: dyn_const.CONF_DEVICE_CLASS, CONF_OPEN_PRESET: dyn_const.CONF_OPEN_PRESET, CONF_CLOSE_PRESET: dyn_const.CONF_CLOSE_PRESET, CONF_STOP_PRESET: dyn_const.CONF_STOP_PRESET, CONF_DURATION: dyn_const.CONF_DURATION, CONF_TILT_TIME: dyn_const.CONF_TILT_TIME, } return convert_with_map(config, my_map)
Convert a config dict by replacing component consts with library consts.
def convert_config( config: dict[str, Any] | MappingProxyType[str, Any], ) -> dict[str, Any]: """Convert a config dict by replacing component consts with library consts.""" my_map = { CONF_NAME: dyn_const.CONF_NAME, CONF_HOST: dyn_const.CONF_HOST, CONF_PORT: dyn_const.CONF_PORT, CONF_AUTO_DISCOVER: dyn_const.CONF_AUTO_DISCOVER, CONF_POLL_TIMER: dyn_const.CONF_POLL_TIMER, } result = convert_with_map(config, my_map) if CONF_AREA in config: result[dyn_const.CONF_AREA] = { area: convert_area(area_conf) for (area, area_conf) in config[CONF_AREA].items() } if CONF_DEFAULT in config: result[dyn_const.CONF_DEFAULT] = convert_default(config[CONF_DEFAULT]) if CONF_ACTIVE in config: result[dyn_const.CONF_ACTIVE] = ACTIVE_MAP[config[CONF_ACTIVE]] if CONF_PRESET in config: result[dyn_const.CONF_PRESET] = { preset: convert_preset(preset_conf) for (preset, preset_conf) in config[CONF_PRESET].items() } if CONF_TEMPLATE in config: result[dyn_const.CONF_TEMPLATE] = { TEMPLATE_MAP[template]: convert_template(template_conf) for (template, template_conf) in config[CONF_TEMPLATE].items() } return result
Record the async_add_entities function to add them later when received from Dynalite.
def async_setup_entry_base( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, platform: str, entity_from_device: Callable, ) -> None: """Record the async_add_entities function to add them later when received from Dynalite.""" LOGGER.debug("Setting up %s entry = %s", platform, config_entry.data) bridge = hass.data[DOMAIN][config_entry.entry_id] @callback def async_add_entities_platform(devices): # assumes it is called with a single platform added_entities = [entity_from_device(device, bridge) for device in devices] async_add_entities(added_entities) bridge.register_add_devices(platform, async_add_entities_platform)
Retrieve the Dynalite config for the frontend.
def get_dynalite_config( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Retrieve the Dynalite config for the frontend.""" entries = hass.config_entries.async_entries(DOMAIN) relevant_config = { entry.entry_id: { conf: entry.data[conf] for conf in RELEVANT_CONFS if conf in entry.data } for entry in entries } dynalite_defaults = { "DEFAULT_NAME": DEFAULT_NAME, "DEVICE_CLASSES": DEVICE_CLASSES, "DEFAULT_PORT": DEFAULT_PORT, } connection.send_result( msg["id"], {"config": relevant_config, "default": dynalite_defaults} )
Retrieve the Dynalite config for the frontend.
def save_dynalite_config( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Retrieve the Dynalite config for the frontend.""" entry_id = msg["entry_id"] entry = hass.config_entries.async_get_entry(entry_id) if not entry: LOGGER.error( "Dynalite - received updated config for invalid entry - %s", entry_id ) connection.send_result(msg["id"], {"error": True}) return message_conf = msg["config"] message_data = { conf: message_conf[conf] for conf in RELEVANT_CONFS if conf in message_conf } LOGGER.info("Updating Dynalite config entry") hass.config_entries.async_update_entry(entry, data=message_data) connection.send_result(msg["id"], {})
Test if value is a string of digits, aka an integer.
def num_string(value: str | int) -> str: """Test if value is a string of digits, aka an integer.""" new_value = str(value) if new_value.isdigit(): return new_value raise vol.Invalid("Not a string with numbers")
Validate that template parameters are only used if area is using the relevant template.
def validate_area(config: dict[str, Any]) -> dict[str, Any]: """Validate that template parameters are only used if area is using the relevant template.""" conf_set = set() for configs in DEFAULT_TEMPLATES.values(): for conf in configs: conf_set.add(conf) if config.get(CONF_TEMPLATE): for conf in DEFAULT_TEMPLATES[config[CONF_TEMPLATE]]: conf_set.remove(conf) for conf in conf_set: if config.get(conf): raise vol.Invalid( f"{conf} should not be part of area {config[CONF_NAME]} config" ) return config
Force measure key to always be a list.
def get_measures(station_data): """Force measure key to always be a list.""" if "measures" not in station_data: return [] if isinstance(station_data["measures"], dict): return [station_data["measures"]] return station_data["measures"]
Get the gas price for a given hour. Args: data: The data object. hours: The number of hours to add to the current time. Returns: The gas market price value.
def get_gas_price(data: EasyEnergyData, hours: int) -> float | None: """Get the gas price for a given hour. Args: data: The data object. hours: The number of hours to add to the current time. Returns: The gas market price value. """ if not data.gas_today: return None return data.gas_today.price_at_time( data.gas_today.utcnow() + timedelta(hours=hours) )
Return the gas value. Args: data: The data object. hours: The number of hours to add to the current time. Returns: The gas market price value.
def get_gas_price(data: EasyEnergyData, hours: int) -> float | None: """Return the gas value. Args: data: The data object. hours: The number of hours to add to the current time. Returns: The gas market price value. """ if data.gas_today is None: return None return data.gas_today.price_at_time( data.gas_today.utcnow() + timedelta(hours=hours) )
Get date.
def __get_date(date_input: str | None) -> date | datetime: """Get date.""" if not date_input: return dt_util.now().date() if value := dt_util.parse_datetime(date_input): return value raise ServiceValidationError( "Invalid datetime provided.", translation_domain=DOMAIN, translation_key="invalid_date", translation_placeholders={ "date": date_input, }, )
Serialize prices to service response.
def __serialize_prices(prices: list[dict[str, float | datetime]]) -> ServiceResponse: """Serialize prices to service response.""" return { "prices": [ { key: str(value) if isinstance(value, datetime) else value for key, value in timestamp_price.items() } for timestamp_price in prices ] }
Get the coordinator from the entry.
def __get_coordinator( hass: HomeAssistant, call: ServiceCall ) -> EasyEnergyDataUpdateCoordinator: """Get the coordinator from the entry.""" entry_id: str = call.data[ATTR_CONFIG_ENTRY] entry: ConfigEntry | None = hass.config_entries.async_get_entry(entry_id) if not entry: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_config_entry", translation_placeholders={ "config_entry": entry_id, }, ) if entry.state != ConfigEntryState.LOADED: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="unloaded_config_entry", translation_placeholders={ "config_entry": entry.title, }, ) coordinator: EasyEnergyDataUpdateCoordinator = hass.data[DOMAIN][entry_id] return coordinator
Set up services for easyEnergy integration.
def async_setup_services(hass: HomeAssistant) -> None: """Set up services for easyEnergy integration.""" hass.services.async_register( DOMAIN, GAS_SERVICE_NAME, partial(__get_prices, hass=hass, price_type=PriceType.GAS), schema=SERVICE_SCHEMA, supports_response=SupportsResponse.ONLY, ) hass.services.async_register( DOMAIN, ENERGY_USAGE_SERVICE_NAME, partial(__get_prices, hass=hass, price_type=PriceType.ENERGY_USAGE), schema=SERVICE_SCHEMA, supports_response=SupportsResponse.ONLY, ) hass.services.async_register( DOMAIN, ENERGY_RETURN_SERVICE_NAME, partial(__get_prices, hass=hass, price_type=PriceType.ENERGY_RETURN), schema=SERVICE_SCHEMA, supports_response=SupportsResponse.ONLY, )
Set up the Ebus sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Ebus sensor.""" if not discovery_info: return ebusd_api = hass.data[DOMAIN] monitored_conditions = discovery_info["monitored_conditions"] name = discovery_info["client_name"] add_entities( ( EbusdSensor(ebusd_api, discovery_info["sensor_types"][condition], name) for condition in monitored_conditions ), True, )
Verify eBusd config.
def verify_ebusd_config(config): """Verify eBusd config.""" circuit = config[CONF_CIRCUIT] for condition in config[CONF_MONITORED_CONDITIONS]: if condition not in SENSOR_TYPES[circuit]: raise vol.Invalid(f"Condition '{condition}' not in '{circuit}'.") return config
Set up the eBusd component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the eBusd component.""" _LOGGER.debug("Integration setup started") conf = config[DOMAIN] name = conf[CONF_NAME] circuit = conf[CONF_CIRCUIT] monitored_conditions = conf.get(CONF_MONITORED_CONDITIONS) server_address = (conf.get(CONF_HOST), conf.get(CONF_PORT)) try: ebusdpy.init(server_address) except (TimeoutError, OSError): return False hass.data[DOMAIN] = EbusdData(server_address, circuit) sensor_config = { CONF_MONITORED_CONDITIONS: monitored_conditions, "client_name": name, "sensor_types": SENSOR_TYPES[circuit], } load_platform(hass, Platform.SENSOR, DOMAIN, sensor_config, config) hass.services.register(DOMAIN, SERVICE_EBUSD_WRITE, hass.data[DOMAIN].write) _LOGGER.debug("Ebusd integration setup completed") return True
Set up the ecoal sensors.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the ecoal sensors.""" if discovery_info is None: return devices = [] ecoal_contr = hass.data[DATA_ECOAL_BOILER] for sensor_id in discovery_info: name = AVAILABLE_SENSORS[sensor_id] devices.append(EcoalTempSensor(ecoal_contr, name, sensor_id)) add_entities(devices, True)
Set up switches based on ecoal interface.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up switches based on ecoal interface.""" if discovery_info is None: return ecoal_contr = hass.data[DATA_ECOAL_BOILER] switches = [] for pump_id in discovery_info: name = AVAILABLE_PUMPS[pump_id] switches.append(EcoalSwitch(ecoal_contr, name, pump_id)) add_entities(switches, True)
Set up global ECoalController instance same for sensors and switches.
def setup(hass: HomeAssistant, hass_config: ConfigType) -> bool: """Set up global ECoalController instance same for sensors and switches.""" conf = hass_config[DOMAIN] host = conf[CONF_HOST] username = conf[CONF_USERNAME] passwd = conf[CONF_PASSWORD] # Creating ECoalController instance makes HTTP request to controller. ecoal_contr = ECoalController(host, username, passwd) if ecoal_contr.version is None: # Wrong credentials nor network config _LOGGER.error( "Unable to read controller status from %s@%s (wrong host/credentials)", username, host, ) return False _LOGGER.debug("Detected controller version: %r @%s", ecoal_contr.version, host) hass.data[DATA_ECOAL_BOILER] = ecoal_contr # Setup switches switches = conf[CONF_SWITCHES][CONF_MONITORED_CONDITIONS] load_platform(hass, Platform.SWITCH, DOMAIN, switches, hass_config) # Setup temp sensors sensors = conf[CONF_SENSORS][CONF_MONITORED_CONDITIONS] load_platform(hass, Platform.SENSOR, DOMAIN, sensors, hass_config) return True
Get the Ecobee notification service.
def get_service( hass: HomeAssistant, config: ConfigType, discovery_info: DiscoveryInfoType | None = None, ) -> EcobeeNotificationService | None: """Get the Ecobee notification service.""" if discovery_info is None: return None data: EcobeeData = hass.data[DOMAIN] return EcobeeNotificationService(data.ecobee)
Ensure an issue is registered.
def migrate_notify_issue(hass: HomeAssistant) -> None: """Ensure an issue is registered.""" ir.async_create_issue( hass, DOMAIN, "migrate_notify", breaks_in_ha_version="2024.11.0", issue_domain=NOTIFY_DOMAIN, is_fixable=True, is_persistent=True, translation_key="migrate_notify", severity=ir.IssueSeverity.WARNING, )
Validate a date_string as valid for the ecobee API.
def ecobee_date(date_string): """Validate a date_string as valid for the ecobee API.""" try: datetime.strptime(date_string, "%Y-%m-%d") except ValueError as err: raise vol.Invalid("Date does not match ecobee date format YYYY-MM-DD") from err return date_string
Validate a time_string as valid for the ecobee API.
def ecobee_time(time_string): """Validate a time_string as valid for the ecobee API.""" try: datetime.strptime(time_string, "%H:%M:%S") except ValueError as err: raise vol.Invalid( "Time does not match ecobee 24-hour time format HH:MM:SS" ) from err return time_string
Determine if the given start and end dates from the ecobee API represent an indefinite hold. This is not documented in the API, so a rough heuristic is used where a hold over 1 year is considered indefinite.
def is_indefinite_hold(start_date_string: str, end_date_string: str) -> bool: """Determine if the given start and end dates from the ecobee API represent an indefinite hold. This is not documented in the API, so a rough heuristic is used where a hold over 1 year is considered indefinite. """ return date.fromisoformat(end_date_string) - date.fromisoformat( start_date_string ) > timedelta(days=365)
Process a single ecobee API forecast to return expected values.
def _process_forecast(json): """Process a single ecobee API forecast to return expected values.""" forecast = {} try: forecast[ATTR_FORECAST_CONDITION] = ECOBEE_WEATHER_SYMBOL_TO_HASS[ json["weatherSymbol"] ] if json["tempHigh"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_NATIVE_TEMP] = float(json["tempHigh"]) / 10 if json["tempLow"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_NATIVE_TEMP_LOW] = float(json["tempLow"]) / 10 if json["windBearing"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_WIND_BEARING] = int(json["windBearing"]) if json["windSpeed"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_NATIVE_WIND_SPEED] = int(json["windSpeed"]) except (ValueError, IndexError, KeyError): return None if forecast: return forecast return None
Validate an URL and return error dictionary.
def _validate_url( value: str, field_name: str, schema_list: set[str], ) -> dict[str, str]: """Validate an URL and return error dictionary.""" if urlparse(value).scheme not in schema_list: return {field_name: f"invalid_url_schema_{field_name}"} try: vol.Schema(vol.Url())(value) except vol.Invalid: return {field_name: "invalid_url"} return {}
Get client device id.
def get_client_device_id(hass: HomeAssistant, self_hosted: bool) -> str: """Get client device id.""" if self_hosted: return f"HA-{slugify(hass.config.location_name)}" return "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(8) )
Return all supported entities for all devices.
def get_supported_entitites( controller: EcovacsController, entity_class: type[EcovacsDescriptionEntity], descriptions: tuple[EcovacsCapabilityEntityDescription, ...], ) -> list[EcovacsEntity]: """Return all supported entities for all devices.""" return [ entity_class(device, capability, description) for device in controller.devices(Capabilities) for description in descriptions if isinstance(device.capabilities, description.device_capabilities) if (capability := description.capability_fn(device.capabilities)) ]
Return the lower case name of the enum.
def get_name_key(enum: Enum) -> str: """Return the lower case name of the enum.""" return enum.name.lower()
Validate configuration, create devices and start monitoring thread.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Validate configuration, create devices and start monitoring thread.""" bt_device_id: int = config[CONF_BT_DEVICE_ID] beacons: dict[str, dict[str, str]] = config[CONF_BEACONS] devices: list[EddystoneTemp] = [] for dev_name, properties in beacons.items(): namespace = get_from_conf(properties, CONF_NAMESPACE, 20) instance = get_from_conf(properties, CONF_INSTANCE, 12) name = properties.get(CONF_NAME, dev_name) if instance is None or namespace is None: _LOGGER.error("Skipping %s", dev_name) continue devices.append(EddystoneTemp(name, namespace, instance)) if devices: mon = Monitor(hass, devices, bt_device_id) def monitor_stop(event: Event) -> None: """Stop the monitor thread.""" _LOGGER.info("Stopping scanner for Eddystone beacons") mon.stop() def monitor_start(event: Event) -> None: """Start the monitor thread.""" _LOGGER.info("Starting scanner for Eddystone beacons") mon.start() add_entities(devices) mon.start() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, monitor_stop) hass.bus.listen_once(EVENT_HOMEASSISTANT_START, monitor_start) else: _LOGGER.warning("No devices were added")
Retrieve value from config and validate length.
def get_from_conf(config: dict[str, str], config_key: str, length: int) -> str | None: """Retrieve value from config and validate length.""" string = config[config_key] if len(string) != length: _LOGGER.error( ( "Error in configuration parameter %s: Must be exactly %d " "bytes. Device will not be added" ), config_key, length / 2, ) return None return string
Find and return Edimax Smart Plugs.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Find and return Edimax Smart Plugs.""" host = config.get(CONF_HOST) auth = (config.get(CONF_USERNAME), config.get(CONF_PASSWORD)) name = config.get(CONF_NAME) add_entities([SmartPlugSwitch(SmartPlug(host, auth), name)], True)
Set up the Egardia Alarm Control Panael platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Egardia Alarm Control Panael platform.""" if discovery_info is None: return device = EgardiaAlarm( discovery_info["name"], hass.data[EGARDIA_DEVICE], discovery_info[CONF_REPORT_SERVER_ENABLED], discovery_info.get(CONF_REPORT_SERVER_CODES), discovery_info[CONF_REPORT_SERVER_PORT], ) add_entities([device], True)
Set up the Egardia platform.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Egardia platform.""" conf = config[DOMAIN] username = conf.get(CONF_USERNAME) password = conf.get(CONF_PASSWORD) host = conf.get(CONF_HOST) port = conf.get(CONF_PORT) version = conf.get(CONF_VERSION) rs_enabled = conf.get(CONF_REPORT_SERVER_ENABLED) rs_port = conf.get(CONF_REPORT_SERVER_PORT) try: device = hass.data[EGARDIA_DEVICE] = egardiadevice.EgardiaDevice( host, port, username, password, "", version ) except requests.exceptions.RequestException: _LOGGER.error( "An error occurred accessing your Egardia device. " "Please check configuration" ) return False except egardiadevice.UnauthorizedError: _LOGGER.error("Unable to authorize. Wrong password or username") return False # Set up the egardia server if enabled if rs_enabled: _LOGGER.debug("Setting up EgardiaServer") try: if EGARDIA_SERVER not in hass.data: server = egardiaserver.EgardiaServer("", rs_port) bound = server.bind() if not bound: raise OSError( "Binding error occurred while starting EgardiaServer." ) hass.data[EGARDIA_SERVER] = server server.start() def handle_stop_event(event): """Handle Home Assistant stop event.""" server.stop() # listen to Home Assistant stop event hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, handle_stop_event) except OSError: _LOGGER.error("Binding error occurred while starting EgardiaServer") return False discovery.load_platform( hass, Platform.ALARM_CONTROL_PANEL, DOMAIN, discovered=conf, hass_config=config ) # Get the sensors from the device and add those sensors = device.getsensors() discovery.load_platform( hass, Platform.BINARY_SENSOR, DOMAIN, {ATTR_DISCOVER_DEVICES: sensors}, config ) return True
Return the time a day forward if HOP end_time is in the past.
def _check_and_move_time(hop: Hop, time: str) -> datetime: """Return the time a day forward if HOP end_time is in the past.""" date_time = datetime.combine( dt_util.start_of_local_day(), datetime.strptime(time, "%I:%M %p").time(), dt_util.DEFAULT_TIME_ZONE, ) end_time = datetime.combine( dt_util.start_of_local_day(), datetime.strptime(hop.end.end_time, "%I:%M %p").time(), dt_util.DEFAULT_TIME_ZONE, ) if end_time < dt_util.now(): return date_time + timedelta(days=1) return date_time
Append the port only if its non-standard.
def _address_from_discovery(device: ElkSystem) -> str: """Append the port only if its non-standard.""" if device.port in STANDARD_PORTS: return device.ip_address return f"{device.ip_address}:{device.port}"
Update a config entry from a discovery.
def async_update_entry_from_discovery( hass: HomeAssistant, entry: config_entries.ConfigEntry, device: ElkSystem, ) -> bool: """Update a config entry from a discovery.""" if not entry.unique_id or ":" not in entry.unique_id: _LOGGER.debug("Adding unique id from discovery: %s", device) return hass.config_entries.async_update_entry( entry, unique_id=dr.format_mac(device.mac_address) ) _LOGGER.debug("Unique id is already present from discovery: %s", device) return False
Trigger config flows for discovered devices.
def async_trigger_discovery( hass: HomeAssistant, discovered_devices: list[ElkSystem], ) -> None: """Trigger config flows for discovered devices.""" for device in discovered_devices: discovery_flow.async_create_flow( hass, DOMAIN, context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY}, data=asdict(device), )
Describe logbook events.
def async_describe_events( hass: HomeAssistant, async_describe_event: Callable[[str, str, Callable[[Event], dict[str, str]]], None], ) -> None: """Describe logbook events.""" @callback def async_describe_button_event(event: Event) -> dict[str, str]: """Describe elkm1 logbook event.""" data = event.data keypad_name = data.get( ATTR_KEYPAD_NAME, data[ATTR_KEYPAD_ID] ) # added in 2022.6 return { LOGBOOK_ENTRY_NAME: f"Elk Keypad {keypad_name}", LOGBOOK_ENTRY_MESSAGE: f"pressed {data[ATTR_KEY_NAME]} ({data[ATTR_KEY]})", } async_describe_event( DOMAIN, EVENT_ELKM1_KEYPAD_KEY_PRESSED, async_describe_button_event )
Convert temperature to a state.
def temperature_to_state(temperature: int, undefined_temperature: int) -> str | None: """Convert temperature to a state.""" return f"{temperature}" if temperature > undefined_temperature else None
Return the hostname from a url.
def hostname_from_url(url: str) -> str: """Return the hostname from a url.""" return parse_url(url)[1]
Validate that a host is properly configured.
def _host_validator(config: dict[str, str]) -> dict[str, str]: """Validate that a host is properly configured.""" if config[CONF_HOST].startswith("elks://"): if CONF_USERNAME not in config or CONF_PASSWORD not in config: raise vol.Invalid("Specify username and password for elks://") elif not config[CONF_HOST].startswith("elk://") and not config[ CONF_HOST ].startswith("serial://"): raise vol.Invalid("Invalid host URL") return config
Validate that each m1 configured has a unique prefix. Uniqueness is determined case-independently.
def _has_all_unique_prefixes(value: list[dict[str, str]]) -> list[dict[str, str]]: """Validate that each m1 configured has a unique prefix. Uniqueness is determined case-independently. """ prefixes = [device[CONF_PREFIX] for device in value] schema = vol.Schema(vol.Unique()) schema(prefixes) return value
Search all config entries for a given prefix.
def _find_elk_by_prefix(hass: HomeAssistant, prefix: str) -> Elk | None: """Search all config entries for a given prefix.""" all_elk: dict[str, ELKM1Data] = hass.data[DOMAIN] for elk_data in all_elk.values(): if elk_data.prefix == prefix: return elk_data.elk return None
Get the ElkM1 panel from a service call.
def _async_get_elk_panel(hass: HomeAssistant, service: ServiceCall) -> Panel: """Get the ElkM1 panel from a service call.""" prefix = service.data["prefix"] elk = _find_elk_by_prefix(hass, prefix) if elk is None: raise HomeAssistantError(f"No ElkM1 with prefix '{prefix}' found") return elk.panel
Create ElkM1 services.
def _create_elk_services(hass: HomeAssistant) -> None: """Create ElkM1 services.""" @callback def _speak_word_service(service: ServiceCall) -> None: _async_get_elk_panel(hass, service).speak_word(service.data["number"]) @callback def _speak_phrase_service(service: ServiceCall) -> None: _async_get_elk_panel(hass, service).speak_phrase(service.data["number"]) @callback def _set_time_service(service: ServiceCall) -> None: _async_get_elk_panel(hass, service).set_time(dt_util.now()) hass.services.async_register( DOMAIN, "speak_word", _speak_word_service, SPEAK_SERVICE_SCHEMA ) hass.services.async_register( DOMAIN, "speak_phrase", _speak_phrase_service, SPEAK_SERVICE_SCHEMA ) hass.services.async_register( DOMAIN, "set_time", _set_time_service, SET_TIME_SERVICE_SCHEMA )
Create the ElkM1 devices of a particular class.
def create_elk_entities( elk_data: ELKM1Data, elk_elements: Iterable[Element], element_type: str, class_: Any, entities: list[ElkEntity], ) -> list[ElkEntity] | None: """Create the ElkM1 devices of a particular class.""" auto_configure = elk_data.auto_configure if not auto_configure and not elk_data.config[element_type]["enabled"]: return None elk = elk_data.elk _LOGGER.debug("Creating elk entities for %s", elk) for element in elk_elements: if auto_configure: if not element.configured: continue # Only check the included list if auto configure is not elif not elk_data.config[element_type]["included"][element.index]: continue entities.append(class_(element, elk, elk_data)) return entities
Return the direct API url given the base URI.
def get_direct_api_url(host: str, port: int, use_ssl: bool) -> str: """Return the direct API url given the base URI.""" schema = "https" if use_ssl else "http" return f"{schema}://{host}:{port}/{ELMAX_LOCAL_API_PATH}"
Create a custom SSL context for direct-api verification.
def build_direct_ssl_context(cadata: str) -> ssl.SSLContext: """Create a custom SSL context for direct-api verification.""" context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) context.check_hostname = False context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(cadata=cadata) return context
Check whether the given API version is supported.
def check_local_version_supported(api_version: str | None) -> bool: """Check whether the given API version is supported.""" if api_version is None: return False return version.parse(api_version) >= version.parse(MIN_APIV2_SUPPORTED_VERSION)
Set up the PCA switch platform.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the PCA switch platform.""" if discovery_info is None: return serial_device = discovery_info["device"] try: pca = pypca.PCA(serial_device) pca.open() entities = [SmartPlugSwitch(pca, device) for device in pca.get_devices()] add_entities(entities, True) except SerialException as exc: _LOGGER.warning("Unable to open serial port: %s", exc) return hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, pca.close) pca.start_scan()
Set up the PCA switch platform.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the PCA switch platform.""" for platform in ELV_PLATFORMS: discovery.load_platform( hass, platform, DOMAIN, {"device": config[DOMAIN][CONF_DEVICE]}, config ) return True
Return unique identifier for feed / sensor.
def get_id(sensorid, feedtag, feedname, feedid, feeduserid): """Return unique identifier for feed / sensor.""" return f"emoncms{sensorid}_{feedtag}_{feedname}_{feedid}_{feeduserid}"
Set up the Emoncms sensor.
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Emoncms sensor.""" apikey = config.get(CONF_API_KEY) url = config.get(CONF_URL) sensorid = config.get(CONF_ID) value_template = config.get(CONF_VALUE_TEMPLATE) config_unit = config.get(CONF_UNIT_OF_MEASUREMENT) exclude_feeds = config.get(CONF_EXCLUDE_FEEDID) include_only_feeds = config.get(CONF_ONLY_INCLUDE_FEEDID) sensor_names = config.get(CONF_SENSOR_NAMES) interval = config.get(CONF_SCAN_INTERVAL) if value_template is not None: value_template.hass = hass data = EmonCmsData(hass, url, apikey, interval) data.update() if data.data is None: return sensors = [] for elem in data.data: if exclude_feeds is not None and int(elem["id"]) in exclude_feeds: continue if include_only_feeds is not None and int(elem["id"]) not in include_only_feeds: continue name = None if sensor_names is not None: name = sensor_names.get(int(elem["id"]), None) if unit := elem.get("unit"): unit_of_measurement = unit else: unit_of_measurement = config_unit sensors.append( EmonCmsSensor( hass, data, name, value_template, unit_of_measurement, str(sensorid), elem, ) ) add_entities(sensors)
Set up the Emoncms history component.
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Emoncms history component.""" conf = config[DOMAIN] whitelist = conf.get(CONF_WHITELIST) def send_data(url, apikey, node, payload): """Send payload data to Emoncms.""" try: fullurl = f"{url}/input/post.json" data = {"apikey": apikey, "data": payload} parameters = {"node": node} req = requests.post( fullurl, params=parameters, data=data, allow_redirects=True, timeout=5 ) except requests.exceptions.RequestException: _LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl) else: if req.status_code != HTTPStatus.OK: _LOGGER.error( "Error saving data %s to %s (http status code = %d)", payload, fullurl, req.status_code, ) def update_emoncms(time): """Send whitelisted entities states regularly to Emoncms.""" payload_dict = {} for entity_id in whitelist: state = hass.states.get(entity_id) if state is None or state.state in (STATE_UNKNOWN, "", STATE_UNAVAILABLE): continue try: payload_dict[entity_id] = state_helper.state_as_number(state) except ValueError: continue if payload_dict: payload = "{{{}}}".format( ",".join(f"{key}:{val}" for key, val in payload_dict.items()) ) send_data( conf.get(CONF_URL), conf.get(CONF_API_KEY), str(conf.get(CONF_INPUTNODE)), payload, ) track_point_in_time( hass, update_emoncms, time + timedelta(seconds=conf.get(CONF_SCAN_INTERVAL)) ) update_emoncms(dt_util.utcnow()) return True
Short version of the mac.
def short_mac(mac): """Short version of the mac.""" return "".join(mac.split(":")[3:]).upper()
Name from short mac.
def name_short_mac(short_mac): """Name from short mac.""" return f"Emonitor {short_mac}"
Check if remote address is allowed.
def _remote_is_allowed(address: str) -> bool: """Check if remote address is allowed.""" return is_local(ip_address(address))
Retrieve and convert state and brightness values for an entity.
def get_entity_state_dict(config: Config, entity: State) -> dict[str, Any]: """Retrieve and convert state and brightness values for an entity.""" cached_state_entry = config.cached_states.get(entity.entity_id, None) cached_state = None # Check if we have a cached entry, and if so if it hasn't expired. if cached_state_entry is not None: entry_state, entry_time = cached_state_entry if entry_time is None: # Handle the case where the entity is listed in config.off_maps_to_on_domains. cached_state = entry_state elif time.time() - entry_time < STATE_CACHED_TIMEOUT and entry_state[ STATE_ON ] == _hass_to_hue_state(entity): # We only want to use the cache if the actual state of the entity # is in sync so that it can be detected as an error by Alexa. cached_state = entry_state else: # Remove the now stale cached entry. config.cached_states.pop(entity.entity_id) if cached_state is None: return _build_entity_state_dict(entity) data: dict[str, Any] = cached_state # Make sure brightness is valid if data[STATE_BRIGHTNESS] is None: data[STATE_BRIGHTNESS] = HUE_API_STATE_BRI_MAX if data[STATE_ON] else 0 # Make sure hue/saturation are valid if (data[STATE_HUE] is None) or (data[STATE_SATURATION] is None): data[STATE_HUE] = 0 data[STATE_SATURATION] = 0 # If the light is off, set the color to off if data[STATE_BRIGHTNESS] == 0: data[STATE_HUE] = 0 data[STATE_SATURATION] = 0 _clamp_values(data) return data
Build a state dict for an entity.
def _build_entity_state_dict(entity: State) -> dict[str, Any]: """Build a state dict for an entity.""" is_on = _hass_to_hue_state(entity) data: dict[str, Any] = { STATE_ON: is_on, STATE_BRIGHTNESS: None, STATE_HUE: None, STATE_SATURATION: None, STATE_COLOR_TEMP: None, } attributes = entity.attributes if is_on: data[STATE_BRIGHTNESS] = hass_to_hue_brightness( attributes.get(ATTR_BRIGHTNESS) or 0 ) if (hue_sat := attributes.get(ATTR_HS_COLOR)) is not None: hue = hue_sat[0] sat = hue_sat[1] # Convert hass hs values back to hue hs values data[STATE_HUE] = int((hue / 360.0) * HUE_API_STATE_HUE_MAX) data[STATE_SATURATION] = int((sat / 100.0) * HUE_API_STATE_SAT_MAX) else: data[STATE_HUE] = HUE_API_STATE_HUE_MIN data[STATE_SATURATION] = HUE_API_STATE_SAT_MIN data[STATE_COLOR_TEMP] = attributes.get(ATTR_COLOR_TEMP) or 0 else: data[STATE_BRIGHTNESS] = 0 data[STATE_HUE] = 0 data[STATE_SATURATION] = 0 data[STATE_COLOR_TEMP] = 0 if entity.domain == climate.DOMAIN: temperature = attributes.get(ATTR_TEMPERATURE, 0) # Convert 0-100 to 0-254 data[STATE_BRIGHTNESS] = round(temperature * HUE_API_STATE_BRI_MAX / 100) elif entity.domain == humidifier.DOMAIN: humidity = attributes.get(ATTR_HUMIDITY, 0) # Convert 0-100 to 0-254 data[STATE_BRIGHTNESS] = round(humidity * HUE_API_STATE_BRI_MAX / 100) elif entity.domain == media_player.DOMAIN: level = attributes.get(ATTR_MEDIA_VOLUME_LEVEL, 1.0 if is_on else 0.0) # Convert 0.0-1.0 to 0-254 data[STATE_BRIGHTNESS] = round(min(1.0, level) * HUE_API_STATE_BRI_MAX) elif entity.domain == fan.DOMAIN: percentage = attributes.get(ATTR_PERCENTAGE) or 0 # Convert 0-100 to 0-254 data[STATE_BRIGHTNESS] = round(percentage * HUE_API_STATE_BRI_MAX / 100) elif entity.domain == cover.DOMAIN: level = attributes.get(ATTR_CURRENT_POSITION, 0) data[STATE_BRIGHTNESS] = round(level / 100 * HUE_API_STATE_BRI_MAX) _clamp_values(data) return data
Clamp brightness, hue, saturation, and color temp to valid values.
def _clamp_values(data: dict[str, Any]) -> None: """Clamp brightness, hue, saturation, and color temp to valid values.""" for key, v_min, v_max in ( (STATE_BRIGHTNESS, HUE_API_STATE_BRI_MIN, HUE_API_STATE_BRI_MAX), (STATE_HUE, HUE_API_STATE_HUE_MIN, HUE_API_STATE_HUE_MAX), (STATE_SATURATION, HUE_API_STATE_SAT_MIN, HUE_API_STATE_SAT_MAX), (STATE_COLOR_TEMP, HUE_API_STATE_CT_MIN, HUE_API_STATE_CT_MAX), ): if data[key] is not None: data[key] = max(v_min, min(data[key], v_max))
Return the emulated_hue unique id for the entity_id.
def _entity_unique_id(entity_id: str) -> str: """Return the emulated_hue unique id for the entity_id.""" unique_id = hashlib.md5(entity_id.encode()).hexdigest() return ( f"00:{unique_id[0:2]}:{unique_id[2:4]}:" f"{unique_id[4:6]}:{unique_id[6:8]}:{unique_id[8:10]}:" f"{unique_id[10:12]}:{unique_id[12:14]}-{unique_id[14:16]}" )
Convert an entity to its Hue bridge JSON representation.
def state_to_json(config: Config, state: State) -> dict[str, Any]: """Convert an entity to its Hue bridge JSON representation.""" color_modes = state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) or [] unique_id = _entity_unique_id(state.entity_id) state_dict = get_entity_state_dict(config, state) json_state: dict[str, str | bool | int] = { HUE_API_STATE_ON: state_dict[STATE_ON], "reachable": state.state != STATE_UNAVAILABLE, "mode": "homeautomation", } retval: dict[str, str | dict[str, str | bool | int]] = { "state": json_state, "name": config.get_entity_name(state), "uniqueid": unique_id, "manufacturername": "Home Assistant", "swversion": "123", } is_light = state.domain == light.DOMAIN color_supported = is_light and light.color_supported(color_modes) color_temp_supported = is_light and light.color_temp_supported(color_modes) if color_supported and color_temp_supported: # Extended Color light (Zigbee Device ID: 0x0210) # Same as Color light, but which supports additional setting of color temperature retval["type"] = "Extended color light" retval["modelid"] = "HASS231" json_state.update( { HUE_API_STATE_BRI: state_dict[STATE_BRIGHTNESS], HUE_API_STATE_HUE: state_dict[STATE_HUE], HUE_API_STATE_SAT: state_dict[STATE_SATURATION], HUE_API_STATE_CT: state_dict[STATE_COLOR_TEMP], HUE_API_STATE_EFFECT: "none", } ) if state_dict[STATE_HUE] > 0 or state_dict[STATE_SATURATION] > 0: json_state[HUE_API_STATE_COLORMODE] = "hs" else: json_state[HUE_API_STATE_COLORMODE] = "ct" elif color_supported: # Color light (Zigbee Device ID: 0x0200) # Supports on/off, dimming and color control (hue/saturation, enhanced hue, color loop and XY) retval["type"] = "Color light" retval["modelid"] = "HASS213" json_state.update( { HUE_API_STATE_BRI: state_dict[STATE_BRIGHTNESS], HUE_API_STATE_COLORMODE: "hs", HUE_API_STATE_HUE: state_dict[STATE_HUE], HUE_API_STATE_SAT: state_dict[STATE_SATURATION], HUE_API_STATE_EFFECT: "none", } ) elif color_temp_supported: # Color temperature light (Zigbee Device ID: 0x0220) # Supports groups, scenes, on/off, dimming, and setting of a color temperature retval["type"] = "Color temperature light" retval["modelid"] = "HASS312" json_state.update( { HUE_API_STATE_COLORMODE: "ct", HUE_API_STATE_CT: state_dict[STATE_COLOR_TEMP], HUE_API_STATE_BRI: state_dict[STATE_BRIGHTNESS], } ) elif state_supports_hue_brightness(state, color_modes): # Dimmable light (Zigbee Device ID: 0x0100) # Supports groups, scenes, on/off and dimming retval["type"] = "Dimmable light" retval["modelid"] = "HASS123" json_state.update({HUE_API_STATE_BRI: state_dict[STATE_BRIGHTNESS]}) elif not config.lights_all_dimmable: # On/Off light (ZigBee Device ID: 0x0000) # Supports groups, scenes and on/off control retval["type"] = "On/Off light" retval["productname"] = "On/Off light" retval["modelid"] = "HASS321" else: # Dimmable light (Zigbee Device ID: 0x0100) # Supports groups, scenes, on/off and dimming # Reports fixed brightness for compatibility with Alexa. retval["type"] = "Dimmable light" retval["modelid"] = "HASS123" json_state.update({HUE_API_STATE_BRI: HUE_API_STATE_BRI_MAX}) return retval
Return True if the state supports brightness.
def state_supports_hue_brightness( state: State, color_modes: Iterable[ColorMode] ) -> bool: """Return True if the state supports brightness.""" domain = state.domain if domain == light.DOMAIN: return light.brightness_supported(color_modes) if not (required_feature := DIMMABLE_SUPPORTED_FEATURES_BY_DOMAIN.get(domain)): return False features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) enum = ENTITY_FEATURES_BY_DOMAIN[domain] features = enum(features) if type(features) is int else features # noqa: E721 return required_feature in features
Create a success response for an attribute set on a light.
def create_hue_success_response( entity_number: str, attr: str, value: str ) -> dict[str, Any]: """Create a success response for an attribute set on a light.""" success_key = f"/lights/{entity_number}/state/{attr}" return {"success": {success_key: value}}
Create a config resource.
def create_config_model(config: Config, request: web.Request) -> dict[str, Any]: """Create a config resource.""" return { "name": "HASS BRIDGE", "mac": "00:00:00:00:00:00", "swversion": "01003542", "apiversion": "1.17.0", "whitelist": {HUE_API_USERNAME: {"name": "HASS BRIDGE"}}, "ipaddress": f"{config.advertise_ip}:{config.advertise_port}", "linkbutton": True, }
Create a list of all entities.
def create_list_of_entities(config: Config, request: web.Request) -> dict[str, Any]: """Create a list of all entities.""" hass = request.app[KEY_HASS] return { config.entity_id_to_number(entity_id): state_to_json(config, state) for entity_id in config.get_exposed_entity_ids() if (state := hass.states.get(entity_id)) }
Convert hue brightness 1..254 to hass format 0..255.
def hue_brightness_to_hass(value: int) -> int: """Convert hue brightness 1..254 to hass format 0..255.""" return min(255, round((value / HUE_API_STATE_BRI_MAX) * 255))
Convert hass brightness 0..255 to hue 1..254 scale.
def hass_to_hue_brightness(value: int) -> int: """Convert hass brightness 0..255 to hue 1..254 scale.""" return max(1, round((value / 255) * HUE_API_STATE_BRI_MAX))
Convert hass entity states to simple True/False on/off state for Hue.
def _hass_to_hue_state(entity: State) -> bool: """Convert hass entity states to simple True/False on/off state for Hue.""" return entity.state != _OFF_STATES.get(entity.domain, STATE_OFF)
Determine the system wide unique_id for an entity.
def get_system_unique_id(entity: er.RegistryEntry): """Determine the system wide unique_id for an entity.""" return f"{entity.platform}.{entity.domain}.{entity.unique_id}"
Produce list of plug devices from config entities.
def get_plug_devices(hass, entity_configs): """Produce list of plug devices from config entities.""" for entity_id, entity_config in entity_configs.items(): if (state := hass.states.get(entity_id)) is None: continue name = entity_config.get(CONF_NAME, state.name) if state.state == STATE_ON or state.domain == SENSOR_DOMAIN: if CONF_POWER in entity_config: power_val = entity_config[CONF_POWER] if isinstance(power_val, (float, int)): power = float(power_val) elif isinstance(power_val, str): power = float(hass.states.get(power_val).state) elif isinstance(power_val, Template): power = float(power_val.async_render()) elif state.domain == SENSOR_DOMAIN: power = float(state.state) else: power = 0.0 last_changed = state.last_changed.timestamp() yield PlugInstance( entity_config[CONF_UNIQUE_ID], start_time=last_changed, alias=name, power=power, )
Return a set of the configured servers.
def configured_servers(hass): """Return a set of the configured servers.""" return { entry.data[CONF_NAME] for entry in hass.config_entries.async_entries(DOMAIN) }
Ensure we use a single price source.
def _flow_from_ensure_single_price( val: FlowFromGridSourceType, ) -> FlowFromGridSourceType: """Ensure we use a single price source.""" if ( val["entity_energy_price"] is not None and val["number_energy_price"] is not None ): raise vol.Invalid("Define either an entity or a fixed number for the price") return val
Generate a validator that ensures a value is only used once.
def _generate_unique_value_validator(key: str) -> Callable[[list[dict]], list[dict]]: """Generate a validator that ensures a value is only used once.""" def validate_uniqueness( val: list[dict], ) -> list[dict]: """Ensure that the user doesn't add duplicate values.""" counts = Counter(flow_from[key] for flow_from in val) for value, count in counts.items(): if count > 1: raise vol.Invalid(f"Cannot specify {value} more than once") return val return validate_uniqueness
Validate that we don't have too many of certain types.
def check_type_limits(value: list[SourceType]) -> list[SourceType]: """Validate that we don't have too many of certain types.""" types = Counter([val["type"] for val in value]) if types.get("grid", 0) > 1: raise vol.Invalid("You cannot have more than 1 grid source") return value