homeassistant.helpers

Helper methods for components within Home Assistant.

homeassistant.helpers.config_per_platform(config: ConfigType, domain: str) → Iterable[tuple[Any, Any]][source]

Break a component config into different platforms.

For example, will find ‘switch’, ‘switch 2’, ‘switch 3’, .. etc Async friendly.

homeassistant.helpers.extract_domain_configs(config: ConfigType, domain: str) → Sequence[str][source]

Extract keys from config for given domain name.

Async friendly.

homeassistant.helpers.aiohttp_client

Helper for aiohttp webclient stuff.

async homeassistant.helpers.aiohttp_client.async_aiohttp_proxy_stream(hass: HomeAssistant, request: web.BaseRequest, stream: aiohttp.StreamReader, content_type: str | None, buffer_size: int = 102400, timeout: int = 10) → web.StreamResponse[source]

Stream a stream to aiohttp web response.

async homeassistant.helpers.aiohttp_client.async_aiohttp_proxy_web(hass: HomeAssistant, request: web.BaseRequest, web_coro: Awaitable[aiohttp.ClientResponse], buffer_size: int = 102400, timeout: int = 10) → web.StreamResponse | None[source]

Stream websession request to aiohttp web response.

homeassistant.helpers.aiohttp_client.async_create_clientsession(hass: homeassistant.core.HomeAssistant, verify_ssl: bool = True, auto_cleanup: bool = True, **kwargs: Any) → aiohttp.client.ClientSession[source]

Create a new ClientSession with kwargs, i.e. for cookies.

If auto_cleanup is False, you need to call detach() after the session returned is no longer used. Default is True, the session will be automatically detached on homeassistant_stop or when being created in config entry setup, the config entry is unloaded.

This method must be run in the event loop.

homeassistant.helpers.aiohttp_client.async_get_clientsession(hass: homeassistant.core.HomeAssistant, verify_ssl: bool = True) → aiohttp.client.ClientSession[source]

Return default aiohttp ClientSession.

This method must be run in the event loop.

homeassistant.helpers.area_registry

Provide a way to connect devices to one physical location.

class homeassistant.helpers.area_registry.AreaEntry(name: str, normalized_name: str, id: str | None = None)[source]

Bases: object

Area Registry Entry.

generate_id(existing_ids: Container[str]) → None[source]

Initialize ID.

id
name
normalized_name
class homeassistant.helpers.area_registry.AreaRegistry(hass: homeassistant.core.HomeAssistant)[source]

Bases: object

Class to hold a registry of areas.

async_create(name: str) → homeassistant.helpers.area_registry.AreaEntry[source]

Create a new area.

async_delete(area_id: str) → None[source]

Delete area.

async_get_area(area_id: str) → AreaEntry | None[source]

Get area by id.

async_get_area_by_name(name: str) → AreaEntry | None[source]

Get area by name.

async_get_or_create(name: str) → homeassistant.helpers.area_registry.AreaEntry[source]

Get or create an area.

async_list_areas() → Iterable[AreaEntry][source]

Get all areas.

async async_load() → None[source]

Load the area registry.

async_schedule_save() → None[source]

Schedule saving the area registry.

async_update(area_id: str, name: str) → homeassistant.helpers.area_registry.AreaEntry[source]

Update name of area.

homeassistant.helpers.area_registry.async_get(hass: homeassistant.core.HomeAssistant) → homeassistant.helpers.area_registry.AreaRegistry[source]

Get area registry.

async homeassistant.helpers.area_registry.async_get_registry(hass: homeassistant.core.HomeAssistant) → homeassistant.helpers.area_registry.AreaRegistry[source]

Get area registry.

This is deprecated and will be removed in the future. Use async_get instead.

async homeassistant.helpers.area_registry.async_load(hass: homeassistant.core.HomeAssistant) → None[source]

Load area registry.

homeassistant.helpers.area_registry.normalize_area_name(area_name: str) → str[source]

Normalize an area name by removing whitespace and case folding.

homeassistant.helpers.check_config

Helper to check the configuration file.

class homeassistant.helpers.check_config.CheckConfigError[source]

Bases: tuple

Configuration check error.

config

Alias for field number 2

domain

Alias for field number 1

message

Alias for field number 0

class homeassistant.helpers.check_config.HomeAssistantConfig[source]

Bases: collections.OrderedDict

Configuration result with errors attribute.

add_error(message: str, domain: str | None = None, config: ConfigType | None = None) → HomeAssistantConfig[source]

Add a single error.

property error_str

Return errors as a string.

async homeassistant.helpers.check_config.async_check_ha_config_file(hass: homeassistant.core.HomeAssistant) → homeassistant.helpers.check_config.HomeAssistantConfig[source]

Load and check if Home Assistant configuration file is valid.

This method is a coroutine.

homeassistant.helpers.collection

Helper to deal with YAML + storage.

class homeassistant.helpers.collection.CollectionChangeSet(change_type: str, item_id: str, item: Any)[source]

Bases: object

Class to represent a change set.

change_type: One of CHANGE_* item_id: The id of the item item: The item

change_type: str = None
item: Any = None
item_id: str = None
exception homeassistant.helpers.collection.CollectionError[source]

Bases: homeassistant.exceptions.HomeAssistantError

Base class for collection related errors.

class homeassistant.helpers.collection.IDLessCollection(logger: logging.Logger, id_manager: IDManager | None = None)[source]

Bases: homeassistant.helpers.collection.ObservableCollection

A collection without IDs.

async async_load(data: list[dict]) → None[source]

Load the collection. Overrides existing data.

counter = 0
class homeassistant.helpers.collection.IDManager[source]

Bases: object

Keep track of IDs across different collections.

add_collection(collection: dict[str, Any]) → None[source]

Add a collection to check for ID usage.

generate_id(suggestion: str) → str[source]

Generate an ID.

has_id(item_id: str) → bool[source]

Test if the ID exists.

exception homeassistant.helpers.collection.ItemNotFound(item_id: str)[source]

Bases: homeassistant.helpers.collection.CollectionError

Raised when an item is not found.

class homeassistant.helpers.collection.ObservableCollection(logger: logging.Logger, id_manager: IDManager | None = None)[source]

Bases: abc.ABC

Base collection type that can be observed.

async_add_change_set_listener(listener: Callable[[Iterable[homeassistant.helpers.collection.CollectionChangeSet]], Awaitable[None]]) → None[source]

Add a listener for a full change set.

Will be called with [(change_type, item_id, updated_config), …]

async_add_listener(listener: Callable[[str, str, dict], Awaitable[None]]) → None[source]

Add a listener.

Will be called with (change_type, item_id, updated_config).

async_items() → list[dict][source]

Return list of items in collection.

async notify_changes(change_sets: Iterable[homeassistant.helpers.collection.CollectionChangeSet]) → None[source]

Notify listeners of a change.

class homeassistant.helpers.collection.StorageCollection(store: Store, logger: logging.Logger, id_manager: IDManager | None = None)[source]

Bases: homeassistant.helpers.collection.ObservableCollection

Offer a CRUD interface on top of JSON storage.

async async_create_item(data: dict) → dict[source]

Create a new item.

async async_delete_item(item_id: str) → None[source]

Delete item.

async async_load() → None[source]

Load the storage Manager.

async async_update_item(item_id: str, updates: dict) → dict[source]

Update item.

property hass

Home Assistant object.

class homeassistant.helpers.collection.StorageCollectionWebsocket(storage_collection: homeassistant.helpers.collection.StorageCollection, api_prefix: str, model_name: str, create_schema: dict, update_schema: dict)[source]

Bases: object

Class to expose storage collection management over websocket.

async_setup(hass: homeassistant.core.HomeAssistant, *, create_list: bool = True, create_create: bool = True) → None[source]

Set up the websocket commands.

property item_id_key

Return item ID key.

async ws_create_item(hass: homeassistant.core.HomeAssistant, connection: homeassistant.components.websocket_api.connection.ActiveConnection, msg: dict) → None[source]

Create a item.

async ws_delete_item(hass: homeassistant.core.HomeAssistant, connection: homeassistant.components.websocket_api.connection.ActiveConnection, msg: dict) → None[source]

Delete a item.

ws_list_item(hass: homeassistant.core.HomeAssistant, connection: homeassistant.components.websocket_api.connection.ActiveConnection, msg: dict) → None[source]

List items.

async ws_update_item(hass: homeassistant.core.HomeAssistant, connection: homeassistant.components.websocket_api.connection.ActiveConnection, msg: dict) → None[source]

Update a item.

class homeassistant.helpers.collection.YamlCollection(logger: logging.Logger, id_manager: IDManager | None = None)[source]

Bases: homeassistant.helpers.collection.ObservableCollection

Offer a collection based on static data.

async async_load(data: list[dict]) → None[source]

Load the YAML collection. Overrides existing data.

homeassistant.helpers.collection.sync_entity_lifecycle(hass: homeassistant.core.HomeAssistant, domain: str, platform: str, entity_component: homeassistant.helpers.entity_component.EntityComponent, collection: homeassistant.helpers.collection.ObservableCollection, create_entity: Callable[[dict], homeassistant.helpers.entity.Entity]) → None[source]

Map a collection to an entity component.

homeassistant.helpers.condition

Offer reusable conditions.

async homeassistant.helpers.condition.async_and_from_config(hass: homeassistant.core.HomeAssistant, config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Create multi condition matcher using ‘AND’.

async homeassistant.helpers.condition.async_device_from_config(hass: homeassistant.core.HomeAssistant, config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Test a device condition.

homeassistant.helpers.condition.async_extract_devices(config: ConfigType | Template) → set[str][source]

Extract devices from a condition.

homeassistant.helpers.condition.async_extract_entities(config: ConfigType | Template) → set[str][source]

Extract entities from a condition.

async homeassistant.helpers.condition.async_from_config(hass: HomeAssistant, config: ConfigType | Template, config_validation: bool = True) → ConditionCheckerType[source]

Turn a condition configuration into a method.

Should be run on the event loop.

async homeassistant.helpers.condition.async_not_from_config(hass: homeassistant.core.HomeAssistant, config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Create multi condition matcher using ‘NOT’.

homeassistant.helpers.condition.async_numeric_state(hass: HomeAssistant, entity: None | str | State, below: float | str | None = None, above: float | str | None = None, value_template: Template | None = None, variables: TemplateVarsType = None, attribute: str | None = None) → bool[source]

Test a numeric state condition.

homeassistant.helpers.condition.async_numeric_state_from_config(config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Wrap action method with state based condition.

async homeassistant.helpers.condition.async_or_from_config(hass: homeassistant.core.HomeAssistant, config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Create multi condition matcher using ‘OR’.

homeassistant.helpers.condition.async_template(hass: homeassistant.core.HomeAssistant, value_template: homeassistant.helpers.template.Template, variables: Optional[Mapping[str, Any]] = None, trace_result: bool = True) → bool[source]

Test if template condition matches.

homeassistant.helpers.condition.async_template_from_config(config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Wrap action method with state based condition.

async homeassistant.helpers.condition.async_trigger_from_config(hass: homeassistant.core.HomeAssistant, config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Test a trigger condition.

async homeassistant.helpers.condition.async_validate_condition_config(hass: HomeAssistant, config: ConfigType | Template) → ConfigType | Template[source]

Validate config.

homeassistant.helpers.condition.condition_trace_append(variables: Optional[Mapping[str, Any]], path: str) → homeassistant.helpers.trace.TraceElement[source]

Append a TraceElement to trace[path].

homeassistant.helpers.condition.condition_trace_set_result(result: bool, **kwargs: Any) → None[source]

Set the result of TraceElement at the top of the stack.

homeassistant.helpers.condition.condition_trace_update_result(**kwargs: Any) → None[source]

Update the result of TraceElement at the top of the stack.

homeassistant.helpers.condition.numeric_state(hass: HomeAssistant, entity: None | str | State, below: float | str | None = None, above: float | str | None = None, value_template: Template | None = None, variables: TemplateVarsType = None) → bool[source]

Test a numeric state condition.

homeassistant.helpers.condition.state(hass: HomeAssistant, entity: None | str | State, req_state: Any, for_period: timedelta | None = None, attribute: str | None = None) → bool[source]

Test if state matches requirements.

Async friendly.

homeassistant.helpers.condition.state_from_config(config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Wrap action method with state based condition.

homeassistant.helpers.condition.sun(hass: HomeAssistant, before: str | None = None, after: str | None = None, before_offset: timedelta | None = None, after_offset: timedelta | None = None) → bool[source]

Test if current time matches sun requirements.

homeassistant.helpers.condition.sun_from_config(config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Wrap action method with sun based condition.

homeassistant.helpers.condition.template(hass: homeassistant.core.HomeAssistant, value_template: homeassistant.helpers.template.Template, variables: Optional[Mapping[str, Any]] = None) → bool[source]

Test if template condition matches.

homeassistant.helpers.condition.time(hass: HomeAssistant, before: dt_util.dt.time | str | None = None, after: dt_util.dt.time | str | None = None, weekday: None | str | Container[str] = None) → bool[source]

Test if local time condition matches.

Handle the fact that time is continuous and we may be testing for a period that crosses midnight. In that case it is easier to test for the opposite. “(23:59 <= now < 00:01)” would be the same as “not (00:01 <= now < 23:59)”.

homeassistant.helpers.condition.time_from_config(config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Wrap action method with time based condition.

homeassistant.helpers.condition.trace_condition(variables: Optional[Mapping[str, Any]]) → collections.abc.Generator[source]

Trace condition evaluation.

homeassistant.helpers.condition.trace_condition_function(condition: Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool]) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Wrap a condition function to enable basic tracing.

homeassistant.helpers.condition.zone(hass: HomeAssistant, zone_ent: None | str | State, entity: None | str | State) → bool[source]

Test if zone-condition matches.

Async friendly.

homeassistant.helpers.condition.zone_from_config(config: Dict[str, Any], config_validation: bool = True) → Callable[[homeassistant.core.HomeAssistant, Optional[Mapping[str, Any]]], bool][source]

Wrap action method with zone based condition.

homeassistant.helpers.config_entry_flow

Helpers for data entry flows for config entries.

class homeassistant.helpers.config_entry_flow.DiscoveryFlowHandler(domain: str, title: str, discovery_function: Callable[[homeassistant.core.HomeAssistant], Union[Awaitable[bool], bool]])[source]

Bases: homeassistant.config_entries.ConfigFlow

Handle a discovery config flow.

VERSION = 1
async async_step_confirm(user_input: dict[str, Any] | None = None) → FlowResult[source]

Confirm setup.

async async_step_dhcp(discovery_info: Dict[str, Any]) → homeassistant.data_entry_flow.FlowResult[source]

Handle a flow initialized by discovery.

async async_step_discovery(discovery_info: Dict[str, Any]) → homeassistant.data_entry_flow.FlowResult[source]

Handle a flow initialized by discovery.

async async_step_homekit(discovery_info: Dict[str, Any]) → homeassistant.data_entry_flow.FlowResult[source]

Handle a flow initialized by discovery.

async async_step_import(_: dict[str, Any] | None) → FlowResult[source]

Handle a flow initialized by import.

async async_step_mqtt(discovery_info: Dict[str, Any]) → homeassistant.data_entry_flow.FlowResult[source]

Handle a flow initialized by discovery.

async async_step_ssdp(discovery_info: Dict[str, Any]) → homeassistant.data_entry_flow.FlowResult[source]

Handle a flow initialized by discovery.

async async_step_user(user_input: dict[str, Any] | None = None) → FlowResult[source]

Handle a flow initialized by the user.

async async_step_zeroconf(discovery_info: Dict[str, Any]) → homeassistant.data_entry_flow.FlowResult[source]

Handle a flow initialized by discovery.

class homeassistant.helpers.config_entry_flow.WebhookFlowHandler(domain: str, title: str, description_placeholder: dict, allow_multiple: bool)[source]

Bases: homeassistant.config_entries.ConfigFlow

Handle a webhook config flow.

VERSION = 1
async async_step_user(user_input: dict[str, Any] | None = None) → FlowResult[source]

Handle a user initiated set up flow to create a webhook.

homeassistant.helpers.config_entry_flow.register_discovery_flow(domain: str, title: str, discovery_function: DiscoveryFunctionType, connection_class: str | UndefinedType = <UndefinedType._singleton: 0>) → None[source]

Register flow for discovered integrations that not require auth.

homeassistant.helpers.config_entry_flow.register_webhook_flow(domain: str, title: str, description_placeholder: dict, allow_multiple: bool = False) → None[source]

Register flow for webhook integrations.

async homeassistant.helpers.config_entry_flow.webhook_async_remove_entry(hass: homeassistant.core.HomeAssistant, entry: homeassistant.config_entries.ConfigEntry) → None[source]

Remove a webhook config entry.

homeassistant.helpers.config_entry_oauth2_flow

Config Flow using OAuth2.

This module exists of the following parts:
  • OAuth2 config flow which supports multiple OAuth2 implementations

  • OAuth2 implementation that works with local provided client ID/secret

class homeassistant.helpers.config_entry_oauth2_flow.AbstractOAuth2FlowHandler[source]

Bases: homeassistant.config_entries.ConfigFlow

Handle a config flow.

DOMAIN = ''
VERSION = 1
async async_oauth_create_entry(data: dict) → homeassistant.data_entry_flow.FlowResult[source]

Create an entry for the flow.

Ok to override if you want to fetch extra info or even add another step.

classmethod async_register_implementation(hass: homeassistant.core.HomeAssistant, local_impl: homeassistant.helpers.config_entry_oauth2_flow.LocalOAuth2Implementation) → None[source]

Register a local implementation.

async async_step_auth(user_input: dict[str, Any] | None = None) → FlowResult[source]

Create an entry for auth.

async async_step_creation(user_input: dict[str, Any] | None = None) → FlowResult[source]

Create config entry from external data.

async async_step_pick_implementation(user_input: dict | None = None) → FlowResult[source]

Handle a flow start.

async async_step_user(user_input: dict[str, Any] | None = None) → FlowResult[source]

Handle a flow start.

property extra_authorize_data

Extra data that needs to be appended to the authorize url.

abstract property logger

Return logger.

class homeassistant.helpers.config_entry_oauth2_flow.AbstractOAuth2Implementation[source]

Bases: abc.ABC

Base class to abstract OAuth2 authentication.

abstract async async_generate_authorize_url(flow_id: str) → str[source]

Generate a url for the user to authorize.

This step is called when a config flow is initialized. It should redirect the user to the vendor website where they can authorize Home Assistant.

The implementation is responsible to get notified when the user is authorized and pass this to the specified config flow. Do as little work as possible once notified. You can do the work inside async_resolve_external_data. This will give the best UX.

Pass external data in with:

await hass.config_entries.flow.async_configure(

flow_id=flow_id, user_input={‘code’: ‘abcd’, ‘state’: { … }

)

async async_refresh_token(token: dict) → dict[source]

Refresh a token and update expires info.

abstract async async_resolve_external_data(external_data: Any) → dict[source]

Resolve external data to tokens.

Turn the data that the implementation passed to the config flow as external step data into tokens. These tokens will be stored as ‘token’ in the config entry data.

abstract property domain

Domain that is providing the implementation.

abstract property name

Name of the implementation.

class homeassistant.helpers.config_entry_oauth2_flow.LocalOAuth2Implementation(hass: homeassistant.core.HomeAssistant, domain: str, client_id: str, client_secret: str, authorize_url: str, token_url: str)[source]

Bases: homeassistant.helpers.config_entry_oauth2_flow.AbstractOAuth2Implementation

Local OAuth2 implementation.

async async_generate_authorize_url(flow_id: str) → str[source]

Generate a url for the user to authorize.

async async_resolve_external_data(external_data: Any) → dict[source]

Resolve the authorization code to tokens.

property domain

Domain providing the implementation.

property extra_authorize_data

Extra data that needs to be appended to the authorize url.

property name

Name of the implementation.

property redirect_uri

Return the redirect uri.

class homeassistant.helpers.config_entry_oauth2_flow.OAuth2AuthorizeCallbackView[source]

Bases: homeassistant.components.http.view.HomeAssistantView

OAuth2 Authorization Callback View.

async get(request: aiohttp.web_request.Request) → aiohttp.web_response.Response[source]

Receive authorization code.

name = 'auth:external:callback'
requires_auth = False
url: str | None = '/auth/external/callback'
class homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session(hass: homeassistant.core.HomeAssistant, config_entry: homeassistant.config_entries.ConfigEntry, implementation: homeassistant.helpers.config_entry_oauth2_flow.AbstractOAuth2Implementation)[source]

Bases: object

Session to make requests authenticated with OAuth2.

async async_ensure_token_valid() → None[source]

Ensure that the current token is valid.

async async_request(method: str, url: str, **kwargs: Any) → aiohttp.client_reqrep.ClientResponse[source]

Make a request.

property token

Return the token.

property valid_token

Return if token is still valid.

homeassistant.helpers.config_entry_oauth2_flow.async_add_implementation_provider(hass: HomeAssistant, provider_domain: str, async_provide_implementation: Callable[[HomeAssistant, str], Awaitable[AbstractOAuth2Implementation | None]]) → None[source]

Add an implementation provider.

If no implementation found, return None.

async homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation(hass: homeassistant.core.HomeAssistant, config_entry: homeassistant.config_entries.ConfigEntry) → homeassistant.helpers.config_entry_oauth2_flow.AbstractOAuth2Implementation[source]

Return the implementation for this config entry.

async homeassistant.helpers.config_entry_oauth2_flow.async_get_implementations(hass: HomeAssistant, domain: str) → dict[str, AbstractOAuth2Implementation][source]

Return OAuth2 implementations for specified domain.

async homeassistant.helpers.config_entry_oauth2_flow.async_oauth2_request(hass: homeassistant.core.HomeAssistant, token: dict, method: str, url: str, **kwargs: Any) → aiohttp.client_reqrep.ClientResponse[source]

Make an OAuth2 authenticated request.

This method will not refresh tokens. Use OAuth2 session for that.

homeassistant.helpers.config_entry_oauth2_flow.async_register_implementation(hass: homeassistant.core.HomeAssistant, domain: str, implementation: homeassistant.helpers.config_entry_oauth2_flow.AbstractOAuth2Implementation) → None[source]

Register an OAuth2 flow implementation for an integration.

homeassistant.helpers.config_validation

Helpers for config validation using voluptuous.

homeassistant.helpers.config_validation.STATE_CONDITION_SCHEMA(value: Any) → dict[source]

Validate a state condition.

homeassistant.helpers.config_validation.boolean(value: Any) → bool[source]

Validate and coerce a boolean value.

homeassistant.helpers.config_validation.custom_serializer(schema: Any) → Any[source]

Serialize additional types for voluptuous_serialize.

homeassistant.helpers.config_validation.date(value: Any) → datetime.date[source]

Validate and transform a date.

homeassistant.helpers.config_validation.datetime(value: Any) → datetime.datetime[source]

Validate datetime.

homeassistant.helpers.config_validation.deprecated(key: str, replacement_key: str | None = None, default: Any | None = None) → Callable[[dict], dict][source]

Log key as deprecated and provide a replacement (if exists).

Expected behavior:
  • Outputs the appropriate deprecation warning if key is detected

  • Processes schema moving the value from key to replacement_key

  • Processes schema changing nothing if only replacement_key provided

  • No warning if only replacement_key provided

  • No warning if neither key nor replacement_key are provided
    • Adds replacement_key with default value in this case

homeassistant.helpers.config_validation.determine_script_action(action: dict[str, Any]) → str[source]

Determine action type.

homeassistant.helpers.config_validation.dynamic_template(value: Any | None) → template_helper.Template[source]

Validate a dynamic (non static) jinja2 template.

homeassistant.helpers.config_validation.ensure_list(value: T | list[T] | None) → list[T][source]

Wrap value in list if it is not one.

homeassistant.helpers.config_validation.ensure_list_csv(value: Any) → list[source]

Ensure that input is a list or make one from comma-separated string.

homeassistant.helpers.config_validation.entities_domain(domain: str | list[str]) → Callable[[str | list], list[str]][source]

Validate that entities belong to domain.

homeassistant.helpers.config_validation.entity_domain(domain: str | list[str]) → Callable[[Any], str][source]

Validate that entity belong to domain.

homeassistant.helpers.config_validation.entity_id(value: Any) → str[source]

Validate Entity ID.

homeassistant.helpers.config_validation.entity_ids(value: str | list) → list[str][source]

Validate Entity IDs.

homeassistant.helpers.config_validation.enum(enumClass: type[Enum]) → vol.All[source]

Create validator for specified enum.

homeassistant.helpers.config_validation.has_at_least_one_key(*keys: str) → Callable[source]

Validate that at least one key exists.

homeassistant.helpers.config_validation.has_at_most_one_key(*keys: str) → Callable[[dict], dict][source]

Validate that zero keys exist or one key exists.

homeassistant.helpers.config_validation.icon(value: Any) → str[source]

Validate icon.

homeassistant.helpers.config_validation.is_regex(value: Any) → re.Pattern[Any][source]

Validate that a string is a valid regular expression.

homeassistant.helpers.config_validation.isdevice(value: Any) → str[source]

Validate that value is a real device.

homeassistant.helpers.config_validation.isdir(value: Any) → str[source]

Validate that the value is an existing dir.

homeassistant.helpers.config_validation.isfile(value: Any) → str[source]

Validate that the value is an existing file.

homeassistant.helpers.config_validation.key_dependency(key: Hashable, dependency: Hashable) → Callable[[dict[Hashable, Any]], dict[Hashable, Any]][source]

Validate that all dependencies exist for key.

homeassistant.helpers.config_validation.key_value_schemas(key: str, value_schemas: dict[Hashable, vol.Schema]) → Callable[[Any], dict[Hashable, Any]][source]

Create a validator that validates based on a value for specific key.

This gives better error messages.

homeassistant.helpers.config_validation.make_entity_service_schema(schema: dict, *, extra: int = 0) → voluptuous.schema_builder.Schema[source]

Create an entity service schema.

homeassistant.helpers.config_validation.match_all(value: T) → T[source]

Validate that matches all values.

homeassistant.helpers.config_validation.matches_regex(regex: str) → Callable[[Any], str][source]

Validate that the value is a string that matches a regex.

class homeassistant.helpers.config_validation.multi_select(options: dict)[source]

Bases: object

Multi select validator returning list of selected values.

homeassistant.helpers.config_validation.path(value: Any) → str[source]

Validate it’s a safe path.

homeassistant.helpers.config_validation.positive_timedelta(value: datetime.timedelta) → datetime.timedelta[source]

Validate timedelta is positive.

homeassistant.helpers.config_validation.remove_falsy(value: list[T]) → list[T][source]

Remove falsy values from a list.

homeassistant.helpers.config_validation.schema_with_slug_keys(value_schema: T | Callable, *, slug_validator: Callable[[Any], str] = <function slug>) → Callable[source]

Ensure dicts have slugs as keys.

Replacement of vol.Schema({cv.slug: value_schema}) to prevent misleading “Extra keys” errors from voluptuous.

homeassistant.helpers.config_validation.script_action(value: Any) → dict[source]

Validate a script action.

homeassistant.helpers.config_validation.service(value: Any) → str[source]

Validate service.

homeassistant.helpers.config_validation.slug(value: Any) → str[source]

Validate value is a valid slug.

homeassistant.helpers.config_validation.slugify(value: Any) → str[source]

Coerce a value to a slug.

homeassistant.helpers.config_validation.socket_timeout(value: Any | None) → object[source]

Validate timeout float > 0.0.

None coerced to socket._GLOBAL_DEFAULT_TIMEOUT bare object.

homeassistant.helpers.config_validation.string(value: Any) → str[source]

Coerce value to string, except for None.

homeassistant.helpers.config_validation.string_with_no_html(value: Any) → str[source]

Validate that the value is a string without HTML.

homeassistant.helpers.config_validation.temperature_unit(value: Any) → str[source]

Validate and transform temperature unit.

homeassistant.helpers.config_validation.template(value: Any | None) → template_helper.Template[source]

Validate a jinja2 template.

homeassistant.helpers.config_validation.template_complex(value: Any) → Any[source]

Validate a complex jinja2 template.

homeassistant.helpers.config_validation.time(value: Any) → datetime.time[source]

Validate and transform a time.

homeassistant.helpers.config_validation.time_period_seconds(value: float | str) → timedelta[source]

Validate and transform seconds to a time offset.

homeassistant.helpers.config_validation.time_period_str(value: str) → datetime.timedelta[source]

Validate and transform time offset.

homeassistant.helpers.config_validation.time_zone(value: str) → str[source]

Validate timezone.

homeassistant.helpers.config_validation.url(value: Any) → str[source]

Validate an URL.

homeassistant.helpers.config_validation.uuid4_hex(value: Any) → str[source]

Validate a v4 UUID in hex format.

homeassistant.helpers.config_validation.whitespace(value: Any) → str[source]

Validate result contains only whitespace.

homeassistant.helpers.config_validation.x10_address(value: str) → str[source]

Validate an x10 address.

homeassistant.helpers.data_entry_flow

Helpers for the data entry flow.

class homeassistant.helpers.data_entry_flow.FlowManagerIndexView(flow_mgr: homeassistant.data_entry_flow.FlowManager)[source]

Bases: homeassistant.helpers.data_entry_flow._BaseFlowManagerView

View to create config flows.

async post(request: web.Request, data: dict[str, Any]) → web.Response[source]

Handle a POST request.

class homeassistant.helpers.data_entry_flow.FlowManagerResourceView(flow_mgr: homeassistant.data_entry_flow.FlowManager)[source]

Bases: homeassistant.helpers.data_entry_flow._BaseFlowManagerView

View to interact with the flow manager.

async delete(request: aiohttp.web_request.Request, flow_id: str) → aiohttp.web_response.Response[source]

Cancel a flow in progress.

async get(request: aiohttp.web_request.Request, flow_id: str) → aiohttp.web_response.Response[source]

Get the current state of a data_entry_flow.

async post(request: web.Request, flow_id: str, data: dict[str, Any]) → web.Response[source]

Handle a POST request.

homeassistant.helpers.debounce

Debounce helper.

class homeassistant.helpers.debounce.Debouncer(hass: HomeAssistant, logger: Logger, *, cooldown: float, immediate: bool, function: Callable[..., Awaitable[Any]] | None = None)[source]

Bases: object

Class to rate limit calls to a specific command.

async async_call() → None[source]

Call the function.

async_cancel() → None[source]

Cancel any scheduled call.

property function

Return the function being wrapped by the Debouncer.

homeassistant.helpers.deprecation

Deprecation helpers for Home Assistant.

homeassistant.helpers.deprecation.deprecated_class(replacement: str) → Any[source]

Mark class as deprecated and provide a replacement class to be used instead.

homeassistant.helpers.deprecation.deprecated_function(replacement: str) → Callable[[...], Callable][source]

Mark function as deprecated and provide a replacement function to be used instead.

homeassistant.helpers.deprecation.deprecated_substitute(substitute_name: str) → Callable[[...], Callable][source]

Help migrate properties to new names.

When a property is added to replace an older property, this decorator can be added to the new property, listing the old property as the substitute. If the old property is defined, its value will be used instead, and a log warning will be issued alerting the user of the impending change.

homeassistant.helpers.deprecation.get_deprecated(config: dict[str, Any], new_name: str, old_name: str, default: Any | None = None) → Any | None[source]

Allow an old config name to be deprecated with a replacement.

If the new config isn’t found, but the old one is, the old value is used and a warning is issued to the user.

homeassistant.helpers.device_registry

Provide a way to connect entities belonging to one device.

class homeassistant.helpers.device_registry.DeletedDeviceEntry(config_entries: set[str], connections: set[tuple[str, str]], identifiers: set[tuple[str, str]], id: str, orphaned_timestamp: float | None)[source]

Bases: object

Deleted Device Registry Entry.

config_entries
connections
id
identifiers
orphaned_timestamp
to_device_entry(config_entry_id: str, connections: set[tuple[str, str]], identifiers: set[tuple[str, str]]) → DeviceEntry[source]

Create DeviceEntry from DeletedDeviceEntry.

class homeassistant.helpers.device_registry.DeviceEntry(config_entries=NOTHING, connections=NOTHING, identifiers=NOTHING, manufacturer: str | None = None, model: str | None = None, name: str | None = None, sw_version: str | None = None, via_device_id: str | None = None, area_id: str | None = None, name_by_user: str | None = None, entry_type: str | None = None, id: str = NOTHING, is_new: bool = False, disabled_by: str | None = None, suggested_area: str | None = None)[source]

Bases: object

Device Registry Entry.

area_id
config_entries
connections
property disabled

Return if entry is disabled.

disabled_by
entry_type
id
identifiers
is_new
manufacturer
model
name
name_by_user
suggested_area
sw_version
via_device_id
class homeassistant.helpers.device_registry.DeviceRegistry(hass: homeassistant.core.HomeAssistant)[source]

Bases: object

Class to hold a registry of devices.

async_clear_area_id(area_id: str) → None[source]

Clear area id from registry entries.

async_clear_config_entry(config_entry_id: str) → None[source]

Clear config entry from registry entries.

async_get(device_id: str) → DeviceEntry | None[source]

Get device.

async_get_device(identifiers: set[tuple[str, str]], connections: set[tuple[str, str]] | None = None) → DeviceEntry | None[source]

Check if device is registered.

async_get_or_create(*, config_entry_id: str, connections: set[tuple[str, str]] | None = None, identifiers: set[tuple[str, str]] | None = None, manufacturer: str | None | UndefinedType = <UndefinedType._singleton: 0>, model: str | None | UndefinedType = <UndefinedType._singleton: 0>, name: str | None | UndefinedType = <UndefinedType._singleton: 0>, default_manufacturer: str | None | UndefinedType = <UndefinedType._singleton: 0>, default_model: str | None | UndefinedType = <UndefinedType._singleton: 0>, default_name: str | None | UndefinedType = <UndefinedType._singleton: 0>, sw_version: str | None | UndefinedType = <UndefinedType._singleton: 0>, entry_type: str | None | UndefinedType = <UndefinedType._singleton: 0>, via_device: tuple[str, str] | None = None, disabled_by: str | None | UndefinedType = <UndefinedType._singleton: 0>, suggested_area: str | None | UndefinedType = <UndefinedType._singleton: 0>) → DeviceEntry[source]

Get device. Create if it doesn’t exist.

async async_load() → None[source]

Load the device registry.

async_purge_expired_orphaned_devices() → None[source]

Purge expired orphaned devices from the registry.

We need to purge these periodically to avoid the database growing without bound.

async_remove_device(device_id: str) → None[source]

Remove a device from the device registry.

async_schedule_save() → None[source]

Schedule saving the device registry.

async_update_device(device_id: str, *, area_id: str | None | UndefinedType = <UndefinedType._singleton: 0>, manufacturer: str | None | UndefinedType = <UndefinedType._singleton: 0>, model: str | None | UndefinedType = <UndefinedType._singleton: 0>, name: str | None | UndefinedType = <UndefinedType._singleton: 0>, name_by_user: str | None | UndefinedType = <UndefinedType._singleton: 0>, new_identifiers: set[tuple[str, str]] | UndefinedType = <UndefinedType._singleton: 0>, sw_version: str | None | UndefinedType = <UndefinedType._singleton: 0>, via_device_id: str | None | UndefinedType = <UndefinedType._singleton: 0>, remove_config_entry_id: str | UndefinedType = <UndefinedType._singleton: 0>, disabled_by: str | None | UndefinedType = <UndefinedType._singleton: 0>, suggested_area: str | None | UndefinedType = <UndefinedType._singleton: 0>) → DeviceEntry | None[source]

Update properties of a device.

deleted_devices = None
devices = None
homeassistant.helpers.device_registry.async_cleanup(hass: HomeAssistant, dev_reg: DeviceRegistry, ent_reg: entity_registry.EntityRegistry) → None[source]

Clean up device registry.

homeassistant.helpers.device_registry.async_config_entry_disabled_by_changed(registry: DeviceRegistry, config_entry: ConfigEntry) → None[source]

Handle a config entry being disabled or enabled.

Disable devices in the registry that are associated with a config entry when the config entry is disabled, enable devices in the registry that are associated with a config entry when the config entry is enabled and the devices are marked DISABLED_CONFIG_ENTRY.

homeassistant.helpers.device_registry.async_entries_for_area(registry: DeviceRegistry, area_id: str) → list[DeviceEntry][source]

Return entries that match an area.

homeassistant.helpers.device_registry.async_entries_for_config_entry(registry: DeviceRegistry, config_entry_id: str) → list[DeviceEntry][source]

Return entries that match a config entry.

homeassistant.helpers.device_registry.async_get(hass: homeassistant.core.HomeAssistant) → homeassistant.helpers.device_registry.DeviceRegistry[source]

Get device registry.

async homeassistant.helpers.device_registry.async_get_registry(hass: homeassistant.core.HomeAssistant) → homeassistant.helpers.device_registry.DeviceRegistry[source]

Get device registry.

This is deprecated and will be removed in the future. Use async_get instead.

async homeassistant.helpers.device_registry.async_load(hass: homeassistant.core.HomeAssistant) → None[source]

Load device registry.

homeassistant.helpers.device_registry.async_setup_cleanup(hass: homeassistant.core.HomeAssistant, dev_reg: homeassistant.helpers.device_registry.DeviceRegistry) → None[source]

Clean up device registry when entities removed.

homeassistant.helpers.device_registry.format_mac(mac: str) → str[source]

Format the mac address string for entry into dev reg.

homeassistant.helpers.discovery

Helper methods to help with platform discovery.

There are two different types of discoveries that can be fired/listened for.
  • listen/discover is for services. These are targeted at a component.

  • listen_platform/discover_platform is for platforms. These are used by components to allow discovery of their platforms.

class homeassistant.helpers.discovery.DiscoveryDict[source]

Bases: dict

Discovery data.

discovered = None
platform = None
service = None
async homeassistant.helpers.discovery.async_discover(hass: core.HomeAssistant, service: str, discovered: DiscoveryInfoType | None, component: str | None, hass_config: ConfigType) → None[source]

Fire discovery event. Can ensure a component is loaded.

homeassistant.helpers.discovery.async_listen(hass: homeassistant.core.HomeAssistant, service: str, callback: Callable[[], None]) → None[source]

Set up listener for discovery of specific service.

Service can be a string or a list/tuple.

homeassistant.helpers.discovery.async_listen_platform(hass: core.HomeAssistant, component: str, callback: Callable[[str, dict[str, Any] | None], Any]) → None[source]

Register a platform loader listener.

This method must be run in the event loop.

async homeassistant.helpers.discovery.async_load_platform(hass: homeassistant.core.HomeAssistant, component: str, platform: str, discovered: Dict[str, Any], hass_config: Dict[str, Any]) → None[source]

Load a component and platform dynamically.

Use async_listen_platform to register a callback for these events.

Warning: Do not await this inside a setup method to avoid a dead lock. Use hass.async_create_task(async_load_platform(..)) instead.

homeassistant.helpers.discovery.discover(hass: homeassistant.core.HomeAssistant, service: str, discovered: Dict[str, Any], component: str, hass_config: Dict[str, Any]) → None[source]

Fire discovery event. Can ensure a component is loaded.

homeassistant.helpers.discovery.load_platform(hass: homeassistant.core.HomeAssistant, component: str, platform: str, discovered: Dict[str, Any], hass_config: Dict[str, Any]) → None[source]

Load a component and platform dynamically.

homeassistant.helpers.dispatcher

Helpers for Home Assistant dispatcher & internal component/platform.

homeassistant.helpers.dispatcher.async_dispatcher_connect(hass: homeassistant.core.HomeAssistant, signal: str, target: Callable[[...], Any]) → Callable[[], None][source]

Connect a callable function to a signal.

This method must be run in the event loop.

homeassistant.helpers.dispatcher.async_dispatcher_send(hass: homeassistant.core.HomeAssistant, signal: str, *args: Any) → None[source]

Send signal and data.

This method must be run in the event loop.

homeassistant.helpers.dispatcher.dispatcher_connect(hass: homeassistant.core.HomeAssistant, signal: str, target: Callable[[...], None]) → Callable[[], None][source]

Connect a callable function to a signal.

homeassistant.helpers.dispatcher.dispatcher_send(hass: homeassistant.core.HomeAssistant, signal: str, *args: Any) → None[source]

Send signal and data.

homeassistant.helpers.entity

An abstract class for entities.

class homeassistant.helpers.entity.DeviceInfo[source]

Bases: dict

Entity device information for device registry.

connections = None
default_manufacturer = None
default_model = None
default_name = None
entry_type = None
identifiers = None
manufacturer = None
model = None
name = None
suggested_area = None
sw_version = None
via_device = None
class homeassistant.helpers.entity.Entity[source]

Bases: abc.ABC

An abstract class for Home Assistant entities.

add_to_platform_abort() → None[source]

Abort adding an entity to a platform.

async add_to_platform_finish() → None[source]

Finish adding an entity to a platform.

add_to_platform_start(hass: HomeAssistant, platform: EntityPlatform, parallel_updates: asyncio.Semaphore | None) → None[source]

Start adding an entity to a platform.

property assumed_state

Return True if unable to access real state of the entity.

async async_added_to_hass() → None[source]

Run when entity about to be added to hass.

To be extended by integrations.

async async_device_update(warning: bool = True) → None[source]

Process ‘update’ or ‘async_update’ from entity.

This method is a coroutine.

async async_internal_added_to_hass() → None[source]

Run when entity about to be added to hass.

Not to be extended by integrations.

async async_internal_will_remove_from_hass() → None[source]

Run when entity will be removed from hass.

Not to be extended by integrations.

async_on_remove(func: Callable[[], None]) → None[source]

Add a function to call when entity removed.

async async_remove(*, force_remove: bool = False) → None[source]

Remove entity from Home Assistant.

If the entity has a non disabled entry in the entity registry, the entity’s state will be set to unavailable, in the same way as when the entity registry is loaded.

If the entity doesn’t have a non disabled entry in the entity registry, or if force_remove=True, its state will be removed.

async async_removed_from_registry() → None[source]

Run when entity has been removed from entity registry.

To be extended by integrations.

async async_request_call(coro: collections.abc.Awaitable) → None[source]

Process request batched.

async_schedule_update_ha_state(force_refresh: bool = False) → None[source]

Schedule an update ha state change task.

This method must be run in the event loop. Scheduling the update avoids executor deadlocks.

Entity state and attributes are read when the update ha state change task is executed. If state is changed more than once before the ha state change task has been executed, the intermediate state transitions will be missed.

async_set_context(context: homeassistant.core.Context) → None[source]

Set the context the entity currently operates under.

async async_update_ha_state(force_refresh: bool = False) → None[source]

Update Home Assistant with current state of entity.

If force_refresh == True will update entity before setting state.

This method must be run in the event loop.

async async_will_remove_from_hass() → None[source]

Run when entity will be removed from hass.

To be extended by integrations.

async_write_ha_state() → None[source]

Write the state to the state machine.

property available

Return True if entity is available.

property capability_attributes

Return the capability attributes.

Attributes that explain the capabilities of an entity.

Implemented by component base class. Convention for attribute names is lowercase snake_case.

property context_recent_time

Time that a context is considered recent.

property device_class

Return the class of this device, from component DEVICE_CLASSES.

property device_info

Return device specific attributes.

Implemented by platform classes.

property device_state_attributes

Return entity specific state attributes.

This method is deprecated, platform classes should implement extra_state_attributes instead.

property enabled

Return if the entity is enabled in the entity registry.

If an entity is not part of the registry, it cannot be disabled and will therefore always be enabled.

entity_id: str = None
property entity_picture

Return the entity picture to use in the frontend, if any.

property entity_registry_enabled_default

Return if the entity should be enabled when first added to the entity registry.

property extra_state_attributes

Return entity specific state attributes.

Implemented by platform classes. Convention for attribute names is lowercase snake_case.

property force_update

Return True if state updates should be forced.

If True, a state change will be triggered anytime the state property is updated, not just when the value changes.

hass: HomeAssistant = None
property icon

Return the icon to use in the frontend, if any.

property name

Return the name of the entity.

parallel_updates: asyncio.Semaphore | None = None
platform: EntityPlatform | None = None
registry_entry: RegistryEntry | None = None
schedule_update_ha_state(force_refresh: bool = False) → None[source]

Schedule an update ha state change task.

Scheduling the update avoids executor deadlocks.

Entity state and attributes are read when the update ha state change task is executed. If state is changed more than once before the ha state change task has been executed, the intermediate state transitions will be missed.

property should_poll

Return True if entity has to be polled for state.

False if entity pushes its state to HA.

property state

Return the state of the entity.

property state_attributes

Return the state attributes.

Implemented by component base class, should not be extended by integrations. Convention for attribute names is lowercase snake_case.

property supported_features

Flag supported features.

property unique_id

Return a unique ID.

property unit_of_measurement

Return the unit of measurement of this entity, if any.

class homeassistant.helpers.entity.ToggleEntity[source]

Bases: homeassistant.helpers.entity.Entity

An abstract class for entities that can be turned on and off.

async async_toggle(**kwargs: Any) → None[source]

Toggle the entity.

async async_turn_off(**kwargs: Any) → None[source]

Turn the entity off.

async async_turn_on(**kwargs: Any) → None[source]

Turn the entity on.

property is_on

Return True if entity is on.

property state

Return the state.

toggle(**kwargs: Any) → None[source]

Toggle the entity.

turn_off(**kwargs: Any) → None[source]

Turn the entity off.

turn_on(**kwargs: Any) → None[source]

Turn the entity on.

homeassistant.helpers.entity.async_generate_entity_id(entity_id_format: str, name: str | None, current_ids: Iterable[str] | None = None, hass: HomeAssistant | None = None) → str[source]

Generate a unique entity ID based on given entity IDs or used IDs.

homeassistant.helpers.entity.entity_sources(hass: HomeAssistant) → dict[str, dict[str, str]][source]

Get the entity sources.

homeassistant.helpers.entity.generate_entity_id(entity_id_format: str, name: str | None, current_ids: list[str] | None = None, hass: HomeAssistant | None = None) → str[source]

Generate a unique entity ID based on given entity IDs or used IDs.

homeassistant.helpers.entity.get_capability(hass: HomeAssistant, entity_id: str, capability: str) → Any | None[source]

Get a capability attribute of an entity.

First try the statemachine, then entity registry.

homeassistant.helpers.entity.get_device_class(hass: HomeAssistant, entity_id: str) → str | None[source]

Get device class of an entity.

First try the statemachine, then entity registry.

homeassistant.helpers.entity.get_supported_features(hass: homeassistant.core.HomeAssistant, entity_id: str) → int[source]

Get supported features for an entity.

First try the statemachine, then entity registry.

homeassistant.helpers.entity.get_unit_of_measurement(hass: HomeAssistant, entity_id: str) → str | None[source]

Get unit of measurement class of an entity.

First try the statemachine, then entity registry.

homeassistant.helpers.entity_component

Helpers for components that manage entities.

class homeassistant.helpers.entity_component.EntityComponent(logger: logging.Logger, domain: str, hass: homeassistant.core.HomeAssistant, scan_interval: datetime.timedelta = datetime.timedelta(seconds=15))[source]

Bases: object

The EntityComponent manages platforms that manages entities.

This class has the following responsibilities:
  • Process the configuration and set up a platform based component.

  • Manage the platforms and their entities.

  • Help extract the entities from a service call.

  • Listen for discovery events for platforms related to the domain.

async async_extract_from_service(service_call: ServiceCall, expand_group: bool = True) → list[entity.Entity][source]

Extract all known and available entities from a service call.

Will return an empty list if entities specified but unknown.

This method must be run in the event loop.

async async_prepare_reload(*, skip_reset: bool = False) → ConfigType | None[source]

Prepare reloading this entity component.

This method must be run in the event loop.

async_register_entity_service(name: str, schema: dict[str, Any] | vol.Schema, func: str | Callable[..., Any], required_features: list[int] | None = None) → None[source]

Register an entity service.

async async_remove_entity(entity_id: str) → None[source]

Remove an entity managed by one of the platforms.

async async_setup(config: Dict[str, Any]) → None[source]

Set up a full entity component.

Loads the platforms from the config and will listen for supported discovered platforms.

This method must be run in the event loop.

async async_setup_entry(config_entry: homeassistant.config_entries.ConfigEntry) → bool[source]

Set up a config entry.

async async_setup_platform(platform_type: str, platform_config: ConfigType, discovery_info: DiscoveryInfoType | None = None) → None[source]

Set up a platform for this component.

async async_unload_entry(config_entry: homeassistant.config_entries.ConfigEntry) → bool[source]

Unload a config entry.

property entities

Return an iterable that returns all entities.

get_entity(entity_id: str) → entity.Entity | None[source]

Get an entity.

setup(config: Dict[str, Any]) → None[source]

Set up a full entity component.

This doesn’t block the executor to protect from deadlocks.

async homeassistant.helpers.entity_component.async_update_entity(hass: homeassistant.core.HomeAssistant, entity_id: str) → None[source]

Trigger an update for an entity.

homeassistant.helpers.entity_platform

Class to manage the entities for a single platform.

class homeassistant.helpers.entity_platform.AddEntitiesCallback(*args, **kwargs)[source]

Bases: typing.Protocol

Protocol type for EntityPlatform.add_entities callback.

class homeassistant.helpers.entity_platform.EntityPlatform(*, hass: HomeAssistant, logger: Logger, domain: str, platform_name: str, platform: ModuleType | None, scan_interval: timedelta, entity_namespace: str | None)[source]

Bases: object

Manage the entities for a single platform.

add_entities(new_entities: Iterable[Entity], update_before_add: bool = False) → None[source]

Add entities for a single platform.

async async_add_entities(new_entities: Iterable[Entity], update_before_add: bool = False) → None[source]

Add entities for a single platform async.

This method must be run in the event loop.

async_cancel_retry_setup() → None[source]

Cancel retry setup.

async async_destroy() → None[source]

Destroy an entity platform.

Call before discarding the object.

async async_extract_from_service(service_call: ServiceCall, expand_group: bool = True) → list[Entity][source]

Extract all known and available entities from a service call.

Will return an empty list if entities specified but unknown.

This method must be run in the event loop.

async_register_entity_service(name: str, schema: dict | vol.Schema, func: str | Callable[..., Any], required_features: Iterable[int] | None = None) → None[source]

Register an entity service.

Services will automatically be shared by all platforms of the same domain.

async async_remove_entity(entity_id: str) → None[source]

Remove entity id from platform.

async async_reset() → None[source]

Remove all entities and reset data.

This method must be run in the event loop.

async async_setup(platform_config: ConfigType, discovery_info: DiscoveryInfoType | None = None) → None[source]

Set up the platform from a config file.

async async_setup_entry(config_entry: homeassistant.config_entries.ConfigEntry) → bool[source]

Set up the platform from a config entry.

async async_shutdown() → None[source]

Call when Home Assistant is stopping.

async_unsub_polling() → None[source]

Stop polling.

homeassistant.helpers.entity_platform.async_get_current_platform() → homeassistant.helpers.entity_platform.EntityPlatform[source]

Get the current platform from context.

homeassistant.helpers.entity_platform.async_get_platforms(hass: HomeAssistant, integration_name: str) → list[EntityPlatform][source]

Find existing platforms.

homeassistant.helpers.entity_registry

Provide a registry to track entity IDs.

The Entity Registry keeps a registry of entities. Entities are uniquely identified by their domain, platform and a unique id provided by that platform.

The Entity Registry will persist itself 10 seconds after a new entity is registered. Registering a new entity while a timer is in progress resets the timer.

class homeassistant.helpers.entity_registry.EntityRegistry(hass: homeassistant.core.HomeAssistant)[source]

Bases: object

Class to hold a registry of entities.

async_clear_area_id(area_id: str) → None[source]

Clear area id from registry entries.

async_clear_config_entry(config_entry: str) → None[source]

Clear config entry from registry entries.

async_device_modified(event: homeassistant.core.Event) → None[source]

Handle the removal or update of a device.

Remove entities from the registry that are associated to a device when the device is removed.

Disable entities in the registry that are associated to a device when the device is disabled.

async_generate_entity_id(domain: str, suggested_object_id: str, known_object_ids: Iterable[str] | None = None) → str[source]

Generate an entity ID that does not conflict.

Conflicts checked against registered and currently existing entities.

async_get(entity_id: str) → RegistryEntry | None[source]

Get EntityEntry for an entity_id.

async_get_device_class_lookup(domain_device_classes: set) → dict[source]

Return a lookup for the device class by domain.

async_get_entity_id(domain: str, platform: str, unique_id: str) → str | None[source]

Check if an entity_id is currently registered.

async_get_or_create(domain: str, platform: str, unique_id: str, *, suggested_object_id: str | None = None, known_object_ids: Iterable[str] | None = None, disabled_by: str | None = None, config_entry: ConfigEntry | None = None, device_id: str | None = None, area_id: str | None = None, capabilities: Mapping[str, Any] | None = None, supported_features: int | None = None, device_class: str | None = None, unit_of_measurement: str | None = None, original_name: str | None = None, original_icon: str | None = None) → RegistryEntry[source]

Get entity. Create if it doesn’t exist.

async_is_registered(entity_id: str) → bool[source]

Check if an entity_id is currently registered.

async async_load() → None[source]

Load the entity registry.

async_remove(entity_id: str) → None[source]

Remove an entity from registry.

async_schedule_save() → None[source]

Schedule saving the entity registry.

async_update_entity(entity_id: str, *, name: str | None | UndefinedType = <UndefinedType._singleton: 0>, icon: str | None | UndefinedType = <UndefinedType._singleton: 0>, area_id: str | None | UndefinedType = <UndefinedType._singleton: 0>, new_entity_id: str | UndefinedType = <UndefinedType._singleton: 0>, new_unique_id: str | UndefinedType = <UndefinedType._singleton: 0>, disabled_by: str | None | UndefinedType = <UndefinedType._singleton: 0>) → RegistryEntry[source]

Update properties of an entity.

class homeassistant.helpers.entity_registry.RegistryEntry(entity_id: str, unique_id: str, platform: str, name: str | None = None, icon: str | None = None, device_id: str | None = None, area_id: str | None = None, config_entry_id: str | None = None, disabled_by: str | None = None, capabilities: Mapping[str, Any] | None = None, supported_features: int = 0, device_class: str | None = None, unit_of_measurement: str | None = None, original_name: str | None = None, original_icon: str | None = None)[source]

Bases: object

Entity Registry Entry.

area_id
capabilities
config_entry_id
device_class
device_id
property disabled

Return if entry is disabled.

disabled_by
domain
entity_id
icon
name
original_icon
original_name
platform
supported_features
unique_id
unit_of_measurement
write_unavailable_state(hass: homeassistant.core.HomeAssistant) → None[source]

Write the unavailable state to the state machine.

homeassistant.helpers.entity_registry.async_config_entry_disabled_by_changed(registry: EntityRegistry, config_entry: ConfigEntry) → None[source]

Handle a config entry being disabled or enabled.

Disable entities in the registry that are associated with a config entry when the config entry is disabled, enable entities in the registry that are associated with a config entry when the config entry is enabled and the entities are marked DISABLED_CONFIG_ENTRY.

homeassistant.helpers.entity_registry.async_entries_for_area(registry: EntityRegistry, area_id: str) → list[RegistryEntry][source]

Return entries that match an area.

homeassistant.helpers.entity_registry.async_entries_for_config_entry(registry: EntityRegistry, config_entry_id: str) → list[RegistryEntry][source]

Return entries that match a config entry.

homeassistant.helpers.entity_registry.async_entries_for_device(registry: EntityRegistry, device_id: str, include_disabled_entities: bool = False) → list[RegistryEntry][source]

Return entries that match a device.

homeassistant.helpers.entity_registry.async_get(hass: homeassistant.core.HomeAssistant) → homeassistant.helpers.entity_registry.EntityRegistry[source]

Get entity registry.

async homeassistant.helpers.entity_registry.async_get_registry(hass: homeassistant.core.HomeAssistant) → homeassistant.helpers.entity_registry.EntityRegistry[source]

Get entity registry.

This is deprecated and will be removed in the future. Use async_get instead.

async homeassistant.helpers.entity_registry.async_load(hass: homeassistant.core.HomeAssistant) → None[source]

Load entity registry.

async homeassistant.helpers.entity_registry.async_migrate_entries(hass: HomeAssistant, config_entry_id: str, entry_callback: Callable[[RegistryEntry], dict | None]) → None[source]

Migrator of unique IDs.

homeassistant.helpers.entity_registry.async_setup_entity_restore(hass: homeassistant.core.HomeAssistant, registry: homeassistant.helpers.entity_registry.EntityRegistry) → None[source]

Set up the entity restore mechanism.

homeassistant.helpers.entity_values

A class to hold entity values.

class homeassistant.helpers.entity_values.EntityValues(exact: dict[str, dict[str, str]] | None = None, domain: dict[str, dict[str, str]] | None = None, glob: dict[str, dict[str, str]] | None = None)[source]

Bases: object

Class to store entity id based values.

get(entity_id: str) → dict[str, str][source]

Get config for an entity id.

homeassistant.helpers.entityfilter

Helper class to implement include/exclude of entities and domains.

homeassistant.helpers.entityfilter.convert_filter(config: dict[str, list[str]]) → Callable[[str], bool][source]

Convert the filter schema into a filter.

homeassistant.helpers.entityfilter.convert_include_exclude_filter(config: dict[str, dict[str, list[str]]]) → Callable[[str], bool][source]

Convert the include exclude filter schema into a filter.

homeassistant.helpers.entityfilter.generate_filter(include_domains: list[str], include_entities: list[str], exclude_domains: list[str], exclude_entities: list[str], include_entity_globs: list[str] = [], exclude_entity_globs: list[str] = []) → Callable[[str], bool][source]

Return a function that will filter entities based on the args.

homeassistant.helpers.event

Helpers for listening to events.

class homeassistant.helpers.event.SunListener(hass: HomeAssistant, job: HassJob, event: str, offset: timedelta | None, unsub_sun: CALLBACK_TYPE | None = None, unsub_config: CALLBACK_TYPE | None = None)[source]

Bases: object

Helper class to help listen to sun events.

async_attach() → None[source]

Attach a sun listener.

async_detach() → None[source]

Detach the sun listener.

event = None
hass = None
job = None
offset = None
class homeassistant.helpers.event.TrackStates(all_states: bool, entities: set, domains: set)[source]

Bases: object

Class for keeping track of states being tracked.

all_states: All states on the system are being tracked entities: Entities to track domains: Domains to track

all_states = None
domains = None
entities = None
class homeassistant.helpers.event.TrackTemplate(template: Template, variables: TemplateVarsType, rate_limit: timedelta | None = None)[source]

Bases: object

Class for keeping track of a template with variables.

The template is template to calculate. The variables are variables to pass to the template. The rate_limit is a rate limit on how often the template is re-rendered.

rate_limit: timedelta | None = None
template = None
variables = None
class homeassistant.helpers.event.TrackTemplateResult(template: homeassistant.helpers.template.Template, last_result: Any, result: Any)[source]

Bases: object

Class for result of template tracking.

template

The template that has changed.

last_result

The output from the template on the last successful run, or None if no previous successful run.

result

Result from the template run. This will be a string or an TemplateError if the template resulted in an error.

last_result = None
result = None
template = None
homeassistant.helpers.event.async_call_later(hass: HomeAssistant, delay: float | timedelta, action: HassJob | Callable[..., Awaitable[None] | None]) → CALLBACK_TYPE[source]

Add a listener that is called in <delay>.

homeassistant.helpers.event.async_track_entity_registry_updated_event(hass: HomeAssistant, entity_ids: str | Iterable[str], action: Callable[[Event], Any]) → Callable[[], None][source]

Track specific entity registry updated events indexed by entity_id.

Similar to async_track_state_change_event.

homeassistant.helpers.event.async_track_point_in_time(hass: HomeAssistant, action: HassJob | Callable[..., Awaitable[None] | None], point_in_time: datetime) → CALLBACK_TYPE[source]

Add a listener that fires once after a specific point in time.

homeassistant.helpers.event.async_track_point_in_utc_time(hass: HomeAssistant, action: HassJob | Callable[..., Awaitable[None] | None], point_in_time: datetime) → CALLBACK_TYPE[source]

Add a listener that fires once after a specific point in UTC time.

homeassistant.helpers.event.async_track_same_state(hass: HomeAssistant, period: timedelta, action: Callable[..., Awaitable[None] | None], async_check_same_func: Callable[[str, State | None, State | None], bool], entity_ids: str | Iterable[str] = '*') → CALLBACK_TYPE[source]

Track the state of entities for a period and run an action.

If async_check_func is None it use the state of orig_value. Without entity_ids we track all state changes.

homeassistant.helpers.event.async_track_state_added_domain(hass: HomeAssistant, domains: str | Iterable[str], action: Callable[[Event], Any]) → Callable[[], None][source]

Track state change events when an entity is added to domains.

homeassistant.helpers.event.async_track_state_change(hass: HomeAssistant, entity_ids: str | Iterable[str], action: Callable[[str, State, State], Awaitable[None] | None], from_state: None | str | Iterable[str] = None, to_state: None | str | Iterable[str] = None) → CALLBACK_TYPE[source]

Track specific state changes.

entity_ids, from_state and to_state can be string or list. Use list to match multiple.

Returns a function that can be called to remove the listener.

If entity_ids are not MATCH_ALL along with from_state and to_state being None, async_track_state_change_event should be used instead as it is slightly faster.

Must be run within the event loop.

homeassistant.helpers.event.async_track_state_change_event(hass: HomeAssistant, entity_ids: str | Iterable[str], action: Callable[[Event], Any]) → Callable[[], None][source]

Track specific state change events indexed by entity_id.

Unlike async_track_state_change, async_track_state_change_event passes the full event to the callback.

In order to avoid having to iterate a long list of EVENT_STATE_CHANGED and fire and create a job for each one, we keep a dict of entity ids that care about the state change events so we can do a fast dict lookup to route events.

homeassistant.helpers.event.async_track_state_change_filtered(hass: homeassistant.core.HomeAssistant, track_states: homeassistant.helpers.event.TrackStates, action: Callable[[homeassistant.core.Event], Any]) → homeassistant.helpers.event._TrackStateChangeFiltered[source]

Track state changes with a TrackStates filter that can be updated.

hass

Home assistant object.

track_states

A TrackStates data class.

action

Callable to call with results.

Object used to update the listeners (async_update_listeners) with a new TrackStates or cancel the tracking (async_remove).

homeassistant.helpers.event.async_track_state_removed_domain(hass: HomeAssistant, domains: str | Iterable[str], action: Callable[[Event], Any]) → Callable[[], None][source]

Track state change events when an entity is removed from domains.

homeassistant.helpers.event.async_track_sunrise(hass: HomeAssistant, action: Callable[(Ellipsis, None)], offset: timedelta | None = None) → CALLBACK_TYPE[source]

Add a listener that will fire a specified offset from sunrise daily.

homeassistant.helpers.event.async_track_sunset(hass: HomeAssistant, action: Callable[(Ellipsis, None)], offset: timedelta | None = None) → CALLBACK_TYPE[source]

Add a listener that will fire a specified offset from sunset daily.

homeassistant.helpers.event.async_track_template(hass: HomeAssistant, template: Template, action: Callable[[str, State | None, State | None], Awaitable[None] | None], variables: TemplateVarsType | None = None) → Callable[[], None][source]

Add a listener that fires when a a template evaluates to ‘true’.

Listen for the result of the template becoming true, or a true-like string result, such as ‘On’, ‘Open’, or ‘Yes’. If the template results in an error state when the value changes, this will be logged and not passed through.

If the initial check of the template is invalid and results in an exception, the listener will still be registered but will only fire if the template result becomes true without an exception.

entity_id

ID of the entity that triggered the state change.

old_state

The old state of the entity that changed.

new_state

New state of the entity that changed.

hass

Home assistant object.

template

The template to calculate.

action

Callable to call with results. See above for arguments.

variables

Variables to pass to the template.

Callable to unregister the listener.

homeassistant.helpers.event.async_track_template_result(hass: HomeAssistant, track_templates: Iterable[TrackTemplate], action: TrackTemplateResultListener, raise_on_template_error: bool = False, strict: bool = False) → _TrackTemplateResultInfo[source]

Add a listener that fires when the result of a template changes.

The action will fire with the initial result from the template, and then whenever the output from the template changes. The template will be reevaluated if any states referenced in the last run of the template change, or if manually triggered. If the result of the evaluation is different from the previous run, the listener is passed the result.

If the template results in an TemplateError, this will be returned to the listener the first time this happens but not for subsequent errors. Once the template returns to a non-error condition the result is sent to the action as usual.

hass

Home assistant object.

track_templates

An iterable of TrackTemplate.

action

Callable to call with results.

raise_on_template_error

When set to True, if there is an exception processing the template during setup, the system will raise the exception instead of setting up tracking.

strict

When set to True, raise on undefined variables.

Info object used to unregister the listener, and refresh the template.

homeassistant.helpers.event.async_track_time_change(hass: HomeAssistant, action: Callable[(Ellipsis, None)], hour: Any | None = None, minute: Any | None = None, second: Any | None = None) → CALLBACK_TYPE[source]

Add a listener that will fire if UTC time matches a pattern.

homeassistant.helpers.event.async_track_time_interval(hass: HomeAssistant, action: Callable[..., Awaitable[None] | None], interval: timedelta) → CALLBACK_TYPE[source]

Add a listener that fires repetitively at every timedelta interval.

homeassistant.helpers.event.async_track_utc_time_change(hass: HomeAssistant, action: Callable[..., Awaitable[None] | None], hour: Any | None = None, minute: Any | None = None, second: Any | None = None, local: bool = False) → CALLBACK_TYPE[source]

Add a listener that will fire if time matches a pattern.

homeassistant.helpers.event.call_later(hass: HomeAssistant, delay: float | timedelta, action: HassJob | Callable[..., Awaitable[None] | None]) → CALLBACK_TYPE[source]

Add a listener that is called in <delay>.

homeassistant.helpers.event.process_state_match(parameter: None | str | Iterable[str]) → Callable[[str], bool][source]

Convert parameter to function that matches input against parameter.

homeassistant.helpers.event.threaded_listener_factory(async_factory: Callable[[...], Any]) → Callable[[...], Callable[[], None]][source]

Convert an async event helper to a threaded one.

homeassistant.helpers.event.track_point_in_time(hass: HomeAssistant, action: HassJob | Callable[..., Awaitable[None] | None], point_in_time: datetime) → CALLBACK_TYPE[source]

Add a listener that fires once after a specific point in time.

homeassistant.helpers.event.track_point_in_utc_time(hass: HomeAssistant, action: HassJob | Callable[..., Awaitable[None] | None], point_in_time: datetime) → CALLBACK_TYPE[source]

Add a listener that fires once after a specific point in UTC time.

homeassistant.helpers.event.track_same_state(hass: HomeAssistant, period: timedelta, action: Callable[..., Awaitable[None] | None], async_check_same_func: Callable[[str, State | None, State | None], bool], entity_ids: str | Iterable[str] = '*') → CALLBACK_TYPE[source]

Track the state of entities for a period and run an action.

If async_check_func is None it use the state of orig_value. Without entity_ids we track all state changes.

homeassistant.helpers.event.track_state_change(hass: HomeAssistant, entity_ids: str | Iterable[str], action: Callable[[str, State, State], Awaitable[None] | None], from_state: None | str | Iterable[str] = None, to_state: None | str | Iterable[str] = None) → CALLBACK_TYPE[source]

Track specific state changes.

entity_ids, from_state and to_state can be string or list. Use list to match multiple.

Returns a function that can be called to remove the listener.

If entity_ids are not MATCH_ALL along with from_state and to_state being None, async_track_state_change_event should be used instead as it is slightly faster.

Must be run within the event loop.

homeassistant.helpers.event.track_sunrise(hass: HomeAssistant, action: Callable[(Ellipsis, None)], offset: timedelta | None = None) → CALLBACK_TYPE[source]

Add a listener that will fire a specified offset from sunrise daily.

homeassistant.helpers.event.track_sunset(hass: HomeAssistant, action: Callable[(Ellipsis, None)], offset: timedelta | None = None) → CALLBACK_TYPE[source]

Add a listener that will fire a specified offset from sunset daily.

homeassistant.helpers.event.track_template(hass: HomeAssistant, template: Template, action: Callable[[str, State | None, State | None], Awaitable[None] | None], variables: TemplateVarsType | None = None) → Callable[[], None][source]

Add a listener that fires when a a template evaluates to ‘true’.

Listen for the result of the template becoming true, or a true-like string result, such as ‘On’, ‘Open’, or ‘Yes’. If the template results in an error state when the value changes, this will be logged and not passed through.

If the initial check of the template is invalid and results in an exception, the listener will still be registered but will only fire if the template result becomes true without an exception.

entity_id

ID of the entity that triggered the state change.

old_state

The old state of the entity that changed.

new_state

New state of the entity that changed.

hass

Home assistant object.

template

The template to calculate.

action

Callable to call with results. See above for arguments.

variables

Variables to pass to the template.

Callable to unregister the listener.

homeassistant.helpers.event.track_time_change(hass: HomeAssistant, action: Callable[(Ellipsis, None)], hour: Any | None = None, minute: Any | None = None, second: Any | None = None) → CALLBACK_TYPE[source]

Add a listener that will fire if UTC time matches a pattern.

homeassistant.helpers.event.track_time_interval(hass: HomeAssistant, action: Callable[..., Awaitable[None] | None], interval: timedelta) → CALLBACK_TYPE[source]

Add a listener that fires repetitively at every timedelta interval.

homeassistant.helpers.event.track_utc_time_change(hass: HomeAssistant, action: Callable[..., Awaitable[None] | None], hour: Any | None = None, minute: Any | None = None, second: Any | None = None, local: bool = False) → CALLBACK_TYPE[source]

Add a listener that will fire if time matches a pattern.

homeassistant.helpers.icon

Icon helper methods.

homeassistant.helpers.icon.icon_for_battery_level(battery_level: int | None = None, charging: bool = False) → str[source]

Return a battery icon valid identifier.

homeassistant.helpers.icon.icon_for_signal_level(signal_level: int | None = None) → str[source]

Return a signal icon valid identifier.

homeassistant.helpers.integration_platform

Helpers to help with integration platforms.

async homeassistant.helpers.integration_platform.async_process_integration_platforms(hass: HomeAssistant, platform_name: str, process_platform: Callable[[HomeAssistant, str, Any], Awaitable[None]]) → None[source]

Process a specific platform for all current and future loaded integrations.

homeassistant.helpers.intent

Module to coordinate user intentions.

class homeassistant.helpers.intent.Intent(hass: HomeAssistant, platform: str, intent_type: str, slots: _SlotsType, text_input: str | None, context: Context)[source]

Bases: object

Hold the intent.

context
create_response() → homeassistant.helpers.intent.IntentResponse[source]

Create a response.

hass
intent_type
platform
slots
text_input
exception homeassistant.helpers.intent.IntentError[source]

Bases: homeassistant.exceptions.HomeAssistantError

Base class for intent related errors.

exception homeassistant.helpers.intent.IntentHandleError[source]

Bases: homeassistant.helpers.intent.IntentError

Error while handling intent.

class homeassistant.helpers.intent.IntentHandler[source]

Bases: object

Intent handler registration.

async_can_handle(intent_obj: homeassistant.helpers.intent.Intent) → bool[source]

Test if an intent can be handled.

async async_handle(intent_obj: homeassistant.helpers.intent.Intent) → homeassistant.helpers.intent.IntentResponse[source]

Handle the intent.

async_validate_slots(slots: Dict[str, Any]) → Dict[str, Any][source]

Validate slot information.

intent_type: str | None = None
platforms: Iterable[str] | None = []
slot_schema: vol.Schema | None = None
class homeassistant.helpers.intent.IntentResponse(intent: Intent | None = None)[source]

Bases: object

Response to an intent.

as_dict() → dict[str, dict[str, dict[str, Any]]][source]

Return a dictionary representation of an intent response.

async_set_card(title: str, content: str, card_type: str = 'simple') → None[source]

Set speech response.

async_set_speech(speech: str, speech_type: str = 'plain', extra_data: Any | None = None) → None[source]

Set speech response.

exception homeassistant.helpers.intent.IntentUnexpectedError[source]

Bases: homeassistant.helpers.intent.IntentError

Unexpected error while handling intent.

exception homeassistant.helpers.intent.InvalidSlotInfo[source]

Bases: homeassistant.helpers.intent.IntentError

When the slot data is invalid.

class homeassistant.helpers.intent.ServiceIntentHandler(intent_type: str, domain: str, service: str, speech: str)[source]

Bases: homeassistant.helpers.intent.IntentHandler

Service Intent handler registration.

Service specific intent handler that calls a service by name/entity_id.

async async_handle(intent_obj: homeassistant.helpers.intent.Intent) → homeassistant.helpers.intent.IntentResponse[source]

Handle the hass intent.

slot_schema: vol.Schema | None = {'name': <function string>}
exception homeassistant.helpers.intent.UnknownIntent[source]

Bases: homeassistant.helpers.intent.IntentError

When the intent is not registered.

async homeassistant.helpers.intent.async_handle(hass: HomeAssistant, platform: str, intent_type: str, slots: _SlotsType | None = None, text_input: str | None = None, context: Context | None = None) → IntentResponse[source]

Handle an intent.

homeassistant.helpers.intent.async_match_state(hass: HomeAssistant, name: str, states: Iterable[State] | None = None) → State[source]

Find a state that matches the name.

homeassistant.helpers.intent.async_register(hass: homeassistant.core.HomeAssistant, handler: homeassistant.helpers.intent.IntentHandler) → None[source]

Register an intent with Home Assistant.

homeassistant.helpers.intent.async_test_feature(state: homeassistant.core.State, feature: int, feature_name: str) → None[source]

Test if state supports a feature.

homeassistant.helpers.json

Helpers to help with encoding Home Assistant objects in JSON.

class homeassistant.helpers.json.ExtendedJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: homeassistant.helpers.json.JSONEncoder

JSONEncoder that supports Home Assistant objects and falls back to repr(o).

default(o: Any) → Any[source]

Convert certain objects.

Fall back to repr(o).

class homeassistant.helpers.json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

JSONEncoder that supports Home Assistant objects.

default(o: Any) → Any[source]

Convert Home Assistant objects.

Hand other objects to the original method.

homeassistant.helpers.location

Location helpers for Home Assistant.

homeassistant.helpers.location.closest(latitude: float, longitude: float, states: Iterable[State]) → State | None[source]

Return closest state to point.

Async friendly.

homeassistant.helpers.location.find_coordinates(hass: HomeAssistant, entity_id: str, recursion_history: list | None = None) → str | None[source]

Find the gps coordinates of the entity in the form of ‘90.000,180.000’.

homeassistant.helpers.location.has_location(state: homeassistant.core.State) → bool[source]

Test if state contains a valid location.

Async friendly.

homeassistant.helpers.logging

Helpers for logging allowing more advanced logging styles to be used.

class homeassistant.helpers.logging.KeywordMessage(fmt: Any, args: Any, kwargs: Mapping[str, Any])[source]

Bases: object

Represents a logging message with keyword arguments.

Adapted from: https://stackoverflow.com/a/24683360/2267718

class homeassistant.helpers.logging.KeywordStyleAdapter(logger: logging.Logger, extra: Mapping[str, Any] | None = None)[source]

Bases: logging.LoggerAdapter

Represents an adapter wrapping the logger allowing KeywordMessages.

log(level: int, msg: Any, *args: Any, **kwargs: Any) → None[source]

Log the message provided at the appropriate level.

process(msg: Any, kwargs: MutableMapping[str, Any]) → tuple[Any, MutableMapping[str, Any]][source]

Process the keyword args in preparation for logging.

homeassistant.helpers.network

Network helpers.

exception homeassistant.helpers.network.NoURLAvailableError[source]

Bases: homeassistant.exceptions.HomeAssistantError

An URL to the Home Assistant instance is not available.

homeassistant.helpers.network.get_url(hass: homeassistant.core.HomeAssistant, *, require_current_request: bool = False, require_ssl: bool = False, require_standard_port: bool = False, allow_internal: bool = True, allow_external: bool = True, allow_cloud: bool = True, allow_ip: bool = True, prefer_external: bool = False, prefer_cloud: bool = False) → str[source]

Get a URL to this instance.

homeassistant.helpers.network.is_internal_request(hass: homeassistant.core.HomeAssistant) → bool[source]

Test if the current request is internal.

homeassistant.helpers.restore_state

Support for restoring entity states on startup.

class homeassistant.helpers.restore_state.RestoreEntity[source]

Bases: homeassistant.helpers.entity.Entity

Mixin class for restoring previous entity state.

async async_get_last_state() → State | None[source]

Get the entity state from the previous run.

async async_internal_added_to_hass() → None[source]

Register this entity as a restorable entity.

async async_internal_will_remove_from_hass() → None[source]

Run when entity will be removed from hass.

class homeassistant.helpers.restore_state.RestoreStateData(hass: homeassistant.core.HomeAssistant)[source]

Bases: object

Helper class for managing the helper saved data.

async async_dump_states() → None[source]

Save the current state machine to storage.

async classmethod async_get_instance(hass: homeassistant.core.HomeAssistant) → homeassistant.helpers.restore_state.RestoreStateData[source]

Get the singleton instance of this data helper.

async_get_stored_states() → list[StoredState][source]

Get the set of states which should be stored.

This includes the states of all registered entities, as well as the stored states from the previous run, which have not been created as entities on this run, and have not expired.

async_restore_entity_added(entity_id: str) → None[source]

Store this entity’s state when hass is shutdown.

async_restore_entity_removed(entity_id: str) → None[source]

Unregister this entity from saving state.

async_setup_dump(*args: Any) → None[source]

Set up the restore state listeners.

class homeassistant.helpers.restore_state.StoredState(state: homeassistant.core.State, last_seen: datetime.datetime)[source]

Bases: object

Object to represent a stored state.

as_dict() → dict[str, Any][source]

Return a dict representation of the stored state.

classmethod from_dict(json_dict: dict) → homeassistant.helpers.restore_state.StoredState[source]

Initialize a stored state from a dict.

homeassistant.helpers.script

Helpers to execute scripts.

class homeassistant.helpers.script.Script(hass: HomeAssistant, sequence: Sequence[dict[str, Any]], name: str, domain: str, *, running_description: str | None = None, change_listener: Callable[..., Any] | None = None, script_mode: str = 'single', max_runs: int = 10, max_exceeded: str = 'WARNING', logger: logging.Logger | None = None, log_exceptions: bool = True, top_level: bool = True, variables: ScriptVariables | None = None)[source]

Bases: object

Representation of a script.

async async_run(run_variables: _VarsType | None = None, context: Context | None = None, started_action: Callable[..., Any] | None = None) → None[source]

Run script.

async async_stop(update_state: bool = True, spare: _ScriptRun | None = None) → None[source]

Stop running script.

property change_listener

Return the change_listener.

property is_running

Return true if script is on.

property referenced_areas

Return a set of referenced areas.

property referenced_devices

Return a set of referenced devices.

property referenced_entities

Return a set of referenced entities.

run(variables: _VarsType | None = None, context: Context | None = None) → None[source]

Run script.

property runs

Return the number of current runs.

property supports_max

Return true if the current mode support max.

update_logger(logger: logging.Logger | None = None) → None[source]

Update logger.

homeassistant.helpers.script.action_trace_append(variables, path)[source]

Append a TraceElement to trace[path].

async homeassistant.helpers.script.async_validate_action_config(hass: homeassistant.core.HomeAssistant, config: Dict[str, Any]) → Dict[str, Any][source]

Validate config.

async homeassistant.helpers.script.async_validate_actions_config(hass: HomeAssistant, actions: list[ConfigType]) → list[ConfigType][source]

Validate a list of actions.

homeassistant.helpers.script.breakpoint_clear(hass, key, run_id, node)[source]

Clear a breakpoint.

homeassistant.helpers.script.breakpoint_clear_all(hass: homeassistant.core.HomeAssistant) → None[source]

Clear all breakpoints.

homeassistant.helpers.script.breakpoint_list(hass: HomeAssistant) → list[dict[str, Any]][source]

List breakpoints.

homeassistant.helpers.script.breakpoint_set(hass, key, run_id, node)[source]

Set a breakpoint.

homeassistant.helpers.script.debug_continue(hass, key, run_id)[source]

Continue execution of a halted script.

homeassistant.helpers.script.debug_step(hass, key, run_id)[source]

Single step a halted script.

homeassistant.helpers.script.debug_stop(hass, key, run_id)[source]

Stop execution of a running or halted script.

homeassistant.helpers.script.make_script_schema(schema, default_script_mode, extra=0)[source]

Make a schema for a component that uses the script helper.

homeassistant.helpers.script.trace_action(hass, script_run, stop, variables)[source]

Trace action execution.

homeassistant.helpers.service

Service calling related helpers.

class homeassistant.helpers.service.ReloadServiceHelper(service_func: Callable[[homeassistant.core.ServiceCall], collections.abc.Awaitable])[source]

Bases: object

Helper for reload services to minimize unnecessary reloads.

async execute_service(service_call: homeassistant.core.ServiceCall) → None[source]

Execute the service.

If a previous reload task if currently in progress, wait for it to finish first. Once the previous reload task has finished, one of the waiting tasks will be assigned to execute the reload, the others will wait for the reload to finish.

class homeassistant.helpers.service.SelectedEntities(referenced: set[str] = <factory>, indirectly_referenced: set[str] = <factory>, missing_devices: set[str] = <factory>, missing_areas: set[str] = <factory>, referenced_devices: set[str] = <factory>)[source]

Bases: object

Class to hold the selected entities.

indirectly_referenced = None
log_missing(missing_entities: set[str]) → None[source]

Log about missing items.

missing_areas = None
missing_devices = None
referenced = None
referenced_devices = None
class homeassistant.helpers.service.ServiceParams[source]

Bases: dict

Type for service call parameters.

domain = None
service = None
service_data = None
target = None
class homeassistant.helpers.service.ServiceTargetSelector(service_call: homeassistant.core.ServiceCall)[source]

Bases: object

Class to hold a target selector for a service.

property has_any_selector

Determine if any selectors are present.

async homeassistant.helpers.service.async_call_from_config(hass: HomeAssistant, config: ConfigType, blocking: bool = False, variables: TemplateVarsType = None, validate_config: bool = True, context: Context | None = None) → None[source]

Call a service based on a config hash.

async homeassistant.helpers.service.async_extract_config_entry_ids(hass: homeassistant.core.HomeAssistant, service_call: homeassistant.core.ServiceCall, expand_group: bool = True) → set[source]

Extract referenced config entry ids from a service call.

async homeassistant.helpers.service.async_extract_entities(hass: HomeAssistant, entities: Iterable[Entity], service_call: ServiceCall, expand_group: bool = True) → list[Entity][source]

Extract a list of entity objects from a service call.

Will convert group entity ids to the entity ids it represents.

async homeassistant.helpers.service.async_extract_entity_ids(hass: HomeAssistant, service_call: ServiceCall, expand_group: bool = True) → set[str][source]

Extract a set of entity ids from a service call.

Will convert group entity ids to the entity ids it represents.

async homeassistant.helpers.service.async_extract_referenced_entity_ids(hass: homeassistant.core.HomeAssistant, service_call: homeassistant.core.ServiceCall, expand_group: bool = True) → homeassistant.helpers.service.SelectedEntities[source]

Extract referenced entity IDs from a service call.

async homeassistant.helpers.service.async_get_all_descriptions(hass: HomeAssistant) → dict[str, dict[str, Any]][source]

Return descriptions (i.e. user documentation) for all service calls.

homeassistant.helpers.service.async_prepare_call_from_config(hass: homeassistant.core.HomeAssistant, config: Dict[str, Any], variables: Optional[Mapping[str, Any]] = None, validate_config: bool = False) → homeassistant.helpers.service.ServiceParams[source]

Prepare to call a service based on a config hash.

homeassistant.helpers.service.async_register_admin_service(hass: HomeAssistant, domain: str, service: str, service_func: Callable[[ServiceCall], Awaitable | None], schema: vol.Schema = <Schema({}, extra=PREVENT_EXTRA, required=False) object>) → None[source]

Register a service that requires admin access.

homeassistant.helpers.service.async_set_service_schema(hass: HomeAssistant, domain: str, service: str, schema: dict[str, Any]) → None[source]

Register a description for a service.

homeassistant.helpers.service.call_from_config(hass: homeassistant.core.HomeAssistant, config: Dict[str, Any], blocking: bool = False, variables: Optional[Mapping[str, Any]] = None, validate_config: bool = True) → None[source]

Call a service based on a config hash.

async homeassistant.helpers.service.entity_service_call(hass: HomeAssistant, platforms: Iterable[EntityPlatform], func: str | Callable[..., Any], call: ServiceCall, required_features: Iterable[int] | None = None) → None[source]

Handle an entity service call.

Calls all platforms simultaneously.

homeassistant.helpers.service.extract_entity_ids(hass: HomeAssistant, service_call: ServiceCall, expand_group: bool = True) → set[str][source]

Extract a list of entity ids from a service call.

Will convert group entity ids to the entity ids it represents.

homeassistant.helpers.service.verify_domain_control(hass: homeassistant.core.HomeAssistant, domain: str) → Callable[[Callable[[homeassistant.core.ServiceCall], Any]], Callable[[homeassistant.core.ServiceCall], Any]][source]

Ensure permission to access any entity under domain in service call.

homeassistant.helpers.signal

Signal handling related helpers.

homeassistant.helpers.signal.async_register_signal_handling(hass: homeassistant.core.HomeAssistant) → None[source]

Register system signal handler for core.

homeassistant.helpers.state

Helpers that help with state related things.

class homeassistant.helpers.state.AsyncTrackStates(hass: homeassistant.core.HomeAssistant)[source]

Bases: object

Record the time when the with-block is entered.

Add all states that have changed since the start time to the return list when with-block is exited.

Must be run within the event loop.

Deprecated. Remove after June 2021. Warning added via get_changed_since.

async homeassistant.helpers.state.async_reproduce_state(hass: HomeAssistant, states: State | Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None) → None[source]

Reproduce a list of states on multiple domains.

homeassistant.helpers.state.get_changed_since(states: Iterable[State], utc_point_in_time: dt.datetime) → list[State][source]

Return list of states that have been changed since utc_point_in_time.

Deprecated. Remove after June 2021.

homeassistant.helpers.state.state_as_number(state: homeassistant.core.State) → float[source]

Try to coerce our state to a number.

Raises ValueError if this is not possible.

homeassistant.helpers.storage

Helper to help store data.

class homeassistant.helpers.storage.Store(hass: HomeAssistant, version: int, key: str, private: bool = False, *, encoder: type[JSONEncoder] | None = None)[source]

Bases: object

Class to help storing data.

async_delay_save(data_func: Callable[[], dict], delay: float = 0) → None[source]

Save data with an optional delay.

async async_load() → dict | list | None[source]

Load data.

If the expected version does not match the given version, the migrate function will be invoked with await migrate_func(version, config).

Will ensure that when a call comes in while another one is in progress, the second call will wait and return the result of the first call.

async async_remove() → None[source]

Remove all data.

async async_save(data: dict | list) → None[source]

Save data.

property path

Return the config path.

async homeassistant.helpers.storage.async_migrator(hass, old_path, store, *, old_conf_load_func=None, old_conf_migrate_func=None)[source]

Migrate old data to a store and then load data.

async def old_conf_migrate_func(old_data)

homeassistant.helpers.sun

Helpers for sun events.

homeassistant.helpers.sun.get_astral_event_date(hass: HomeAssistant, event: str, date: datetime.date | datetime.datetime | None = None) → datetime.datetime | None[source]

Calculate the astral event time for the specified date.

homeassistant.helpers.sun.get_astral_event_next(hass: HomeAssistant, event: str, utc_point_in_time: datetime.datetime | None = None, offset: datetime.timedelta | None = None) → datetime.datetime[source]

Calculate the next specified solar event.

homeassistant.helpers.sun.get_astral_location(hass: HomeAssistant) → tuple[astral.location.Location, astral.Elevation][source]

Get an astral location for the current Home Assistant configuration.

homeassistant.helpers.sun.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[source]

Calculate the next specified solar event.

homeassistant.helpers.sun.is_up(hass: HomeAssistant, utc_point_in_time: datetime.datetime | None = None) → bool[source]

Calculate if the sun is currently up.

homeassistant.helpers.system_info

Helper to gather system info.

async homeassistant.helpers.system_info.async_get_system_info(hass: HomeAssistant) → dict[str, Any][source]

Return info about the system.

homeassistant.helpers.temperature

Temperature helpers for Home Assistant.

homeassistant.helpers.temperature.display_temp(hass: HomeAssistant, temperature: float | None, unit: str, precision: float) → float | None[source]

Convert temperature into preferred units/precision for display.

homeassistant.helpers.template

Template helper methods for rendering strings with Home Assistant data.

class homeassistant.helpers.template.AllStates(hass: homeassistant.core.HomeAssistant)[source]

Bases: object

Class to expose all HA states as attributes.

class homeassistant.helpers.template.DomainStates(hass: homeassistant.core.HomeAssistant, domain: str)[source]

Bases: object

Class to expose a specific HA domain as attributes.

class homeassistant.helpers.template.LoggingUndefined(hint: Optional[str] = None, obj: Any = missing, name: Optional[str] = None, exc: Type[jinja2.exceptions.TemplateRuntimeError] = <class 'jinja2.exceptions.UndefinedError'>)[source]

Bases: jinja2.runtime.Undefined

Log on undefined variables.

class homeassistant.helpers.template.RenderInfo(template: homeassistant.helpers.template.Template)[source]

Bases: object

Holds information about a template render.

result() → str[source]

Results of the template computation.

class homeassistant.helpers.template.ResultWrapper[source]

Bases: object

Result wrapper class to store render result.

render_result = None
class homeassistant.helpers.template.Template(template, hass=None)[source]

Bases: object

Class to hold a template and manage caching and rendering.

async_render(variables: Optional[Mapping[str, Any]] = None, parse_result: bool = True, limited: bool = False, strict: bool = False, **kwargs: Any) → Any[source]

Render given template.

This method must be run in the event loop.

If limited is True, the template is not allowed to access any function or filter depending on hass or the state machine.

async_render_to_info(variables: Optional[Mapping[str, Any]] = None, strict: bool = False, **kwargs: Any) → homeassistant.helpers.template.RenderInfo[source]

Render the template and collect an entity filter.

async async_render_will_timeout(timeout: float, variables: Optional[Mapping[str, Any]] = None, strict: bool = False, **kwargs: Any) → bool[source]

Check to see if rendering a template will timeout during render.

This is intended to check for expensive templates that will make the system unstable. The template is rendered in the executor to ensure it does not tie up the event loop.

This function is not a security control and is only intended to be used as a safety check when testing templates.

This method must be run in the event loop.

async_render_with_possible_json_value(value, error_value=<object object>, variables=None)[source]

Render template with value exposed.

If valid JSON will expose value_json too.

This method must be run in the event loop.

ensure_valid() → None[source]

Return if template is valid.

hass
is_static
render(variables: Optional[Mapping[str, Any]] = None, parse_result: bool = True, limited: bool = False, **kwargs: Any) → Any[source]

Render given template.

If limited is True, the template is not allowed to access any function or filter depending on hass or the state machine.

render_with_possible_json_value(value, error_value=<object object>)[source]

Render template with value exposed.

If valid JSON will expose value_json too.

template
class homeassistant.helpers.template.TemplateEnvironment(hass, limited=False, strict=False)[source]

Bases: jinja2.sandbox.ImmutableSandboxedEnvironment

The Home Assistant template environment.

compile(source, name=None, filename=None, raw=False, defer_init=False)[source]

Compile the template.

is_safe_attribute(obj, attr, value)[source]

Test if attribute is safe.

is_safe_callable(obj)[source]

Test if callback is safe.

class homeassistant.helpers.template.TemplateState(hass: homeassistant.core.HomeAssistant, state: homeassistant.core.State, collect: bool = True)[source]

Bases: homeassistant.core.State

Class to represent a state object in a template.

property attributes

Wrap State.attributes.

property context

Wrap State.context.

property domain

Wrap State.domain.

property entity_id

Wrap State.entity_id.

Intentionally does not collect state

property last_changed

Wrap State.last_changed.

property last_updated

Wrap State.last_updated.

property name

Wrap State.name.

property object_id

Wrap State.object_id.

property state

Wrap State.state.

property state_with_unit

Return the state concatenated with the unit if available.

class homeassistant.helpers.template.TupleWrapper(value: tuple, *, render_result: str | None = None)[source]

Bases: tuple, homeassistant.helpers.template.ResultWrapper

Wrap a tuple.

render_result = None
homeassistant.helpers.template.arc_cosine(value)[source]

Filter to get arc cosine of the value.

homeassistant.helpers.template.arc_sine(value)[source]

Filter to get arc sine of the value.

homeassistant.helpers.template.arc_tangent(value)[source]

Filter to get arc tangent of the value.

homeassistant.helpers.template.arc_tangent2(*args)[source]

Filter to calculate four quadrant arc tangent of y / x.

homeassistant.helpers.template.attach(hass: homeassistant.core.HomeAssistant, obj: Any) → None[source]

Recursively attach hass to all template instances in list and dict.

homeassistant.helpers.template.base64_decode(value)[source]

Perform base64 denode.

homeassistant.helpers.template.base64_encode(value)[source]

Perform base64 encode.

homeassistant.helpers.template.bitwise_and(first_value, second_value)[source]

Perform a bitwise and operation.

homeassistant.helpers.template.bitwise_or(first_value, second_value)[source]

Perform a bitwise or operation.

homeassistant.helpers.template.closest(hass, *args)[source]

Find closest entity.

Closest to home:

closest(states) closest(states.device_tracker) closest(‘group.children’) closest(states.group.children)

Closest to a point:

closest(23.456, 23.456, ‘group.children’) closest(‘zone.school’, ‘group.children’) closest(states.zone.school, ‘group.children’)

As a filter:

states | closest states.device_tracker | closest [‘group.children’, states.device_tracker] | closest ‘group.children’ | closest(23.456, 23.456) states.device_tracker | closest(‘zone.school’) ‘group.children’ | closest(states.zone.school)

homeassistant.helpers.template.closest_filter(hass, *args)[source]

Call closest as a filter. Need to reorder arguments.

homeassistant.helpers.template.cosine(value)[source]

Filter to get cosine of the value.

homeassistant.helpers.template.device_entities(hass: HomeAssistant, device_id: str) → Iterable[str][source]

Get entity ids for entities tied to a device.

homeassistant.helpers.template.distance(hass, *args)[source]

Calculate distance.

Will calculate distance from home to a point or between points. Points can be passed in using state objects or lat/lng coordinates.

homeassistant.helpers.template.expand(hass: HomeAssistant, *args: Any) → Iterable[State][source]

Expand out any groups into entity states.

homeassistant.helpers.template.fail_when_undefined(value)[source]

Filter to force a failure when the value is undefined.

homeassistant.helpers.template.forgiving_as_timestamp(value)[source]

Try to convert value to timestamp.

homeassistant.helpers.template.forgiving_float(value)[source]

Try to convert value to a float.

homeassistant.helpers.template.forgiving_round(value, precision=0, method='common')[source]

Round accepted strings.

homeassistant.helpers.template.from_json(value)[source]

Convert a JSON string to an object.

homeassistant.helpers.template.gen_result_wrapper(kls)[source]

Generate a result wrapper.

homeassistant.helpers.template.is_complex(value: Any) → bool[source]

Test if data structure is a complex template.

homeassistant.helpers.template.is_state(hass: homeassistant.core.HomeAssistant, entity_id: str, state: homeassistant.core.State) → bool[source]

Test if a state is a specific value.

homeassistant.helpers.template.is_state_attr(hass: homeassistant.core.HomeAssistant, entity_id: str, name: str, value: Any) → bool[source]

Test if a state’s attribute is a specific value.

homeassistant.helpers.template.is_template_string(maybe_template: str) → bool[source]

Check if the input is a Jinja2 template.

homeassistant.helpers.template.logarithm(value, base=2.718281828459045)[source]

Filter to get logarithm of the value with a specific base.

homeassistant.helpers.template.multiply(value, amount)[source]

Filter to convert value to float and multiply it.

homeassistant.helpers.template.now(hass: homeassistant.core.HomeAssistant) → datetime.datetime[source]

Record fetching now.

homeassistant.helpers.template.ordinal(value)[source]

Perform ordinal conversion.

homeassistant.helpers.template.random_every_time(context, values)[source]

Choose a random value.

Unlike Jinja’s random filter, this is context-dependent to avoid caching the chosen value.

homeassistant.helpers.template.regex_findall_index(value, find='', index=0, ignorecase=False)[source]

Find all matches using regex and then pick specific match index.

homeassistant.helpers.template.regex_match(value, find='', ignorecase=False)[source]

Match value using regex.

homeassistant.helpers.template.regex_replace(value='', find='', replace='', ignorecase=False)[source]

Replace using regex.

Search using regex.

homeassistant.helpers.template.relative_time(value)[source]

Take a datetime and return its “age” as a string.

The age can be in second, minute, hour, day, month or year. Only the biggest unit is considered, e.g. if it’s 2 days and 3 hours, “2 days” will be returned. Make sure date is not in the future, or else it will return None.

If the input are not a datetime object the input will be returned unmodified.

homeassistant.helpers.template.render_complex(value: Any, variables: Optional[Mapping[str, Any]] = None, limited: bool = False) → Any[source]

Recursive template creator helper function.

homeassistant.helpers.template.result_as_boolean(template_result: str | None) → bool[source]

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

homeassistant.helpers.template.sine(value)[source]

Filter to get sine of the value.

homeassistant.helpers.template.square_root(value)[source]

Filter to get square root of the value.

homeassistant.helpers.template.state_attr(hass: homeassistant.core.HomeAssistant, entity_id: str, name: str) → Any[source]

Get a specific attribute from a state.

homeassistant.helpers.template.strptime(string, fmt)[source]

Parse a time string to datetime.

homeassistant.helpers.template.tangent(value)[source]

Filter to get tangent of the value.

homeassistant.helpers.template.timestamp_custom(value, date_format='%Y-%m-%d %H:%M:%S', local=True)[source]

Filter to convert given timestamp to format.

homeassistant.helpers.template.timestamp_local(value)[source]

Filter to convert given timestamp to local date/time.

homeassistant.helpers.template.timestamp_utc(value)[source]

Filter to convert given timestamp to UTC date/time.

homeassistant.helpers.template.to_json(value)[source]

Convert an object to a JSON string.

homeassistant.helpers.template.urlencode(value)[source]

Urlencode dictionary and return as UTF-8 string.

homeassistant.helpers.template.utcnow(hass: homeassistant.core.HomeAssistant) → datetime.datetime[source]

Record fetching utcnow.

homeassistant.helpers.translation

Translation string lookup helpers.

async homeassistant.helpers.translation.async_get_component_strings(hass: HomeAssistant, language: str, components: set[str]) → dict[str, Any][source]

Load translations.

async homeassistant.helpers.translation.async_get_translations(hass: HomeAssistant, language: str, category: str, integration: str | None = None, config_flow: bool | None = None) → dict[str, Any][source]

Return all backend translations.

If integration specified, load it for that one. Otherwise default to loaded intgrations combined with config flow integrations if config_flow is true.

homeassistant.helpers.translation.component_translation_path(component: str, language: str, integration: Integration) → str | None[source]

Return the translation json file location for a component.

For component:
  • components/hue/translations/nl.json

For platform:
  • components/hue/translations/light.nl.json

If component is just a single file, will return None.

homeassistant.helpers.translation.load_translations_files(translation_files: dict[str, str]) → dict[str, dict[str, Any]][source]

Load and parse translation.json files.

homeassistant.helpers.translation.recursive_flatten(prefix: Any, data: dict) → dict[str, Any][source]

Return a flattened representation of dict data.

homeassistant.helpers.typing

Typing Helpers for Home Assistant.

class homeassistant.helpers.typing.UndefinedType[source]

Bases: enum.Enum

Singleton type for use with not set sentinel values.

homeassistant.helpers.update_coordinator

Helpers to help coordinate updates.

class homeassistant.helpers.update_coordinator.CoordinatorEntity(coordinator: homeassistant.helpers.update_coordinator.DataUpdateCoordinator[~T][T])[source]

Bases: typing.Generic, homeassistant.helpers.entity.Entity

A class for entities using DataUpdateCoordinator.

async async_added_to_hass() → None[source]

When entity is added to hass.

async async_update() → None[source]

Update the entity.

Only used by the generic entity update service.

property available

Return if entity is available.

property should_poll

No need to poll. Coordinator notifies entity of updates.

class homeassistant.helpers.update_coordinator.DataUpdateCoordinator(hass: HomeAssistant, logger: logging.Logger, *, name: str, update_interval: timedelta | None = None, update_method: Callable[[], Awaitable[T]] | None = None, request_refresh_debouncer: Debouncer | None = None)[source]

Bases: typing.Generic

Class to manage fetching data from single endpoint.

async_add_listener(update_callback: Callable[[], None]) → Callable[[], None][source]

Listen for data updates.

async async_config_entry_first_refresh() → None[source]

Refresh data for the first time when a config entry is setup.

Will automatically raise ConfigEntryNotReady if the refresh fails. Additionally logging is handled by config entry setup to ensure that multiple retries do not cause log spam.

async async_refresh() → None[source]

Refresh data and log errors.

async_remove_listener(update_callback: Callable[[], None]) → None[source]

Remove data update.

async async_request_refresh() → None[source]

Request a refresh.

Refresh will wait a bit to see if it can batch them.

async_set_updated_data(data: T) → None[source]

Manually update data, notify listeners and reset refresh interval.

exception homeassistant.helpers.update_coordinator.UpdateFailed[source]

Bases: Exception

Raised when an update has failed.