Open-source home automation platform running on Python 3.
69
Comprehensive collection of utility functions and classes for common Home Assistant development tasks including validation, templating, event handling, service management, and async operations.
Voluptuous schema helpers and validation functions for validating configuration data, user input, and service parameters.
import homeassistant.helpers.config_validation as cv
def entity_id(value: Any) -> str:
"""Validate entity ID format.
Args:
value: Value to validate
Returns:
Validated entity ID
Raises:
vol.Invalid: If invalid entity ID
"""
def entity_ids(value: Any) -> list[str]:
"""Validate list of entity IDs.
Args:
value: Value to validate
Returns:
List of validated entity IDs
"""
def time(value: Any) -> datetime.time:
"""Validate time format.
Args:
value: Value to validate
Returns:
Validated time object
"""
def coordinates(value: Any) -> tuple[float, float]:
"""Validate GPS coordinates.
Args:
value: Value to validate
Returns:
Tuple of (latitude, longitude)
"""
def url(value: Any) -> str:
"""Validate URL format.
Args:
value: Value to validate
Returns:
Validated URL
"""
def port(value: Any) -> int:
"""Validate port number.
Args:
value: Value to validate
Returns:
Validated port number (1-65535)
"""
def positive_int(value: Any) -> int:
"""Validate positive integer.
Args:
value: Value to validate
Returns:
Validated positive integer
"""
def boolean(value: Any) -> bool:
"""Validate boolean value.
Args:
value: Value to validate
Returns:
Boolean value
"""
def string(value: Any) -> str:
"""Validate string value.
Args:
value: Value to validate
Returns:
String value
"""
def icon(value: Any) -> str:
"""Validate icon name.
Args:
value: Value to validate
Returns:
Validated icon name (mdi:*)
"""
def temperature_unit(value: Any) -> str:
"""Validate temperature unit.
Args:
value: Value to validate
Returns:
Validated temperature unit
"""
# Schema building helpers
PLATFORM_SCHEMA = vol.Schema({
vol.Required(CONF_PLATFORM): string,
}, extra=vol.ALLOW_EXTRA)
PLATFORM_SCHEMA_BASE = vol.Schema({})
SERVICE_SCHEMA = vol.Schema({}, extra=vol.ALLOW_EXTRA)Utilities for registering services, handling service calls, and managing service-related functionality.
async def async_register_admin_service(hass: HomeAssistant, domain: str,
service: str, service_func: Callable,
schema: dict = None) -> None:
"""Register admin service.
Args:
hass: Home Assistant instance
domain: Service domain
service: Service name
service_func: Service handler function
schema: Service schema
"""
async def async_extract_entity_ids(hass: HomeAssistant, service_call: ServiceCall,
expand_group: bool = True) -> list[str]:
"""Extract entity IDs from service call.
Args:
hass: Home Assistant instance
service_call: Service call
expand_group: Expand groups to individual entities
Returns:
List of entity IDs
"""
async def async_extract_entities(hass: HomeAssistant, service_call: ServiceCall,
expand_group: bool = True) -> list[Entity]:
"""Extract entities from service call.
Args:
hass: Home Assistant instance
service_call: Service call
expand_group: Expand groups to individual entities
Returns:
List of entity objects
"""
def verify_domain_control(hass: HomeAssistant, domain: str) -> None:
"""Verify domain control permissions.
Args:
hass: Home Assistant instance
domain: Domain to verify
Raises:
Unauthorized: If domain control not allowed
"""
async def entity_service_call(hass: HomeAssistant, platforms: list,
service_name: str, service_call: ServiceCall) -> None:
"""Call service on entity platforms.
Args:
hass: Home Assistant instance
platforms: List of entity platforms
service_name: Service to call
service_call: Service call data
"""Event tracking, state change monitoring, and time-based event scheduling utilities.
async def async_track_state_change(hass: HomeAssistant, entity_ids: Union[str, list[str]],
action: Callable, from_state: str = None,
to_state: str = None) -> Callable:
"""Track state changes for entities.
Args:
hass: Home Assistant instance
entity_ids: Entity ID(s) to track
action: Function to call on state change
from_state: Previous state to match
to_state: New state to match
Returns:
Function to stop tracking
"""
async def async_track_time_interval(hass: HomeAssistant, action: Callable,
interval: timedelta) -> Callable:
"""Track time intervals.
Args:
hass: Home Assistant instance
action: Function to call at intervals
interval: Time interval
Returns:
Function to stop tracking
"""
async def async_track_utc_time_change(hass: HomeAssistant, action: Callable,
hour: int = None, minute: int = None,
second: int = None) -> Callable:
"""Track UTC time changes.
Args:
hass: Home Assistant instance
action: Function to call on time change
hour: Hour to trigger on
minute: Minute to trigger on
second: Second to trigger on
Returns:
Function to stop tracking
"""
async def async_call_later(hass: HomeAssistant, delay: float, action: Callable) -> Callable:
"""Call function after delay.
Args:
hass: Home Assistant instance
delay: Delay in seconds
action: Function to call
Returns:
Function to cancel call
"""
async def async_track_sunrise(hass: HomeAssistant, action: Callable,
offset: timedelta = None) -> Callable:
"""Track sunrise events.
Args:
hass: Home Assistant instance
action: Function to call at sunrise
offset: Time offset from sunrise
Returns:
Function to stop tracking
"""
async def async_track_sunset(hass: HomeAssistant, action: Callable,
offset: timedelta = None) -> Callable:
"""Track sunset events.
Args:
hass: Home Assistant instance
action: Function to call at sunset
offset: Time offset from sunset
Returns:
Function to stop tracking
"""
async def async_track_template(hass: HomeAssistant, template: Template,
action: Callable, variables: dict = None) -> Callable:
"""Track template value changes.
Args:
hass: Home Assistant instance
template: Template to track
action: Function to call on template change
variables: Template variables
Returns:
Function to stop tracking
"""Jinja2 template engine integration for dynamic content generation and evaluation.
class Template:
"""Template wrapper for Jinja2 templates."""
def __init__(self, template: str, hass: HomeAssistant = None):
"""Initialize template.
Args:
template: Template string
hass: Home Assistant instance
"""
def render(self, variables: dict = None, **kwargs) -> str:
"""Render template.
Args:
variables: Template variables
**kwargs: Additional variables
Returns:
Rendered template string
"""
async def async_render(self, variables: dict = None, **kwargs) -> str:
"""Render template asynchronously.
Args:
variables: Template variables
**kwargs: Additional variables
Returns:
Rendered template string
"""
def ensure_valid(self) -> None:
"""Ensure template is valid.
Raises:
TemplateError: If template is invalid
"""
@property
def is_static(self) -> bool:
"""Return True if template is static."""
def render_complex(value: Any, variables: dict = None,
limited: bool = False) -> Any:
"""Render complex template data.
Args:
value: Value to render (may contain templates)
variables: Template variables
limited: Use limited template environment
Returns:
Rendered value
"""
def is_template_string(maybe_template: str) -> bool:
"""Check if string contains template syntax.
Args:
maybe_template: String to check
Returns:
True if string contains templates
"""
def extract_entities(template: str) -> set[str]:
"""Extract entity IDs from template.
Args:
template: Template string
Returns:
Set of entity IDs referenced in template
"""
# Template functions available in templates
def now() -> datetime:
"""Get current datetime in template."""
def utcnow() -> datetime:
"""Get current UTC datetime in template."""
def states(entity_id: str = None) -> Union[State, list[State]]:
"""Get entity state(s) in template."""
def is_state(entity_id: str, state: str) -> bool:
"""Check entity state in template."""
def is_state_attr(entity_id: str, attribute: str, value: Any) -> bool:
"""Check entity attribute in template."""
def state_attr(entity_id: str, attribute: str) -> Any:
"""Get entity attribute in template."""
def distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""Calculate distance between coordinates in template."""Persistent storage utilities for integrations to store and retrieve configuration and state data.
class Store:
"""Storage helper for integrations."""
def __init__(self, hass: HomeAssistant, version: int, key: str,
encoder: Callable = None, decoder: Callable = None):
"""Initialize store.
Args:
hass: Home Assistant instance
version: Storage version
key: Storage key
encoder: Custom encoder
decoder: Custom decoder
"""
async def async_load(self) -> dict:
"""Load data from storage.
Returns:
Stored data or None if not found
"""
async def async_save(self, data: dict) -> None:
"""Save data to storage.
Args:
data: Data to save
"""
async def async_remove(self) -> None:
"""Remove data from storage."""Type checking and validation utilities for Home Assistant development.
def is_callback(func: Callable) -> bool:
"""Check if function is marked as callback.
Args:
func: Function to check
Returns:
True if function is callback
"""
def is_coroutine_function(func: Callable) -> bool:
"""Check if function is a coroutine.
Args:
func: Function to check
Returns:
True if function is coroutine
"""
def callback_wrapper(func: Callable) -> Callable:
"""Wrap function as callback.
Args:
func: Function to wrap
Returns:
Wrapped function
"""Network-related utility functions for IP address validation, network discovery, and connectivity checking.
def is_private(ip: str) -> bool:
"""Check if IP address is private.
Args:
ip: IP address to check
Returns:
True if IP is private
"""
def is_loopback(ip: str) -> bool:
"""Check if IP address is loopback.
Args:
ip: IP address to check
Returns:
True if IP is loopback
"""
def is_local(ip: str) -> bool:
"""Check if IP address is local.
Args:
ip: IP address to check
Returns:
True if IP is local
"""
def get_source_ip(target_ip: str) -> str:
"""Get source IP for connecting to target.
Args:
target_ip: Target IP address
Returns:
Source IP address
"""
async def async_get_source_ip(target_ip: str) -> str:
"""Get source IP asynchronously.
Args:
target_ip: Target IP address
Returns:
Source IP address
"""from typing import Any, Callable, Dict, List, Optional, Union
import voluptuous as vol
from datetime import datetime, timedelta
# Validation types
ValidatorType = Callable[[Any], Any]
SchemaType = vol.Schema
# Template types
TemplateType = Union[str, Template, None]
TemplateRenderType = Union[str, int, float, bool, None]
# Event tracking types
EntityIdType = Union[str, List[str]]
ActionType = Callable[[str, State, State], None]
TimeActionType = Callable[[datetime], None]
# Storage types
StorageDataType = Dict[str, Any]
StorageKeyType = str
# Network types
IPAddressType = str
PortType = intInstall with Tessl CLI
npx tessl i tessl/pypi-homeassistantdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10