homeassistant.helpers package

Submodules

homeassistant.helpers.condition module

Offer reusable conditions.

homeassistant.helpers.condition.and_from_config(config: typing.Dict[str, typing.Any], config_validation: bool = True)[source]

Create multi condition matcher using ‘AND’.

homeassistant.helpers.condition.async_and_from_config(config: typing.Dict[str, typing.Any], config_validation: bool = True)[source]

Create multi condition matcher using ‘AND’.

homeassistant.helpers.condition.async_from_config(config: typing.Dict[str, typing.Any], config_validation: bool = True)[source]

Turn a condition configuration into a method.

Should be run on the event loop.

homeassistant.helpers.condition.async_numeric_state(hass: homeassistant.core.HomeAssistant, entity, below=None, above=None, value_template=None, variables=None)[source]

Test a numeric state condition.

homeassistant.helpers.condition.async_numeric_state_from_config(config, config_validation=True)[source]

Wrap action method with state based condition.

homeassistant.helpers.condition.async_or_from_config(config: typing.Dict[str, typing.Any], config_validation: bool = True)[source]

Create multi condition matcher using ‘OR’.

homeassistant.helpers.condition.async_template(hass, value_template, variables=None)[source]

Test if template condition matches.

homeassistant.helpers.condition.async_template_from_config(config, config_validation=True)[source]

Wrap action method with state based condition.

homeassistant.helpers.condition.from_config(config: typing.Dict[str, typing.Any], config_validation: bool = True)[source]

Turn a condition configuration into a method.

Should be run on the event loop.

homeassistant.helpers.condition.numeric_state(hass: homeassistant.core.HomeAssistant, entity, below=None, above=None, value_template=None, variables=None)[source]

Test a numeric state condition.

homeassistant.helpers.condition.numeric_state_from_config(config, config_validation=True)[source]

Wrap action method with state based condition.

homeassistant.helpers.condition.or_from_config(config: typing.Dict[str, typing.Any], config_validation: bool = True)[source]

Create multi condition matcher using ‘OR’.

homeassistant.helpers.condition.state(hass, entity, req_state, for_period=None)[source]

Test if state matches requirements.

Async friendly.

homeassistant.helpers.condition.state_from_config(config, config_validation=True)[source]

Wrap action method with state based condition.

homeassistant.helpers.condition.sun(hass, before=None, after=None, before_offset=None, after_offset=None)[source]

Test if current time matches sun requirements.

homeassistant.helpers.condition.sun_from_config(config, config_validation=True)[source]

Wrap action method with sun based condition.

homeassistant.helpers.condition.template(hass, value_template, variables=None)[source]

Test if template condition matches.

homeassistant.helpers.condition.template_from_config(config, config_validation=True)[source]

Wrap action method with state based condition.

homeassistant.helpers.condition.time(before=None, after=None, weekday=None)[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, config_validation=True)[source]

Wrap action method with time based condition.

homeassistant.helpers.condition.zone(hass, zone_ent, entity)[source]

Test if zone-condition matches.

Async friendly.

homeassistant.helpers.condition.zone_from_config(config, config_validation=True)[source]

Wrap action method with zone based condition.

homeassistant.helpers.config_validation module

Helpers for config validation using voluptuous.

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

Validate and coerce a boolean value.

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

Validate and transform a date.

homeassistant.helpers.config_validation.datetime(value)[source]

Validate datetime.

homeassistant.helpers.config_validation.ensure_list(value: typing.Union[T, typing.Sequence[T]]) → typing.Sequence[T][source]

Wrap value in list if it is not one.

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

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

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

Validate Entity ID.

homeassistant.helpers.config_validation.entity_ids(value: typing.Sequence) → typing.Sequence[str][source]

Validate Entity IDs.

homeassistant.helpers.config_validation.enum(enumClass)[source]

Create validator for specified enum.

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

Validate that at least one key exists.

homeassistant.helpers.config_validation.has_at_least_one_key_value(*items: list) → typing.Callable[source]

Validate that at least one (key, value) pair exists.

homeassistant.helpers.config_validation.icon(value)[source]

Validate icon.

homeassistant.helpers.config_validation.isdevice(value)[source]

Validate that value is a real device.

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

Validate that the value is an existing dir.

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

Validate that the value is an existing file.

homeassistant.helpers.config_validation.key_dependency(key, dependency)[source]

Validate that all dependencies exist for key.

homeassistant.helpers.config_validation.match_all(value)[source]

Validate that matches all values.

homeassistant.helpers.config_validation.platform_validator(domain)[source]

Validate if platform exists for given domain.

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

Validate timedelta is positive.

homeassistant.helpers.config_validation.service(value)[source]

Validate service.

homeassistant.helpers.config_validation.slug(value)[source]

Validate value is a valid slug.

homeassistant.helpers.config_validation.slugify(value)[source]

Coerce a value to a slug.

homeassistant.helpers.config_validation.socket_timeout(value)[source]

Validate timeout float > 0.0.

None coerced to socket._GLOBAL_DEFAULT_TIMEOUT bare object.

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

Coerce value to string, except for None.

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

Validate and transform temperature unit.

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

Validate a jinja2 template.

homeassistant.helpers.config_validation.template_complex(value)[source]

Validate a complex jinja2 template.

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

Validate and transform a time.

homeassistant.helpers.config_validation.time_period_seconds(value: typing.Union[int, str]) → datetime.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)[source]

Validate timezone.

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

Validate an URL.

homeassistant.helpers.config_validation.x10_address(value)[source]

Validate an x10 address.

homeassistant.helpers.discovery module

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.
homeassistant.helpers.discovery.async_discover(hass, service, discovered=None, component=None, hass_config=None)[source]

Fire discovery event. Can ensure a component is loaded.

homeassistant.helpers.discovery.async_listen(hass, service, callback)[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, component, callback)[source]

Register a platform loader listener.

This method must be run in the event loop.

homeassistant.helpers.discovery.async_load_platform(hass, component, platform, discovered=None, hass_config=None)[source]

Load a component and platform dynamically.

Target components will be loaded and an EVENT_PLATFORM_DISCOVERED will be fired to load the platform. The event will contain:

{ ATTR_SERVICE = LOAD_PLATFORM + ‘.’ + <<component>>
ATTR_PLATFORM = <<platform>> ATTR_DISCOVERED = <<discovery info>> }

Use listen_platform to register a callback for these events.

Warning: Do not yield from this inside a setup method to avoid a dead lock. Use hass.loop.async_add_job(async_load_platform(..)) instead.

This method is a coroutine.

homeassistant.helpers.discovery.discover(hass, service, discovered=None, component=None, hass_config=None)[source]

Fire discovery event. Can ensure a component is loaded.

homeassistant.helpers.discovery.listen(hass, service, callback)[source]

Set up listener for discovery of specific service.

Service can be a string or a list/tuple.

homeassistant.helpers.discovery.listen_platform(hass, component, callback)[source]

Register a platform loader listener.

homeassistant.helpers.discovery.load_platform(hass, component, platform, discovered=None, hass_config=None)[source]

Load a component and platform dynamically.

Target components will be loaded and an EVENT_PLATFORM_DISCOVERED will be fired to load the platform. The event will contain:

{ ATTR_SERVICE = LOAD_PLATFORM + ‘.’ + <<component>>
ATTR_PLATFORM = <<platform>> ATTR_DISCOVERED = <<discovery info>> }

Use listen_platform to register a callback for these events.

homeassistant.helpers.entity module

An abstract class for entities.

class homeassistant.helpers.entity.Entity[source]

Bases: object

An abstract class for Home Assistant entities.

assumed_state

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

async_device_update(warning=True)[source]

Process ‘update’ or ‘async_update’ from entity.

This method is a coroutine.

async_remove() → None[source]

Remove entity from async HASS.

This method must be run in the event loop.

async_schedule_update_ha_state(force_refresh=False)[source]

Schedule a update ha state change task.

async_update_ha_state(force_refresh=False)[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.

available

Return True if entity is available.

device_class

Return the class of this device, from component DEVICE_CLASSES.

device_state_attributes

Return device specific state attributes.

Implemented by platform classes.

entity_id = None
entity_picture

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

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 = None
hidden

Return True if the entity should be hidden from UIs.

icon

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

name

Return the name of the entity.

parallel_updates = None
remove() → None[source]

Remove entity from HASS.

schedule_update_ha_state(force_refresh=False)[source]

Schedule a update ha state change task.

That avoid executor dead looks.

should_poll

Return True if entity has to be polled for state.

False if entity pushes its state to HA.

state

Return the state of the entity.

state_attributes

Return the state attributes.

Implemented by component base class.

supported_features

Flag supported features.

unique_id

Return an unique ID.

unit_of_measurement

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

update()[source]

Retrieve latest state.

When not implemented, will forward call to async version if available.

class homeassistant.helpers.entity.ToggleEntity[source]

Bases: homeassistant.helpers.entity.Entity

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

async_toggle(**kwargs)[source]

Toggle the entity.

This method must be run in the event loop and returns a coroutine.

async_turn_off(**kwargs)[source]

Turn the entity off.

This method must be run in the event loop and returns a coroutine.

async_turn_on(**kwargs)[source]

Turn the entity on.

This method must be run in the event loop and returns a coroutine.

is_on

Return True if entity is on.

state

Return the state.

toggle(**kwargs) → None[source]

Toggle the entity.

turn_off(**kwargs) → None[source]

Turn the entity off.

turn_on(**kwargs) → None[source]

Turn the entity on.

homeassistant.helpers.entity.async_generate_entity_id(entity_id_format: str, name: typing.Union[str, NoneType], current_ids: typing.Union[typing.List[str], NoneType] = None, hass: typing.Union[homeassistant.core.HomeAssistant, NoneType] = None) → str[source]

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

homeassistant.helpers.entity.generate_entity_id(entity_id_format: str, name: typing.Union[str, NoneType], current_ids: typing.Union[typing.List[str], NoneType] = None, hass: typing.Union[homeassistant.core.HomeAssistant, NoneType] = None) → str[source]

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

homeassistant.helpers.entity_component module

Helpers for components that manage entities.

class homeassistant.helpers.entity_component.EntityComponent(logger, domain, hass, scan_interval=datetime.timedelta(0, 15), group_name=None)[source]

Bases: object

Helper class that will help a component manage its entities.

add_entity(entity, platform=None, update_before_add=False)[source]

Add entity to component.

async_add_entity(entity, platform=None, update_before_add=False)[source]

Add entity to component.

This method must be run in the event loop.

async_extract_from_service(service, expand_group=True)[source]

Extract all known and available entities from a service call.

Will return all entities if no entities specified in call. Will return an empty list if entities specified but unknown.

This method must be run in the event loop.

async_prepare_reload()[source]

Prepare reloading this entity component.

This method must be run in the event loop.

async_reset()[source]

Remove entities and reset the entity component to initial values.

This method must be run in the event loop.

async_setup(config)[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_update_group()[source]

Set up and/or update component group.

This method must be run in the event loop.

extract_from_service(service, expand_group=True)[source]

Extract all known entities from a service call.

Will return all entities if no entities specified in call. Will return an empty list if entities specified but unknown.

prepare_reload()[source]

Prepare reloading this entity component.

reset()[source]

Remove entities and reset the entity component to initial values.

setup(config)[source]

Set up a full entity component.

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

update_group()[source]

Set up and/or update component group.

class homeassistant.helpers.entity_component.EntityPlatform(component, platform, scan_interval, parallel_updates, entity_namespace)[source]

Bases: object

Keep track of entities for a single platform and stay in loop.

add_entities(new_entities, update_before_add=False)[source]

Add entities for a single platform.

async_add_entities(new_entities, update_before_add=False)[source]

Add entities for a single platform async.

This method must be run in the event loop.

async_block_entities_done()[source]

Wait until all entities add to hass.

async_reset()[source]

Remove all entities and reset data.

This method must be run in the event loop.

async_schedule_add_entities(new_entities, update_before_add=False)[source]

Add entities for a single platform async.

schedule_add_entities(new_entities, update_before_add=False)[source]

Add entities for a single platform.

homeassistant.helpers.event module

Helpers for listening to events.

homeassistant.helpers.event.async_track_point_in_time(hass, action, point_in_time)[source]

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

homeassistant.helpers.event.async_track_point_in_utc_time(hass, action, point_in_time)[source]

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

homeassistant.helpers.event.async_track_same_state(hass, period, action, async_check_same_func, entity_ids='*')[source]

Track the state of entities for a period and run a 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_change(hass, entity_ids, action, from_state=None, to_state=None)[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.

Must be run within the event loop.

homeassistant.helpers.event.async_track_sunrise(hass, action, offset=None)[source]

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

homeassistant.helpers.event.async_track_sunset(hass, action, offset=None)[source]

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

homeassistant.helpers.event.async_track_template(hass, template, action, variables=None)[source]

Add a listener that track state changes with template condition.

homeassistant.helpers.event.async_track_time_change(hass, action, year=None, month=None, day=None, hour=None, minute=None, second=None)[source]

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

homeassistant.helpers.event.async_track_time_interval(hass, action, interval)[source]

Add a listener that fires repetitively at every timedelta interval.

homeassistant.helpers.event.async_track_utc_time_change(hass, action, year=None, month=None, day=None, hour=None, minute=None, second=None, local=False)[source]

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

homeassistant.helpers.event.threaded_listener_factory(async_factory)[source]

Convert an async event helper to a threaded one.

homeassistant.helpers.event.track_point_in_time(hass, action, point_in_time)[source]

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

homeassistant.helpers.event.track_point_in_utc_time(hass, action, point_in_time)[source]

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

homeassistant.helpers.event.track_same_state(hass, period, action, async_check_same_func, entity_ids='*')[source]

Track the state of entities for a period and run a 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, entity_ids, action, from_state=None, to_state=None)[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.

Must be run within the event loop.

homeassistant.helpers.event.track_sunrise(hass, action, offset=None)[source]

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

homeassistant.helpers.event.track_sunset(hass, action, offset=None)[source]

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

homeassistant.helpers.event.track_template(hass, template, action, variables=None)[source]

Add a listener that track state changes with template condition.

homeassistant.helpers.event.track_time_change(hass, action, year=None, month=None, day=None, hour=None, minute=None, second=None)[source]

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

homeassistant.helpers.event.track_time_interval(hass, action, interval)[source]

Add a listener that fires repetitively at every timedelta interval.

homeassistant.helpers.event.track_utc_time_change(hass, action, year=None, month=None, day=None, hour=None, minute=None, second=None, local=False)[source]

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

homeassistant.helpers.event_decorators module

homeassistant.helpers.location module

Location helpers for Home Assistant.

homeassistant.helpers.location.closest(latitude: float, longitude: float, states: typing.Sequence[homeassistant.core.State]) → homeassistant.core.State[source]

Return closest state to point.

Async friendly.

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

Test if state contains a valid location.

Async friendly.

homeassistant.helpers.script module

Helpers to execute scripts.

class homeassistant.helpers.script.Script(hass: homeassistant.core.HomeAssistant, sequence, name: str = None, change_listener=None) → None[source]

Bases: object

Representation of a script.

async_run(variables: typing.Union[typing.Sequence, NoneType] = None) → None[source]

Run script.

This method is a coroutine.

async_stop() → None[source]

Stop running script.

is_running

Return true if script is on.

run(variables=None)[source]

Run script.

stop() → None[source]

Stop running script.

homeassistant.helpers.script.call_from_config(hass: homeassistant.core.HomeAssistant, config: typing.Dict[str, typing.Any], variables: typing.Union[typing.Sequence, NoneType] = None) → None[source]

Call a script based on a config entry.

homeassistant.helpers.service module

Service calling related helpers.

homeassistant.helpers.service.async_call_from_config(hass, config, blocking=False, variables=None, validate_config=True)[source]

Call a service based on a config hash.

homeassistant.helpers.service.call_from_config(hass, config, blocking=False, variables=None, validate_config=True)[source]

Call a service based on a config hash.

homeassistant.helpers.service.extract_entity_ids(hass, service_call, expand_group=True)[source]

Extract a list of entity ids from a service call.

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

Async friendly.

homeassistant.helpers.state module

Helpers that help with state related things.

class homeassistant.helpers.state.AsyncTrackStates(hass)[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.

homeassistant.helpers.state.async_reproduce_state(hass, states, blocking=False)[source]

Reproduce given state.

homeassistant.helpers.state.get_changed_since(states, utc_point_in_time)[source]

Return list of states that have been changed since utc_point_in_time.

homeassistant.helpers.state.reproduce_state(hass, states, blocking=False)[source]

Reproduce given state.

homeassistant.helpers.state.state_as_number(state)[source]

Try to coerce our state to a number.

Raises ValueError if this is not possible.

homeassistant.helpers.template module

Template helper methods for rendering strings with Home Assistant data.

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

Bases: object

Class to expose all HA states as attributes.

class homeassistant.helpers.template.DomainStates(hass, domain)[source]

Bases: object

Class to expose a specific HA domain as attributes.

class homeassistant.helpers.template.LocationMethods(hass)[source]

Bases: object

Class to expose distance helpers to templates.

closest(*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’)
distance(*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.

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

Bases: object

Class to hold a template and manage caching and rendering.

async_render(variables=None, **kwargs)[source]

Render given template.

This method must be run in the event loop.

async_render_with_possible_json_value(value, error_value=<object object>)[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()[source]

Return if template is valid.

extract_entities(variables=None)[source]

Extract all entities for state_changed listener.

render(variables=None, **kwargs)[source]

Render given template.

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

Render template with value exposed.

If valid JSON will expose value_json too.

class homeassistant.helpers.template.TemplateEnvironment(*args, **kwargs)[source]

Bases: jinja2.sandbox.ImmutableSandboxedEnvironment

The Home Assistant template environment.

is_safe_callable(obj)[source]

Test if callback is safe.

class homeassistant.helpers.template.TemplateState(state)[source]

Bases: homeassistant.core.State

Class to represent a state object in a template.

state_with_unit

Return the state concatenated with the unit if available.

homeassistant.helpers.template.attach(hass, obj)[source]

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

homeassistant.helpers.template.extract_entities(template, variables=None)[source]

Extract all entities for state_changed listener from template string.

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)[source]

Round accepted strings.

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

Filter to convert value to float and multiply it.

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.strptime(string, fmt)[source]

Parse a time string to datetime.

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.typing module

Typing Helpers for Home Assistant.

Module contents

Helper methods for components within Home Assistant.

homeassistant.helpers.config_per_platform(config: typing.Dict[str, typing.Any], domain: str) → typing.Iterable[typing.Tuple[typing.Any, typing.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: typing.Dict[str, typing.Any], domain: str) → typing.Sequence[str][source]

Extract keys from config for given domain name.

Async friendly.