response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Try to resolve the a location from a supplied name or entity_id. Will recursively resolve an entity if pointed to by the state of the supplied entity. Returns coordinates in the form of '90.000,180.000', an address or the state of the last resolved entity.
def find_coordinates( hass: HomeAssistant, name: str, recursion_history: list | None = None ) -> str | None: """Try to resolve the a location from a supplied name or entity_id. Will recursively resolve an entity if pointed to by the state of the supplied entity. Returns coordinates in the form of '90.000,180.000', an address or the state of the last resolved entity. """ # Check if a friendly name of a zone was supplied if (zone_coords := resolve_zone(hass, name)) is not None: return zone_coords # Check if an entity_id was supplied. if (entity_state := hass.states.get(name)) is None: _LOGGER.debug("Unable to find entity %s", name) return name # Check if the entity_state has location attributes if has_location(entity_state): return _get_location_from_attributes(entity_state) # Check if entity_state is a zone zone_entity = hass.states.get(f"zone.{entity_state.state}") if has_location(zone_entity): # type: ignore[arg-type] _LOGGER.debug( "%s is in %s, getting zone location", name, zone_entity.entity_id, # type: ignore[union-attr] ) return _get_location_from_attributes(zone_entity) # type: ignore[arg-type] # Check if entity_state is a friendly name of a zone if (zone_coords := resolve_zone(hass, entity_state.state)) is not None: return zone_coords # Check if entity_state is an entity_id if recursion_history is None: recursion_history = [] recursion_history.append(name) if entity_state.state in recursion_history: _LOGGER.error( ( "Circular reference detected while trying to find coordinates of an" " entity. The state of %s has already been checked" ), entity_state.state, ) return None _LOGGER.debug("Getting nested entity for state: %s", entity_state.state) nested_entity = hass.states.get(entity_state.state) if nested_entity is not None: _LOGGER.debug("Resolving nested entity_id: %s", entity_state.state) return find_coordinates(hass, entity_state.state, recursion_history) # Might be an address, coordinates or anything else. # This has to be checked by the caller. return entity_state.state
Get a lat/long from a zones friendly_name. None is returned if no zone is found by that friendly_name.
def resolve_zone(hass: HomeAssistant, zone_name: str) -> str | None: """Get a lat/long from a zones friendly_name. None is returned if no zone is found by that friendly_name. """ states = hass.states.async_all("zone") for state in states: if state.name == zone_name: return _get_location_from_attributes(state) return None
Get the lat/long string from an entities attributes.
def _get_location_from_attributes(entity_state: State) -> str: """Get the lat/long string from an entities attributes.""" attr = entity_state.attributes return f"{attr.get(ATTR_LATITUDE)},{attr.get(ATTR_LONGITUDE)}"
Test if the current request is internal.
def is_internal_request(hass: HomeAssistant) -> bool: """Test if the current request is internal.""" try: get_url( hass, allow_external=False, allow_cloud=False, require_current_request=True ) except NoURLAvailableError: return False return True
Get URL for home assistant within supervisor network.
def get_supervisor_network_url( hass: HomeAssistant, *, allow_ssl: bool = False ) -> str | None: """Get URL for home assistant within supervisor network.""" # Local import to avoid circular dependencies # pylint: disable-next=import-outside-toplevel from homeassistant.components.hassio import is_hassio if hass.config.api is None or not is_hassio(hass): return None scheme = "http" if hass.config.api.use_ssl: # Certificate won't be valid for hostname so this URL usually won't work if not allow_ssl: return None scheme = "https" return str( yarl.URL.build( scheme=scheme, host=SUPERVISOR_NETWORK_HOST, port=hass.config.api.port, ) )
Return if the URL points at this Home Assistant instance.
def is_hass_url(hass: HomeAssistant, url: str) -> bool: """Return if the URL points at this Home Assistant instance.""" parsed = yarl.URL(url) if not parsed.is_absolute(): return False if parsed.is_default_port(): parsed = parsed.with_port(None) def host_ip() -> str | None: if hass.config.api is None or is_loopback(ip_address(hass.config.api.local_ip)): return None return str( yarl.URL.build( scheme="http", host=hass.config.api.local_ip, port=hass.config.api.port ) ) def cloud_url() -> str | None: try: return _get_cloud_url(hass) except NoURLAvailableError: return None potential_base_factory: Callable[[], str | None] for potential_base_factory in ( lambda: hass.config.internal_url, lambda: hass.config.external_url, cloud_url, host_ip, lambda: get_supervisor_network_url(hass, allow_ssl=True), ): potential_base = potential_base_factory() if potential_base is None: continue potential_parsed = yarl.URL(normalize_url(potential_base)) if ( parsed.scheme == potential_parsed.scheme and parsed.authority == potential_parsed.authority ): return True return False
Get a URL to this instance.
def get_url( hass: HomeAssistant, *, require_current_request: bool = False, require_ssl: bool = False, require_standard_port: bool = False, require_cloud: bool = False, allow_internal: bool = True, allow_external: bool = True, allow_cloud: bool = True, allow_ip: bool | None = None, prefer_external: bool | None = None, prefer_cloud: bool = False, ) -> str: """Get a URL to this instance.""" if require_current_request and http.current_request.get() is None: raise NoURLAvailableError if prefer_external is None: prefer_external = hass.config.api is not None and hass.config.api.use_ssl if allow_ip is None: allow_ip = hass.config.api is None or not hass.config.api.use_ssl order = [TYPE_URL_INTERNAL, TYPE_URL_EXTERNAL] if prefer_external: order.reverse() # Try finding an URL in the order specified for url_type in order: if allow_internal and url_type == TYPE_URL_INTERNAL and not require_cloud: with suppress(NoURLAvailableError): return _get_internal_url( hass, allow_ip=allow_ip, require_current_request=require_current_request, require_ssl=require_ssl, require_standard_port=require_standard_port, ) if require_cloud or (allow_external and url_type == TYPE_URL_EXTERNAL): with suppress(NoURLAvailableError): return _get_external_url( hass, allow_cloud=allow_cloud, allow_ip=allow_ip, prefer_cloud=prefer_cloud, require_current_request=require_current_request, require_ssl=require_ssl, require_standard_port=require_standard_port, require_cloud=require_cloud, ) if require_cloud: raise NoURLAvailableError # For current request, we accept loopback interfaces (e.g., 127.0.0.1), # the Supervisor hostname and localhost transparently request_host = _get_request_host() if ( require_current_request and request_host is not None and hass.config.api is not None ): # Local import to avoid circular dependencies # pylint: disable-next=import-outside-toplevel from homeassistant.components.hassio import get_host_info, is_hassio scheme = "https" if hass.config.api.use_ssl else "http" current_url = yarl.URL.build( scheme=scheme, host=request_host, port=hass.config.api.port ) known_hostnames = ["localhost"] if is_hassio(hass) and (host_info := get_host_info(hass)): known_hostnames.extend( [host_info["hostname"], f"{host_info['hostname']}.local"] ) if ( ( ( allow_ip and is_ip_address(request_host) and is_loopback(ip_address(request_host)) ) or request_host in known_hostnames ) and (not require_ssl or current_url.scheme == "https") and (not require_standard_port or current_url.is_default_port()) ): return normalize_url(str(current_url)) # We have to be honest now, we have no viable option available raise NoURLAvailableError
Get the host address of the current request.
def _get_request_host() -> str | None: """Get the host address of the current request.""" if (request := http.current_request.get()) is None: raise NoURLAvailableError return yarl.URL(request.url).host
Get internal URL of this instance.
def _get_internal_url( hass: HomeAssistant, *, allow_ip: bool = True, require_current_request: bool = False, require_ssl: bool = False, require_standard_port: bool = False, ) -> str: """Get internal URL of this instance.""" if hass.config.internal_url: internal_url = yarl.URL(hass.config.internal_url) if ( (not require_current_request or internal_url.host == _get_request_host()) and (not require_ssl or internal_url.scheme == "https") and (not require_standard_port or internal_url.is_default_port()) and (allow_ip or not is_ip_address(str(internal_url.host))) ): return normalize_url(str(internal_url)) # Fallback to detected local IP if allow_ip and not ( require_ssl or hass.config.api is None or hass.config.api.use_ssl ): ip_url = yarl.URL.build( scheme="http", host=hass.config.api.local_ip, port=hass.config.api.port ) if ( ip_url.host and not is_loopback(ip_address(ip_url.host)) and (not require_current_request or ip_url.host == _get_request_host()) and (not require_standard_port or ip_url.is_default_port()) ): return normalize_url(str(ip_url)) raise NoURLAvailableError
Get external URL of this instance.
def _get_external_url( hass: HomeAssistant, *, allow_cloud: bool = True, allow_ip: bool = True, prefer_cloud: bool = False, require_current_request: bool = False, require_ssl: bool = False, require_standard_port: bool = False, require_cloud: bool = False, ) -> str: """Get external URL of this instance.""" if require_cloud: return _get_cloud_url(hass, require_current_request=require_current_request) if prefer_cloud and allow_cloud: with suppress(NoURLAvailableError): return _get_cloud_url(hass) if hass.config.external_url: external_url = yarl.URL(hass.config.external_url) if ( (allow_ip or not is_ip_address(str(external_url.host))) and ( not require_current_request or external_url.host == _get_request_host() ) and (not require_standard_port or external_url.is_default_port()) and ( not require_ssl or ( external_url.scheme == "https" and not is_ip_address(str(external_url.host)) ) ) ): return normalize_url(str(external_url)) if allow_cloud: with suppress(NoURLAvailableError): return _get_cloud_url(hass, require_current_request=require_current_request) raise NoURLAvailableError
Get external Home Assistant Cloud URL of this instance.
def _get_cloud_url(hass: HomeAssistant, require_current_request: bool = False) -> str: """Get external Home Assistant Cloud URL of this instance.""" if "cloud" in hass.config.components: # Local import to avoid circular dependencies # pylint: disable-next=import-outside-toplevel from homeassistant.components.cloud import ( CloudNotAvailable, async_remote_ui_url, ) try: cloud_url = yarl.URL(async_remote_ui_url(hass)) except CloudNotAvailable as err: raise NoURLAvailableError from err if not require_current_request or cloud_url.host == _get_request_host(): return normalize_url(str(cloud_url)) raise NoURLAvailableError
Return True if the current connection is a nabucasa cloud connection.
def is_cloud_connection(hass: HomeAssistant) -> bool: """Return True if the current connection is a nabucasa cloud connection.""" if "cloud" not in hass.config.components: return False return remote.is_cloud_request.get()
Normalize a name by removing whitespace and case folding.
def normalize_name(name: str) -> str: """Normalize a name by removing whitespace and case folding.""" return name.casefold().replace(" ", "")
Check to see if a recorder migration is in progress.
def async_migration_in_progress(hass: HomeAssistant) -> bool: """Check to see if a recorder migration is in progress.""" if "recorder" not in hass.config.components: return False # pylint: disable-next=import-outside-toplevel from homeassistant.components import recorder return recorder.util.async_migration_in_progress(hass)
Initialize recorder data.
def async_initialize_recorder(hass: HomeAssistant) -> None: """Initialize recorder data.""" hass.data[DOMAIN] = RecorderData()
Mask part of a string with *.
def partial_redact( x: str | Any, unmasked_prefix: int = 4, unmasked_suffix: int = 4 ) -> str: """Mask part of a string with *.""" if not isinstance(x, str): return REDACTED unmasked = unmasked_prefix + unmasked_suffix if len(x) < unmasked * 2: return REDACTED if not unmasked_prefix and not unmasked_suffix: return REDACTED suffix = x[-unmasked_suffix:] if unmasked_suffix else "" return f"{x[:unmasked_prefix]}***{suffix}"
Redact sensitive data in a dict.
def async_redact_data( data: _T, to_redact: Iterable[Any] | Mapping[Any, Callable[[_ValueT], _ValueT]] ) -> _T: """Redact sensitive data in a dict.""" if not isinstance(data, (Mapping, list)): return data if isinstance(data, list): return cast(_T, [async_redact_data(val, to_redact) for val in data]) redacted = {**data} for key, value in redacted.items(): if value is None: continue if isinstance(value, str) and not value: continue if key in to_redact: if isinstance(to_redact, Mapping): redacted[key] = to_redact[key](value) else: redacted[key] = REDACTED elif isinstance(value, Mapping): redacted[key] = async_redact_data(value, to_redact) elif isinstance(value, list): redacted[key] = [async_redact_data(item, to_redact) for item in value] return cast(_T, redacted)
Find an existing platform that is not a config entry.
def async_get_platform_without_config_entry( hass: HomeAssistant, integration_name: str, integration_platform_name: str ) -> EntityPlatform | None: """Find an existing platform that is not a config entry.""" for integration_platform in async_get_platforms(hass, integration_name): if integration_platform.config_entry is not None: continue if integration_platform.domain == integration_platform_name: platform: EntityPlatform = integration_platform return platform return None
Sync version of async_setup_reload_service.
def setup_reload_service( hass: HomeAssistant, domain: str, platforms: Iterable[str] ) -> None: """Sync version of async_setup_reload_service.""" asyncio.run_coroutine_threadsafe( async_setup_reload_service(hass, domain, platforms), hass.loop, ).result()
Get the restore state data helper.
def async_get(hass: HomeAssistant) -> RestoreStateData: """Get the restore state data helper.""" return cast(RestoreStateData, hass.data[DATA_RESTORE_STATE])
Generate title for a config entry wrapping a single entity. If the entity is registered, use the registry entry's name. If the entity is in the state machine, use the name from the state. Otherwise, fall back to the object ID.
def wrapped_entity_config_entry_title( hass: HomeAssistant, entity_id_or_uuid: str ) -> str: """Generate title for a config entry wrapping a single entity. If the entity is registered, use the registry entry's name. If the entity is in the state machine, use the name from the state. Otherwise, fall back to the object ID. """ registry = er.async_get(hass) entity_id = er.async_validate_entity_id(registry, entity_id_or_uuid) object_id = split_entity_id(entity_id)[1] entry = registry.async_get(entity_id) if entry: return entry.name or entry.original_name or object_id state = hass.states.get(entity_id) if state: return state.name or object_id return object_id
Return an entity selector which excludes own entities.
def entity_selector_without_own_entities( handler: SchemaOptionsFlowHandler, entity_selector_config: selector.EntitySelectorConfig, ) -> vol.Schema: """Return an entity selector which excludes own entities.""" entity_registry = er.async_get(handler.hass) entities = er.async_entries_for_config_entry( entity_registry, handler.config_entry.entry_id, ) entity_ids = [ent.entity_id for ent in entities] final_selector_config = entity_selector_config.copy() final_selector_config["exclude_entities"] = entity_ids return selector.EntitySelector(final_selector_config)
Set result of future unless it is done.
def _set_result_unless_done(future: asyncio.Future[None]) -> None: """Set result of future unless it is done.""" if not future.done(): future.set_result(None)
Append a TraceElement to trace[path].
def action_trace_append(variables, path): """Append a TraceElement to trace[path].""" trace_element = TraceElement(variables, path) trace_append_element(trace_element, ACTION_TRACE_NODE_MAX_LEN) return trace_element
Make a schema for a component that uses the script helper.
def make_script_schema( schema: Mapping[Any, Any], default_script_mode: str, extra: int = vol.PREVENT_EXTRA ) -> vol.Schema: """Make a schema for a component that uses the script helper.""" return vol.Schema( { **schema, vol.Optional(CONF_MODE, default=default_script_mode): vol.In( SCRIPT_MODE_CHOICES ), vol.Optional(CONF_MAX, default=DEFAULT_MAX): vol.All( vol.Coerce(int), vol.Range(min=2) ), vol.Optional(CONF_MAX_EXCEEDED, default=DEFAULT_MAX_EXCEEDED): vol.All( vol.Upper, vol.In(_MAX_EXCEEDED_CHOICES) ), }, extra=extra, )
Stop running Script objects started after shutdown.
def _schedule_stop_scripts_after_shutdown(hass: HomeAssistant) -> None: """Stop running Script objects started after shutdown.""" async_call_later( hass, _SHUTDOWN_MAX_WAIT, partial(_async_stop_scripts_after_shutdown, hass) )
Extract referenced IDs.
def _referenced_extract_ids(data: Any, key: str, found: set[str]) -> None: """Extract referenced IDs.""" # Data may not exist, or be a template if not isinstance(data, dict): return item_ids = data.get(key) if item_ids is None or isinstance(item_ids, template.Template): return if isinstance(item_ids, str): found.add(item_ids) else: for item_id in item_ids: found.add(item_id)
Clear a breakpoint.
def breakpoint_clear( hass: HomeAssistant, key: str, run_id: str | None, node: str ) -> None: """Clear a breakpoint.""" run_id = run_id or RUN_ID_ANY breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS] if key not in breakpoints or run_id not in breakpoints[key]: return breakpoints[key][run_id].discard(node)
Clear all breakpoints.
def breakpoint_clear_all(hass: HomeAssistant) -> None: """Clear all breakpoints.""" hass.data[DATA_SCRIPT_BREAKPOINTS] = {}
Set a breakpoint.
def breakpoint_set( hass: HomeAssistant, key: str, run_id: str | None, node: str ) -> None: """Set a breakpoint.""" run_id = run_id or RUN_ID_ANY breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS] if key not in breakpoints: breakpoints[key] = {} if run_id not in breakpoints[key]: breakpoints[key][run_id] = set() breakpoints[key][run_id].add(node)
List breakpoints.
def breakpoint_list(hass: HomeAssistant) -> list[dict[str, Any]]: """List breakpoints.""" breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS] return [ {"key": key, "run_id": run_id, "node": node} for key in breakpoints for run_id in breakpoints[key] for node in breakpoints[key][run_id] ]
Continue execution of a halted script.
def debug_continue(hass: HomeAssistant, key: str, run_id: str) -> None: """Continue execution of a halted script.""" # Clear any wildcard breakpoint breakpoint_clear(hass, key, run_id, NODE_ANY) signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id) async_dispatcher_send(hass, signal, "continue")
Single step a halted script.
def debug_step(hass: HomeAssistant, key: str, run_id: str) -> None: """Single step a halted script.""" # Set a wildcard breakpoint breakpoint_set(hass, key, run_id, NODE_ANY) signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id) async_dispatcher_send(hass, signal, "continue")
Stop execution of a running or halted script.
def debug_stop(hass: HomeAssistant, key: str, run_id: str) -> None: """Stop execution of a running or halted script.""" signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id) async_dispatcher_send(hass, signal, "stop")
Get selector class type.
def _get_selector_class(config: Any) -> type[Selector]: """Get selector class type.""" if not isinstance(config, dict): raise vol.Invalid("Expected a dictionary") if len(config) != 1: raise vol.Invalid(f"Only one type can be specified. Found {', '.join(config)}") selector_type: str = list(config)[0] if (selector_class := SELECTORS.get(selector_type)) is None: raise vol.Invalid(f"Unknown selector type {selector_type} found") return selector_class
Instantiate a selector.
def selector(config: Any) -> Selector: """Instantiate a selector.""" selector_class = _get_selector_class(config) selector_type = list(config)[0] return selector_class(config[selector_type])
Validate a selector.
def validate_selector(config: Any) -> dict: """Validate a selector.""" selector_class = _get_selector_class(config) selector_type = list(config)[0] # Selectors can be empty if config[selector_type] is None: return {selector_type: {}} return { selector_type: cast(dict, selector_class.CONFIG_SCHEMA(config[selector_type])) }
Return a cached lookup of entity feature enums.
def _entity_features() -> dict[str, type[IntFlag]]: """Return a cached lookup of entity feature enums.""" # pylint: disable=import-outside-toplevel from homeassistant.components.alarm_control_panel import ( AlarmControlPanelEntityFeature, ) from homeassistant.components.calendar import CalendarEntityFeature from homeassistant.components.camera import CameraEntityFeature from homeassistant.components.climate import ClimateEntityFeature from homeassistant.components.cover import CoverEntityFeature from homeassistant.components.fan import FanEntityFeature from homeassistant.components.humidifier import HumidifierEntityFeature from homeassistant.components.lawn_mower import LawnMowerEntityFeature from homeassistant.components.light import LightEntityFeature from homeassistant.components.lock import LockEntityFeature from homeassistant.components.media_player import MediaPlayerEntityFeature from homeassistant.components.remote import RemoteEntityFeature from homeassistant.components.siren import SirenEntityFeature from homeassistant.components.todo import TodoListEntityFeature from homeassistant.components.update import UpdateEntityFeature from homeassistant.components.vacuum import VacuumEntityFeature from homeassistant.components.valve import ValveEntityFeature from homeassistant.components.water_heater import WaterHeaterEntityFeature from homeassistant.components.weather import WeatherEntityFeature return { "AlarmControlPanelEntityFeature": AlarmControlPanelEntityFeature, "CalendarEntityFeature": CalendarEntityFeature, "CameraEntityFeature": CameraEntityFeature, "ClimateEntityFeature": ClimateEntityFeature, "CoverEntityFeature": CoverEntityFeature, "FanEntityFeature": FanEntityFeature, "HumidifierEntityFeature": HumidifierEntityFeature, "LawnMowerEntityFeature": LawnMowerEntityFeature, "LightEntityFeature": LightEntityFeature, "LockEntityFeature": LockEntityFeature, "MediaPlayerEntityFeature": MediaPlayerEntityFeature, "RemoteEntityFeature": RemoteEntityFeature, "SirenEntityFeature": SirenEntityFeature, "TodoListEntityFeature": TodoListEntityFeature, "UpdateEntityFeature": UpdateEntityFeature, "VacuumEntityFeature": VacuumEntityFeature, "ValveEntityFeature": ValveEntityFeature, "WaterHeaterEntityFeature": WaterHeaterEntityFeature, "WeatherEntityFeature": WeatherEntityFeature, }
Validate a supported feature and resolve an enum string to its value.
def _validate_supported_feature(supported_feature: str) -> int: """Validate a supported feature and resolve an enum string to its value.""" known_entity_features = _entity_features() try: _, enum, feature = supported_feature.split(".", 2) except ValueError as exc: raise vol.Invalid( f"Invalid supported feature '{supported_feature}', expected " "<domain>.<enum>.<member>" ) from exc try: return cast(int, getattr(known_entity_features[enum], feature).value) except (AttributeError, KeyError) as exc: raise vol.Invalid(f"Unknown supported feature '{supported_feature}'") from exc
Validate a supported feature and resolve an enum string to its value.
def _validate_supported_features(supported_features: int | list[str]) -> int: """Validate a supported feature and resolve an enum string to its value.""" if isinstance(supported_features, int): return supported_features feature_mask = 0 for supported_feature in supported_features: feature_mask |= _validate_supported_feature(supported_feature) return feature_mask
Validate configuration.
def validate_slider(data: Any) -> Any: """Validate configuration.""" if data["mode"] == "box": return data if "min" not in data or "max" not in data: raise vol.Invalid("min and max are required in slider mode") return data
Convert a sensor_state_data sensor device info to a HA device info.
def sensor_device_info_to_hass_device_info( sensor_device_info: SensorDeviceInfo, ) -> DeviceInfo: """Convert a sensor_state_data sensor device info to a HA device info.""" device_info = DeviceInfo() if sensor_device_info.name is not None: device_info[const.ATTR_NAME] = sensor_device_info.name if sensor_device_info.manufacturer is not None: device_info[const.ATTR_MANUFACTURER] = sensor_device_info.manufacturer if sensor_device_info.model is not None: device_info[const.ATTR_MODEL] = sensor_device_info.model return device_info
Return a cached lookup of base components.
def _base_components() -> dict[str, ModuleType]: """Return a cached lookup of base components.""" # pylint: disable-next=import-outside-toplevel from homeassistant.components import ( alarm_control_panel, calendar, camera, climate, cover, fan, humidifier, light, lock, media_player, notify, remote, siren, todo, update, vacuum, water_heater, ) return { "alarm_control_panel": alarm_control_panel, "calendar": calendar, "camera": camera, "climate": climate, "cover": cover, "fan": fan, "humidifier": humidifier, "light": light, "lock": lock, "media_player": media_player, "notify": notify, "remote": remote, "siren": siren, "todo": todo, "update": update, "vacuum": vacuum, "water_heater": water_heater, }
Validate attribute option or supported feature.
def _validate_option_or_feature(option_or_feature: str, label: str) -> Any: """Validate attribute option or supported feature.""" try: domain, enum, option = option_or_feature.split(".", 2) except ValueError as exc: raise vol.Invalid( f"Invalid {label} '{option_or_feature}', expected " "<domain>.<enum>.<member>" ) from exc base_components = _base_components() if not (base_component := base_components.get(domain)): raise vol.Invalid(f"Unknown base component '{domain}'") try: attribute_enum = getattr(base_component, enum) except AttributeError as exc: raise vol.Invalid(f"Unknown {label} enum '{domain}.{enum}'") from exc if not issubclass(attribute_enum, Enum): raise vol.Invalid(f"Expected {label} '{domain}.{enum}' to be an enum") try: return getattr(attribute_enum, option).value except AttributeError as exc: raise vol.Invalid(f"Unknown {label} '{enum}.{option}'") from exc
Validate attribute option.
def validate_attribute_option(attribute_option: str) -> Any: """Validate attribute option.""" return _validate_option_or_feature(attribute_option, "attribute option")
Validate supported feature.
def validate_supported_feature(supported_feature: str) -> Any: """Validate supported feature.""" return _validate_option_or_feature(supported_feature, "supported feature")
Call a service based on a config hash.
def call_from_config( hass: HomeAssistant, config: ConfigType, blocking: bool = False, variables: TemplateVarsType = None, validate_config: bool = True, ) -> None: """Call a service based on a config hash.""" asyncio.run_coroutine_threadsafe( async_call_from_config(hass, config, blocking, variables, validate_config), hass.loop, ).result()
Prepare to call a service based on a config hash.
def async_prepare_call_from_config( hass: HomeAssistant, config: ConfigType, variables: TemplateVarsType = None, validate_config: bool = False, ) -> ServiceParams: """Prepare to call a service based on a config hash.""" if validate_config: try: config = cv.SERVICE_SCHEMA(config) except vol.Invalid as ex: raise HomeAssistantError( f"Invalid config for calling service: {ex}" ) from ex if CONF_SERVICE in config: domain_service = config[CONF_SERVICE] else: domain_service = config[CONF_SERVICE_TEMPLATE] if isinstance(domain_service, template.Template): try: domain_service.hass = hass domain_service = domain_service.async_render(variables) domain_service = cv.service(domain_service) except TemplateError as ex: raise HomeAssistantError( f"Error rendering service name template: {ex}" ) from ex except vol.Invalid as ex: raise HomeAssistantError( f"Template rendered invalid service: {domain_service}" ) from ex domain, _, service = domain_service.partition(".") target = {} if CONF_TARGET in config: conf = config[CONF_TARGET] try: if isinstance(conf, template.Template): conf.hass = hass target.update(conf.async_render(variables)) else: template.attach(hass, conf) target.update(template.render_complex(conf, variables)) if CONF_ENTITY_ID in target: registry = entity_registry.async_get(hass) entity_ids = cv.comp_entity_ids_or_uuids(target[CONF_ENTITY_ID]) if entity_ids not in (ENTITY_MATCH_ALL, ENTITY_MATCH_NONE): entity_ids = entity_registry.async_validate_entity_ids( registry, entity_ids ) target[CONF_ENTITY_ID] = entity_ids except TemplateError as ex: raise HomeAssistantError( f"Error rendering service target template: {ex}" ) from ex except vol.Invalid as ex: raise HomeAssistantError( f"Template rendered invalid entity IDs: {target[CONF_ENTITY_ID]}" ) from ex service_data = {} for conf in (CONF_SERVICE_DATA, CONF_SERVICE_DATA_TEMPLATE): if conf not in config: continue try: template.attach(hass, config[conf]) render = template.render_complex(config[conf], variables) if not isinstance(render, dict): raise HomeAssistantError( "Error rendering data template: Result is not a Dictionary" ) service_data.update(render) except TemplateError as ex: raise HomeAssistantError(f"Error rendering data template: {ex}") from ex if CONF_SERVICE_ENTITY_ID in config: if target: target[ATTR_ENTITY_ID] = config[CONF_SERVICE_ENTITY_ID] else: target = {ATTR_ENTITY_ID: config[CONF_SERVICE_ENTITY_ID]} return { "domain": domain, "service": service, "service_data": service_data, "target": target, }
Extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents.
def extract_entity_ids( hass: HomeAssistant, service_call: ServiceCall, expand_group: bool = True ) -> set[str]: """Extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents. """ return asyncio.run_coroutine_threadsafe( async_extract_entity_ids(hass, service_call, expand_group), hass.loop ).result()
Check if ids can match anything.
def _has_match(ids: str | list[str] | None) -> TypeGuard[str | list[str]]: """Check if ids can match anything.""" return ids not in (None, ENTITY_MATCH_NONE)
Extract referenced entity IDs from a service call.
def async_extract_referenced_entity_ids( # noqa: C901 hass: HomeAssistant, service_call: ServiceCall, expand_group: bool = True ) -> SelectedEntities: """Extract referenced entity IDs from a service call.""" selector = ServiceTargetSelector(service_call) selected = SelectedEntities() if not selector.has_any_selector: return selected entity_ids: set[str] | list[str] = selector.entity_ids if expand_group: entity_ids = expand_entity_ids(hass, entity_ids) selected.referenced.update(entity_ids) if ( not selector.device_ids and not selector.area_ids and not selector.floor_ids and not selector.label_ids ): return selected entities = entity_registry.async_get(hass).entities dev_reg = device_registry.async_get(hass) area_reg = area_registry.async_get(hass) if selector.floor_ids: floor_reg = floor_registry.async_get(hass) for floor_id in selector.floor_ids: if floor_id not in floor_reg.floors: selected.missing_floors.add(floor_id) for area_id in selector.area_ids: if area_id not in area_reg.areas: selected.missing_areas.add(area_id) for device_id in selector.device_ids: if device_id not in dev_reg.devices: selected.missing_devices.add(device_id) if selector.label_ids: label_reg = label_registry.async_get(hass) for label_id in selector.label_ids: if label_id not in label_reg.labels: selected.missing_labels.add(label_id) for entity_entry in entities.get_entries_for_label(label_id): if ( entity_entry.entity_category is None and entity_entry.hidden_by is None ): selected.indirectly_referenced.add(entity_entry.entity_id) for device_entry in dev_reg.devices.get_devices_for_label(label_id): selected.referenced_devices.add(device_entry.id) for area_entry in area_reg.areas.get_areas_for_label(label_id): selected.referenced_areas.add(area_entry.id) # Find areas for targeted floors if selector.floor_ids: selected.referenced_areas.update( area_entry.id for floor_id in selector.floor_ids for area_entry in area_reg.areas.get_areas_for_floor(floor_id) ) # Find devices for targeted areas selected.referenced_devices.update(selector.device_ids) selected.referenced_areas.update(selector.area_ids) if selected.referenced_areas: for area_id in selected.referenced_areas: selected.referenced_devices.update( device_entry.id for device_entry in dev_reg.devices.get_devices_for_area_id(area_id) ) if not selected.referenced_areas and not selected.referenced_devices: return selected # Add indirectly referenced by area selected.indirectly_referenced.update( entry.entity_id for area_id in selected.referenced_areas # The entity's area matches a targeted area for entry in entities.get_entries_for_area_id(area_id) # Do not add entities which are hidden or which are config # or diagnostic entities. if entry.entity_category is None and entry.hidden_by is None ) # Add indirectly referenced by device selected.indirectly_referenced.update( entry.entity_id for device_id in selected.referenced_devices for entry in entities.get_entries_for_device_id(device_id) # Do not add entities which are hidden or which are config # or diagnostic entities. if ( entry.entity_category is None and entry.hidden_by is None and ( # The entity's device matches a device referenced # by an area and the entity # has no explicitly set area not entry.area_id # The entity's device matches a targeted device or device_id in selector.device_ids ) ) ) return selected
Load services file for an integration.
def _load_services_file(hass: HomeAssistant, integration: Integration) -> JSON_TYPE: """Load services file for an integration.""" try: return cast( JSON_TYPE, _SERVICES_SCHEMA( load_yaml_dict(str(integration.file_path / "services.yaml")) ), ) except FileNotFoundError: _LOGGER.warning( "Unable to find services.yaml for the %s integration", integration.domain ) return {} except (HomeAssistantError, vol.Invalid) as ex: _LOGGER.warning( "Unable to parse services.yaml for the %s integration: %s", integration.domain, ex, ) return {}
Load service files for multiple integrations.
def _load_services_files( hass: HomeAssistant, integrations: Iterable[Integration] ) -> list[JSON_TYPE]: """Load service files for multiple integrations.""" return [_load_services_file(hass, integration) for integration in integrations]
Remove entity service fields.
def remove_entity_service_fields(call: ServiceCall) -> dict[Any, Any]: """Remove entity service fields.""" return { key: val for key, val in call.data.items() if key not in cv.ENTITY_SERVICE_FIELDS }
Register a description for a service.
def async_set_service_schema( hass: HomeAssistant, domain: str, service: str, schema: dict[str, Any] ) -> None: """Register a description for a service.""" domain = domain.lower() service = service.lower() descriptions_cache: dict[tuple[str, str], dict[str, Any] | None] = ( hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {}) ) description = { "name": schema.get("name", ""), "description": schema.get("description", ""), "fields": schema.get("fields", {}), } if "target" in schema: description["target"] = schema["target"] if ( response := hass.services.supports_response(domain, service) ) != SupportsResponse.NONE: description["response"] = { "optional": response == SupportsResponse.OPTIONAL, } hass.data.pop(ALL_SERVICE_DESCRIPTIONS_CACHE, None) descriptions_cache[(domain, service)] = description
Get entity candidates that the user is allowed to access.
def _get_permissible_entity_candidates( call: ServiceCall, entities: dict[str, Entity], entity_perms: None | (Callable[[str, str], bool]), target_all_entities: bool, all_referenced: set[str] | None, ) -> list[Entity]: """Get entity candidates that the user is allowed to access.""" if entity_perms is not None: # Check the permissions since entity_perms is set if target_all_entities: # If we target all entities, we will select all entities the user # is allowed to control. return [ entity for entity_id, entity in entities.items() if entity_perms(entity_id, POLICY_CONTROL) ] assert all_referenced is not None # If they reference specific entities, we will check if they are all # allowed to be controlled. for entity_id in all_referenced: if not entity_perms(entity_id, POLICY_CONTROL): raise Unauthorized( context=call.context, entity_id=entity_id, permission=POLICY_CONTROL, ) elif target_all_entities: return list(entities.values()) # We have already validated they have permissions to control all_referenced # entities so we do not need to check again. if TYPE_CHECKING: assert all_referenced is not None if ( len(all_referenced) == 1 and (single_entity := list(all_referenced)[0]) and (entity := entities.get(single_entity)) is not None ): return [entity] return [entities[entity_id] for entity_id in all_referenced.intersection(entities)]
Register a service that requires admin access.
def async_register_admin_service( hass: HomeAssistant, domain: str, service: str, service_func: Callable[[ServiceCall], Awaitable[None] | None], schema: vol.Schema = vol.Schema({}, extra=vol.PREVENT_EXTRA), ) -> None: """Register a service that requires admin access.""" hass.services.async_register( domain, service, partial( _async_admin_handler, hass, HassJob(service_func, f"admin service {domain}.{service}"), ), schema, )
Ensure permission to access any entity under domain in service call.
def verify_domain_control( hass: HomeAssistant, domain: str ) -> Callable[[Callable[[ServiceCall], Any]], Callable[[ServiceCall], Any]]: """Ensure permission to access any entity under domain in service call.""" def decorator( service_handler: Callable[[ServiceCall], Any], ) -> Callable[[ServiceCall], Any]: """Decorate.""" if not asyncio.iscoroutinefunction(service_handler): raise HomeAssistantError("Can only decorate async functions.") async def check_permissions(call: ServiceCall) -> Any: """Check user permission and raise before call if unauthorized.""" if not call.context.user_id: return await service_handler(call) user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser( context=call.context, permission=POLICY_CONTROL, user_id=call.context.user_id, ) reg = entity_registry.async_get(hass) authorized = False for entity in reg.entities.values(): if entity.platform != domain: continue if user.permissions.check_entity(entity.entity_id, POLICY_CONTROL): authorized = True break if not authorized: raise Unauthorized( context=call.context, permission=POLICY_CONTROL, user_id=call.context.user_id, perm_category=CAT_ENTITIES, ) return await service_handler(call) return check_permissions return decorator
Register system signal handler for core.
def async_register_signal_handling(hass: HomeAssistant) -> None: """Register system signal handler for core.""" @callback def async_signal_handle(exit_code: int) -> None: """Wrap signal handling. * queue call to shutdown task * re-instate default handler """ hass.loop.remove_signal_handler(signal.SIGTERM) hass.loop.remove_signal_handler(signal.SIGINT) hass.data["homeassistant_stop"] = asyncio.create_task( hass.async_stop(exit_code) ) try: hass.loop.add_signal_handler(signal.SIGTERM, async_signal_handle, 0) except ValueError: _LOGGER.warning("Could not bind to SIGTERM") try: hass.loop.add_signal_handler(signal.SIGINT, async_signal_handle, 0) except ValueError: _LOGGER.warning("Could not bind to SIGINT") try: hass.loop.add_signal_handler( signal.SIGHUP, async_signal_handle, RESTART_EXIT_CODE ) except ValueError: _LOGGER.warning("Could not bind to SIGHUP")
Test if exactly one value is None.
def either_one_none(val1: Any | None, val2: Any | None) -> bool: """Test if exactly one value is None.""" return (val1 is None and val2 is not None) or (val1 is not None and val2 is None)
Check if two numeric values have changed.
def _check_numeric_change( old_state: float | None, new_state: float | None, change: float, metric: Callable[[int | float, int | float], int | float], ) -> bool: """Check if two numeric values have changed.""" if old_state is None and new_state is None: return False if either_one_none(old_state, new_state): return True assert old_state is not None assert new_state is not None if metric(old_state, new_state) >= change: return True return False
Check if two numeric values have changed.
def check_absolute_change( val1: float | None, val2: float | None, change: float, ) -> bool: """Check if two numeric values have changed.""" return _check_numeric_change( val1, val2, change, lambda val1, val2: abs(val1 - val2) )
Check if two numeric values have changed.
def check_percentage_change( old_state: float | None, new_state: float | None, change: float, ) -> bool: """Check if two numeric values have changed.""" def percentage_change(old_state: float, new_state: float) -> float: if old_state == new_state: return 0 try: return (abs(new_state - old_state) / old_state) * 100.0 except ZeroDivisionError: return float("inf") return _check_numeric_change(old_state, new_state, change, percentage_change)
Check if given value is a valid float.
def check_valid_float(value: str | float) -> bool: """Check if given value is a valid float.""" try: float(value) except ValueError: return False return True
Decorate a function that should be called once per instance. Result will be cached and simultaneous calls will be handled.
def singleton(data_key: str) -> Callable[[_FuncType[_T]], _FuncType[_T]]: """Decorate a function that should be called once per instance. Result will be cached and simultaneous calls will be handled. """ def wrapper(func: _FuncType[_T]) -> _FuncType[_T]: """Wrap a function with caching logic.""" if not asyncio.iscoroutinefunction(func): @functools.lru_cache(maxsize=1) @bind_hass @functools.wraps(func) def wrapped(hass: HomeAssistant) -> _T: if data_key not in hass.data: hass.data[data_key] = func(hass) return cast(_T, hass.data[data_key]) return wrapped @bind_hass @functools.wraps(func) async def async_wrapped(hass: HomeAssistant) -> Any: if data_key not in hass.data: evt = hass.data[data_key] = asyncio.Event() result = await func(hass) hass.data[data_key] = result evt.set() return cast(_T, result) obj_or_evt = hass.data[data_key] if isinstance(obj_or_evt, asyncio.Event): await obj_or_evt.wait() return cast(_T, hass.data[data_key]) return cast(_T, obj_or_evt) return async_wrapped # type: ignore[return-value] return wrapper
Execute a job at_start_cb when Home Assistant has the wanted state. The job is executed immediately if Home Assistant is in the wanted state. Will wait for event specified by event_type if it isn't.
def _async_at_core_state( hass: HomeAssistant, at_start_cb: Callable[[HomeAssistant], Coroutine[Any, Any, None] | None], event_type: EventType[NoEventData], check_state: Callable[[HomeAssistant], bool], ) -> CALLBACK_TYPE: """Execute a job at_start_cb when Home Assistant has the wanted state. The job is executed immediately if Home Assistant is in the wanted state. Will wait for event specified by event_type if it isn't. """ at_start_job = HassJob(at_start_cb) if check_state(hass): hass.async_run_hass_job(at_start_job, hass) return lambda: None unsub: None | CALLBACK_TYPE = None @callback def _matched_event(event: Event) -> None: """Call the callback when Home Assistant started.""" hass.async_run_hass_job(at_start_job, hass) nonlocal unsub unsub = None @callback def cancel() -> None: if unsub: unsub() unsub = hass.bus.async_listen_once(event_type, _matched_event) return cancel
Execute a job at_start_cb when Home Assistant is starting. The job is executed immediately if Home Assistant is already starting or started. Will wait for EVENT_HOMEASSISTANT_START if it isn't.
def async_at_start( hass: HomeAssistant, at_start_cb: Callable[[HomeAssistant], Coroutine[Any, Any, None] | None], ) -> CALLBACK_TYPE: """Execute a job at_start_cb when Home Assistant is starting. The job is executed immediately if Home Assistant is already starting or started. Will wait for EVENT_HOMEASSISTANT_START if it isn't. """ def _is_running(hass: HomeAssistant) -> bool: return hass.is_running return _async_at_core_state( hass, at_start_cb, EVENT_HOMEASSISTANT_START, _is_running )
Execute a job at_start_cb when Home Assistant has started. The job is executed immediately if Home Assistant is already started. Will wait for EVENT_HOMEASSISTANT_STARTED if it isn't.
def async_at_started( hass: HomeAssistant, at_start_cb: Callable[[HomeAssistant], Coroutine[Any, Any, None] | None], ) -> CALLBACK_TYPE: """Execute a job at_start_cb when Home Assistant has started. The job is executed immediately if Home Assistant is already started. Will wait for EVENT_HOMEASSISTANT_STARTED if it isn't. """ def _is_started(hass: HomeAssistant) -> bool: return hass.state is CoreState.running return _async_at_core_state( hass, at_start_cb, EVENT_HOMEASSISTANT_STARTED, _is_started )
Try to coerce our state to a number. Raises ValueError if this is not possible.
def state_as_number(state: State) -> float: """Try to coerce our state to a number. Raises ValueError if this is not possible. """ if state.state in ( STATE_ON, STATE_LOCKED, STATE_ABOVE_HORIZON, STATE_OPEN, STATE_HOME, ): return 1 if state.state in ( STATE_OFF, STATE_UNLOCKED, STATE_UNKNOWN, STATE_BELOW_HORIZON, STATE_CLOSED, STATE_NOT_HOME, ): return 0 return float(state.state)
Get the store manager. This function is not part of the API and should only be used in the Home Assistant core internals. It is not guaranteed to be stable.
def get_internal_store_manager(hass: HomeAssistant) -> _StoreManager: """Get the store manager. This function is not part of the API and should only be used in the Home Assistant core internals. It is not guaranteed to be stable. """ if STORAGE_MANAGER not in hass.data: manager = _StoreManager(hass) hass.data[STORAGE_MANAGER] = manager return hass.data[STORAGE_MANAGER]
Get an astral location for the current Home Assistant configuration.
def get_astral_location( hass: HomeAssistant, ) -> tuple[astral.location.Location, astral.Elevation]: """Get an astral location for the current Home Assistant configuration.""" from astral import LocationInfo # pylint: disable=import-outside-toplevel from astral.location import Location # pylint: disable=import-outside-toplevel latitude = hass.config.latitude longitude = hass.config.longitude timezone = str(hass.config.time_zone) elevation = hass.config.elevation info = ("", "", timezone, latitude, longitude) # Cache astral locations so they aren't recreated with the same args if DATA_LOCATION_CACHE not in hass.data: hass.data[DATA_LOCATION_CACHE] = {} if info not in hass.data[DATA_LOCATION_CACHE]: hass.data[DATA_LOCATION_CACHE][info] = Location(LocationInfo(*info)) return hass.data[DATA_LOCATION_CACHE][info], elevation
Calculate the next specified solar event.
def get_astral_event_next( hass: HomeAssistant, event: str, utc_point_in_time: datetime.datetime | None = None, offset: datetime.timedelta | None = None, ) -> datetime.datetime: """Calculate the next specified solar event.""" location, elevation = get_astral_location(hass) return get_location_astral_event_next( location, elevation, event, utc_point_in_time, offset )
Calculate the next specified solar event.
def get_location_astral_event_next( location: astral.location.Location, elevation: astral.Elevation, event: str, utc_point_in_time: datetime.datetime | None = None, offset: datetime.timedelta | None = None, ) -> datetime.datetime: """Calculate the next specified solar event.""" if offset is None: offset = datetime.timedelta() if utc_point_in_time is None: utc_point_in_time = dt_util.utcnow() kwargs: dict[str, Any] = {"local": False} if event not in ELEVATION_AGNOSTIC_EVENTS: kwargs["observer_elevation"] = elevation mod = -1 first_err = None while mod < 367: try: next_dt = ( cast(_AstralSunEventCallable, getattr(location, event))( dt_util.as_local(utc_point_in_time).date() + datetime.timedelta(days=mod), **kwargs, ) + offset ) if next_dt > utc_point_in_time: return next_dt except ValueError as err: if not first_err: first_err = err mod += 1 raise ValueError( f"Unable to find event after one year, initial ValueError: {first_err}" ) from first_err
Calculate the astral event time for the specified date.
def get_astral_event_date( hass: HomeAssistant, event: str, date: datetime.date | datetime.datetime | None = None, ) -> datetime.datetime | None: """Calculate the astral event time for the specified date.""" location, elevation = get_astral_location(hass) if date is None: date = dt_util.now().date() if isinstance(date, datetime.datetime): date = dt_util.as_local(date).date() kwargs: dict[str, Any] = {"local": False} if event not in ELEVATION_AGNOSTIC_EVENTS: kwargs["observer_elevation"] = elevation try: return cast(_AstralSunEventCallable, getattr(location, event))(date, **kwargs) except ValueError: # Event never occurs for specified date. return None
Calculate if the sun is currently up.
def is_up( hass: HomeAssistant, utc_point_in_time: datetime.datetime | None = None ) -> bool: """Calculate if the sun is currently up.""" if utc_point_in_time is None: utc_point_in_time = dt_util.utcnow() next_sunrise = get_astral_event_next(hass, SUN_EVENT_SUNRISE, utc_point_in_time) next_sunset = get_astral_event_next(hass, SUN_EVENT_SUNSET, utc_point_in_time) return next_sunrise > next_sunset
Return True if Home Assistant is running in an official container.
def is_official_image() -> bool: """Return True if Home Assistant is running in an official container.""" return os.path.isfile("/OFFICIAL_IMAGE")
Convert temperature into preferred units/precision for display.
def display_temp( hass: HomeAssistant, temperature: float | None, unit: str, precision: float ) -> float | None: """Convert temperature into preferred units/precision for display.""" temperature_unit = unit ha_unit = hass.config.units.temperature_unit if temperature is None: return temperature # If the temperature is not a number this can cause issues # with Polymer components, so bail early there. if not isinstance(temperature, Number): raise TypeError(f"Temperature is not a number: {temperature}") if temperature_unit != ha_unit: temperature = TemperatureConverter.converter_factory(temperature_unit, ha_unit)( temperature ) # Round in the units appropriate if precision == PRECISION_HALVES: return round(temperature * 2) / 2.0 if precision == PRECISION_TENTHS: return round(temperature, 1) # Integer as a fall back (PRECISION_WHOLE) return round(temperature)
Return a TemplateState for a state without collecting.
def _template_state_no_collect(hass: HomeAssistant, state: State) -> TemplateState: """Return a TemplateState for a state without collecting.""" if template_state := CACHED_TEMPLATE_NO_COLLECT_LRU.get(state): return template_state template_state = _create_template_state_no_collect(hass, state) CACHED_TEMPLATE_NO_COLLECT_LRU[state] = template_state return template_state
Return a TemplateState for a state that collects.
def _template_state(hass: HomeAssistant, state: State) -> TemplateState: """Return a TemplateState for a state that collects.""" if template_state := CACHED_TEMPLATE_LRU.get(state): return template_state template_state = TemplateState(hass, state) CACHED_TEMPLATE_LRU[state] = template_state return template_state
Set up tracking the template LRUs.
def async_setup(hass: HomeAssistant) -> bool: """Set up tracking the template LRUs.""" @callback def _async_adjust_lru_sizes(_: Any) -> None: """Adjust the lru cache sizes.""" new_size = int( round(hass.states.async_entity_ids_count() * ENTITY_COUNT_GROWTH_FACTOR) ) for lru in (CACHED_TEMPLATE_LRU, CACHED_TEMPLATE_NO_COLLECT_LRU): # There is no typing for LRU current_size = lru.get_size() if new_size > current_size: lru.set_size(new_size) from .event import ( # pylint: disable=import-outside-toplevel async_track_time_interval, ) cancel = async_track_time_interval( hass, _async_adjust_lru_sizes, timedelta(minutes=10) ) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _async_adjust_lru_sizes) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, callback(lambda _: cancel())) return True
Recursively attach hass to all template instances in list and dict.
def attach(hass: HomeAssistant, obj: Any) -> None: """Recursively attach hass to all template instances in list and dict.""" if isinstance(obj, list): for child in obj: attach(hass, child) elif isinstance(obj, collections.abc.Mapping): for child_key, child_value in obj.items(): attach(hass, child_key) attach(hass, child_value) elif isinstance(obj, Template): obj.hass = hass
Recursive template creator helper function.
def render_complex( value: Any, variables: TemplateVarsType = None, limited: bool = False, parse_result: bool = True, ) -> Any: """Recursive template creator helper function.""" if isinstance(value, list): return [ render_complex(item, variables, limited, parse_result) for item in value ] if isinstance(value, collections.abc.Mapping): return { render_complex(key, variables, limited, parse_result): render_complex( item, variables, limited, parse_result ) for key, item in value.items() } if isinstance(value, Template): return value.async_render(variables, limited=limited, parse_result=parse_result) return value
Test if data structure is a complex template.
def is_complex(value: Any) -> bool: """Test if data structure is a complex template.""" if isinstance(value, Template): return True if isinstance(value, list): return any(is_complex(val) for val in value) if isinstance(value, collections.abc.Mapping): return any(is_complex(val) for val in value) or any( is_complex(val) for val in value.values() ) return False
Check if the input is a Jinja2 template.
def is_template_string(maybe_template: str) -> bool: """Check if the input is a Jinja2 template.""" return _RE_JINJA_DELIMITERS.search(maybe_template) is not None
Generate a result wrapper.
def gen_result_wrapper(kls: type[dict | list | set]) -> type: """Generate a result wrapper.""" class Wrapper(kls, ResultWrapper): # type: ignore[valid-type,misc] """Wrapper of a kls that can store render_result.""" def __init__(self, *args: Any, render_result: str | None = None) -> None: super().__init__(*args) self.render_result = render_result def __str__(self) -> str: if self.render_result is None: # Can't get set repr to work if kls is set: return str(set(self)) return kls.__str__(self) return self.render_result return Wrapper
Raise an exception when a states object is modified.
def _readonly(*args: Any, **kwargs: Any) -> Any: """Raise an exception when a states object is modified.""" raise RuntimeError(f"Cannot modify template States object: {args} {kwargs}")
State generator for a domain or all states.
def _state_generator( hass: HomeAssistant, domain: str | None ) -> Generator[TemplateState, None, None]: """State generator for a domain or all states.""" states = hass.states # If domain is None, we want to iterate over all states, but making # a copy of the dict is expensive. So we iterate over the protected # _states dict instead. This is safe because we're not modifying it # and everything is happening in the same thread (MainThread). # # We do not want to expose this method in the public API though to # ensure it does not get misused. # container: Iterable[State] if domain is None: container = states._states.values() # pylint: disable=protected-access else: container = states.async_all(domain) for state in container: yield _template_state_no_collect(hass, state)
Return state or entity_id if given.
def _resolve_state( hass: HomeAssistant, entity_id_or_state: Any ) -> State | TemplateState | None: """Return state or entity_id if given.""" if isinstance(entity_id_or_state, State): return entity_id_or_state if isinstance(entity_id_or_state, str): return _get_state(hass, entity_id_or_state) return None
Try to convert value to a boolean.
def forgiving_boolean( value: Any, default: _T | object = _SENTINEL ) -> bool | _T | object: """Try to convert value to a boolean.""" try: # Import here, not at top-level to avoid circular import from . import config_validation as cv # pylint: disable=import-outside-toplevel return cv.boolean(value) except vol.Invalid: if default is _SENTINEL: raise_no_default("bool", value) return default
Convert the template result to a boolean. True/not 0/'1'/'true'/'yes'/'on'/'enable' are considered truthy False/0/None/'0'/'false'/'no'/'off'/'disable' are considered falsy
def result_as_boolean(template_result: Any | None) -> bool: """Convert the template result to a boolean. True/not 0/'1'/'true'/'yes'/'on'/'enable' are considered truthy False/0/None/'0'/'false'/'no'/'off'/'disable' are considered falsy """ if template_result is None: return False return forgiving_boolean(template_result, default=False)
Expand out any groups and zones into entity states.
def expand(hass: HomeAssistant, *args: Any) -> Iterable[State]: """Expand out any groups and zones into entity states.""" # circular import. from . import entity as entity_helper # pylint: disable=import-outside-toplevel search = list(args) found = {} sources = entity_helper.entity_sources(hass) while search: entity = search.pop() if isinstance(entity, str): entity_id = entity if (entity := _get_state(hass, entity)) is None: continue elif isinstance(entity, State): entity_id = entity.entity_id elif isinstance(entity, collections.abc.Iterable): search += entity continue else: # ignore other types continue if entity_id in found: continue domain = entity.domain if domain == "group" or ( (source := sources.get(entity_id)) and source["domain"] == "group" ): # Collect state will be called in here since it's wrapped if group_entities := entity.attributes.get(ATTR_ENTITY_ID): search += group_entities elif domain == "zone": if zone_entities := entity.attributes.get(ATTR_PERSONS): search += zone_entities else: _collect_state(hass, entity_id) found[entity_id] = entity return list(found.values())
Get entity ids for entities tied to a device.
def device_entities(hass: HomeAssistant, _device_id: str) -> Iterable[str]: """Get entity ids for entities tied to a device.""" entity_reg = entity_registry.async_get(hass) entries = entity_registry.async_entries_for_device(entity_reg, _device_id) return [entry.entity_id for entry in entries]
Get entity ids for entities tied to an integration/domain. Provide entry_name as domain to get all entity id's for a integration/domain or provide a config entry title for filtering between instances of the same integration.
def integration_entities(hass: HomeAssistant, entry_name: str) -> Iterable[str]: """Get entity ids for entities tied to an integration/domain. Provide entry_name as domain to get all entity id's for a integration/domain or provide a config entry title for filtering between instances of the same integration. """ # Don't allow searching for config entries without title if not entry_name: return [] # first try if there are any config entries with a matching title entities: list[str] = [] ent_reg = entity_registry.async_get(hass) for entry in hass.config_entries.async_entries(): if entry.title != entry_name: continue entries = entity_registry.async_entries_for_config_entry( ent_reg, entry.entry_id ) entities.extend(entry.entity_id for entry in entries) if entities: return entities # fallback to just returning all entities for a domain # pylint: disable-next=import-outside-toplevel from .entity import entity_sources return [ entity_id for entity_id, info in entity_sources(hass).items() if info["domain"] == entry_name ]
Get an config entry ID from an entity ID.
def config_entry_id(hass: HomeAssistant, entity_id: str) -> str | None: """Get an config entry ID from an entity ID.""" entity_reg = entity_registry.async_get(hass) if entity := entity_reg.async_get(entity_id): return entity.config_entry_id return None
Get a device ID from an entity ID or device name.
def device_id(hass: HomeAssistant, entity_id_or_device_name: str) -> str | None: """Get a device ID from an entity ID or device name.""" entity_reg = entity_registry.async_get(hass) entity = entity_reg.async_get(entity_id_or_device_name) if entity is not None: return entity.device_id dev_reg = device_registry.async_get(hass) return next( ( device_id for device_id, device in dev_reg.devices.items() if (name := device.name_by_user or device.name) and (str(entity_id_or_device_name) == name) ), None, )
Get the device specific attribute.
def device_attr(hass: HomeAssistant, device_or_entity_id: str, attr_name: str) -> Any: """Get the device specific attribute.""" device_reg = device_registry.async_get(hass) if not isinstance(device_or_entity_id, str): raise TemplateError("Must provide a device or entity ID") device = None if ( "." in device_or_entity_id and (_device_id := device_id(hass, device_or_entity_id)) is not None ): device = device_reg.async_get(_device_id) elif "." not in device_or_entity_id: device = device_reg.async_get(device_or_entity_id) if device is None or not hasattr(device, attr_name): return None return getattr(device, attr_name)
Test if a device's attribute is a specific value.
def is_device_attr( hass: HomeAssistant, device_or_entity_id: str, attr_name: str, attr_value: Any ) -> bool: """Test if a device's attribute is a specific value.""" return bool(device_attr(hass, device_or_entity_id, attr_name) == attr_value)
Return all open issues.
def issues(hass: HomeAssistant) -> dict[tuple[str, str], dict[str, Any]]: """Return all open issues.""" current_issues = issue_registry.async_get(hass).issues # Use JSON for safe representation return {k: v.to_json() for (k, v) in current_issues.items()}
Get issue by domain and issue_id.
def issue(hass: HomeAssistant, domain: str, issue_id: str) -> dict[str, Any] | None: """Get issue by domain and issue_id.""" result = issue_registry.async_get(hass).async_get_issue(domain, issue_id) if result: return result.to_json() return None
Return all floors.
def floors(hass: HomeAssistant) -> Iterable[str | None]: """Return all floors.""" floor_registry = fr.async_get(hass) return [floor.floor_id for floor in floor_registry.async_list_floors()]