response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Return the base unique ID for an entity that is not based on a value.
def get_valueless_base_unique_id(driver: Driver, node: ZwaveNode) -> str: """Return the base unique ID for an entity that is not based on a value.""" return f"{driver.controller.home_id}.{node.node_id}"
Get unique ID from client and value ID.
def get_unique_id(driver: Driver, value_id: str) -> str: """Get unique ID from client and value ID.""" return f"{driver.controller.home_id}.{value_id}"
Get device registry identifier for Z-Wave node.
def get_device_id(driver: Driver, node: ZwaveNode) -> tuple[str, str]: """Get device registry identifier for Z-Wave node.""" return (DOMAIN, f"{driver.controller.home_id}-{node.node_id}")
Get extended device registry identifier for Z-Wave node.
def get_device_id_ext(driver: Driver, node: ZwaveNode) -> tuple[str, str] | None: """Get extended device registry identifier for Z-Wave node.""" if None in (node.manufacturer_id, node.product_type, node.product_id): return None domain, dev_id = get_device_id(driver, node) return ( domain, f"{dev_id}-{node.manufacturer_id}:{node.product_type}:{node.product_id}", )
Get home ID and node ID for Z-Wave device registry entry. Returns (home_id, node_id) or None if not found.
def get_home_and_node_id_from_device_entry( device_entry: dr.DeviceEntry, ) -> tuple[str, int] | None: """Get home ID and node ID for Z-Wave device registry entry. Returns (home_id, node_id) or None if not found. """ device_id = next( ( identifier[1] for identifier in device_entry.identifiers if identifier[0] == DOMAIN ), None, ) if device_id is None: return None id_ = device_id.split("-") return (id_[0], int(id_[1]))
Get node from a device ID. Raises ValueError if device is invalid or node can't be found.
def async_get_node_from_device_id( hass: HomeAssistant, device_id: str, dev_reg: dr.DeviceRegistry | None = None ) -> ZwaveNode: """Get node from a device ID. Raises ValueError if device is invalid or node can't be found. """ if not dev_reg: dev_reg = dr.async_get(hass) if not (device_entry := dev_reg.async_get(device_id)): raise ValueError(f"Device ID {device_id} is not valid") # Use device config entry ID's to validate that this is a valid zwave_js device # and to get the client config_entry_ids = device_entry.config_entries entry = next( ( entry for entry in hass.config_entries.async_entries(DOMAIN) if entry.entry_id in config_entry_ids ), None, ) if entry and entry.state != ConfigEntryState.LOADED: raise ValueError(f"Device {device_id} config entry is not loaded") if entry is None or entry.entry_id not in hass.data[DOMAIN]: raise ValueError( f"Device {device_id} is not from an existing zwave_js config entry" ) client: ZwaveClient = hass.data[DOMAIN][entry.entry_id][DATA_CLIENT] driver = client.driver if driver is None: raise ValueError("Driver is not ready.") # Get node ID from device identifier, perform some validation, and then get the # node identifiers = get_home_and_node_id_from_device_entry(device_entry) node_id = identifiers[1] if identifiers else None if node_id is None or node_id not in driver.controller.nodes: raise ValueError(f"Node for device {device_id} can't be found") return driver.controller.nodes[node_id]
Get node from an entity ID. Raises ValueError if entity is invalid.
def async_get_node_from_entity_id( hass: HomeAssistant, entity_id: str, ent_reg: er.EntityRegistry | None = None, dev_reg: dr.DeviceRegistry | None = None, ) -> ZwaveNode: """Get node from an entity ID. Raises ValueError if entity is invalid. """ if not ent_reg: ent_reg = er.async_get(hass) entity_entry = ent_reg.async_get(entity_id) if entity_entry is None or entity_entry.platform != DOMAIN: raise ValueError(f"Entity {entity_id} is not a valid {DOMAIN} entity") # Assert for mypy, safe because we know that zwave_js entities are always # tied to a device assert entity_entry.device_id return async_get_node_from_device_id(hass, entity_entry.device_id, dev_reg)
Get nodes for all Z-Wave JS devices and entities that are in an area.
def async_get_nodes_from_area_id( hass: HomeAssistant, area_id: str, ent_reg: er.EntityRegistry | None = None, dev_reg: dr.DeviceRegistry | None = None, ) -> set[ZwaveNode]: """Get nodes for all Z-Wave JS devices and entities that are in an area.""" nodes: set[ZwaveNode] = set() if ent_reg is None: ent_reg = er.async_get(hass) if dev_reg is None: dev_reg = dr.async_get(hass) # Add devices for all entities in an area that are Z-Wave JS entities nodes.update( { async_get_node_from_device_id(hass, entity.device_id, dev_reg) for entity in er.async_entries_for_area(ent_reg, area_id) if entity.platform == DOMAIN and entity.device_id is not None } ) # Add devices in an area that are Z-Wave JS devices for device in dr.async_entries_for_area(dev_reg, area_id): if next( ( config_entry_id for config_entry_id in device.config_entries if cast( ConfigEntry, hass.config_entries.async_get_entry(config_entry_id), ).domain == DOMAIN ), None, ): nodes.add(async_get_node_from_device_id(hass, device.id, dev_reg)) return nodes
Get nodes for all targets. Supports entity_id with group expansion, area_id, and device_id.
def async_get_nodes_from_targets( hass: HomeAssistant, val: dict[str, Any], ent_reg: er.EntityRegistry | None = None, dev_reg: dr.DeviceRegistry | None = None, logger: logging.Logger = LOGGER, ) -> set[ZwaveNode]: """Get nodes for all targets. Supports entity_id with group expansion, area_id, and device_id. """ nodes: set[ZwaveNode] = set() # Convert all entity IDs to nodes for entity_id in expand_entity_ids(hass, val.get(ATTR_ENTITY_ID, [])): try: nodes.add(async_get_node_from_entity_id(hass, entity_id, ent_reg, dev_reg)) except ValueError as err: logger.warning(err.args[0]) # Convert all area IDs to nodes for area_id in val.get(ATTR_AREA_ID, []): nodes.update(async_get_nodes_from_area_id(hass, area_id, ent_reg, dev_reg)) # Convert all device IDs to nodes for device_id in val.get(ATTR_DEVICE_ID, []): try: nodes.add(async_get_node_from_device_id(hass, device_id, dev_reg)) except ValueError as err: logger.warning(err.args[0]) return nodes
Get a Z-Wave JS Value from a config.
def get_zwave_value_from_config(node: ZwaveNode, config: ConfigType) -> ZwaveValue: """Get a Z-Wave JS Value from a config.""" endpoint = None if config.get(ATTR_ENDPOINT): endpoint = config[ATTR_ENDPOINT] property_key = None if config.get(ATTR_PROPERTY_KEY): property_key = config[ATTR_PROPERTY_KEY] value_id = get_value_id_str( node, config[ATTR_COMMAND_CLASS], config[ATTR_PROPERTY], endpoint, property_key, ) if value_id not in node.values: raise vol.Invalid(f"Value {value_id} can't be found on node {node}") return node.values[value_id]
Find zwave_js config entry from a device.
def _zwave_js_config_entry(hass: HomeAssistant, device: dr.DeviceEntry) -> str | None: """Find zwave_js config entry from a device.""" for entry_id in device.config_entries: entry = hass.config_entries.async_get_entry(entry_id) if entry and entry.domain == DOMAIN: return entry_id return None
Get the node status sensor entity ID for a given Z-Wave JS device.
def async_get_node_status_sensor_entity_id( hass: HomeAssistant, device_id: str, ent_reg: er.EntityRegistry | None = None, dev_reg: dr.DeviceRegistry | None = None, ) -> str | None: """Get the node status sensor entity ID for a given Z-Wave JS device.""" if not ent_reg: ent_reg = er.async_get(hass) if not dev_reg: dev_reg = dr.async_get(hass) if not (device := dev_reg.async_get(device_id)): raise HomeAssistantError("Invalid Device ID provided") if not (entry_id := _zwave_js_config_entry(hass, device)): return None client = hass.data[DOMAIN][entry_id][DATA_CLIENT] node = async_get_node_from_device_id(hass, device_id, dev_reg) return ent_reg.async_get_entity_id( SENSOR_DOMAIN, DOMAIN, f"{client.driver.controller.home_id}.{node.node_id}.node_status", )
Remove keys from config where the value is an empty string or None.
def remove_keys_with_empty_values(config: ConfigType) -> ConfigType: """Remove keys from config where the value is an empty string or None.""" return {key: value for key, value in config.items() if value not in ("", None)}
Check type specific schema against config.
def check_type_schema_map( schema_map: dict[str, vol.Schema], ) -> Callable[[ConfigType], ConfigType]: """Check type specific schema against config.""" def _check_type_schema(config: ConfigType) -> ConfigType: """Check type specific schema against config.""" return cast(ConfigType, schema_map[str(config[CONF_TYPE])](config)) return _check_type_schema
Copy available params from input into output.
def copy_available_params( input_dict: dict[str, Any], output_dict: dict[str, Any], params: list[str] ) -> None: """Copy available params from input into output.""" output_dict.update( {param: input_dict[param] for param in params if param in input_dict} )
Return device automation schema for a config entry.
def get_value_state_schema(value: ZwaveValue) -> vol.Schema | None: """Return device automation schema for a config entry.""" if isinstance(value, ConfigurationValue): min_ = value.metadata.min max_ = value.metadata.max if value.configuration_value_type in ( ConfigurationValueType.RANGE, ConfigurationValueType.MANUAL_ENTRY, ): return vol.All(vol.Coerce(int), vol.Range(min=min_, max=max_)) if value.configuration_value_type == ConfigurationValueType.BOOLEAN: return vol.Coerce(bool) if value.configuration_value_type == ConfigurationValueType.ENUMERATED: return vol.In({int(k): v for k, v in value.metadata.states.items()}) return None if value.metadata.states: return vol.In({int(k): v for k, v in value.metadata.states.items()}) return vol.All( vol.Coerce(int), vol.Range(min=value.metadata.min, max=value.metadata.max), )
Get DeviceInfo for node.
def get_device_info(driver: Driver, node: ZwaveNode) -> DeviceInfo: """Get DeviceInfo for node.""" return DeviceInfo( identifiers={get_device_id(driver, node)}, sw_version=node.firmware_version, name=node.name or node.device_config.description or f"Node {node.node_id}", model=node.device_config.label, manufacturer=node.device_config.manufacturer, suggested_area=node.location if node.location else None, )
Return the network identifier string for persistent notifications.
def get_network_identifier_for_notification( hass: HomeAssistant, config_entry: ConfigEntry, controller: Controller ) -> str: """Return the network identifier string for persistent notifications.""" home_id = str(controller.home_id) if len(hass.config_entries.async_entries(DOMAIN)) > 1: if str(home_id) != config_entry.title: return f"`{config_entry.title}`, with the home ID `{home_id}`," return f"with the home ID `{home_id}`" return ""
Convert brightness in 0-255 scale to 0-99 scale. `value` -- (int) Brightness byte value from 0-255.
def byte_to_zwave_brightness(value: int) -> int: """Convert brightness in 0-255 scale to 0-99 scale. `value` -- (int) Brightness byte value from 0-255. """ if value > 0: return max(1, round((value / 255) * 99)) return 0
Describe logbook events.
def async_describe_events( hass: HomeAssistant, async_describe_event: Callable[[str, str, Callable[[Event], dict[str, str]]], None], ) -> None: """Describe logbook events.""" dev_reg = dr.async_get(hass) @callback def async_describe_zwave_js_notification_event( event: Event, ) -> dict[str, str]: """Describe Z-Wave JS notification event.""" device = dev_reg.devices[event.data[ATTR_DEVICE_ID]] # Z-Wave JS devices always have a name device_name = device.name_by_user or device.name assert device_name command_class = event.data[ATTR_COMMAND_CLASS] command_class_name = event.data[ATTR_COMMAND_CLASS_NAME] data: dict[str, str] = {LOGBOOK_ENTRY_NAME: device_name} prefix = f"fired {command_class_name} CC 'notification' event" if command_class == CommandClass.NOTIFICATION: label = event.data[ATTR_LABEL] event_label = event.data[ATTR_EVENT_LABEL] return { **data, LOGBOOK_ENTRY_MESSAGE: f"{prefix} '{label}': '{event_label}'", } if command_class == CommandClass.ENTRY_CONTROL: event_type = event.data[ATTR_EVENT_TYPE] data_type = event.data[ATTR_DATA_TYPE] return { **data, LOGBOOK_ENTRY_MESSAGE: ( f"{prefix} for event type '{event_type}' with data type " f"'{data_type}'" ), } if command_class == CommandClass.SWITCH_MULTILEVEL: event_type = event.data[ATTR_EVENT_TYPE] direction = event.data[ATTR_DIRECTION] return { **data, LOGBOOK_ENTRY_MESSAGE: ( f"{prefix} for event type '{event_type}': '{direction}'" ), } return {**data, LOGBOOK_ENTRY_MESSAGE: prefix} @callback def async_describe_zwave_js_value_notification_event( event: Event, ) -> dict[str, str]: """Describe Z-Wave JS value notification event.""" device = dev_reg.devices[event.data[ATTR_DEVICE_ID]] # Z-Wave JS devices always have a name device_name = device.name_by_user or device.name assert device_name command_class = event.data[ATTR_COMMAND_CLASS_NAME] label = event.data[ATTR_LABEL] value = event.data[ATTR_VALUE] return { LOGBOOK_ENTRY_NAME: device_name, LOGBOOK_ENTRY_MESSAGE: ( f"fired {command_class} CC 'value notification' event for '{label}': " f"'{value}'" ), } async_describe_event( DOMAIN, ZWAVE_JS_NOTIFICATION_EVENT, async_describe_zwave_js_notification_event ) async_describe_event( DOMAIN, ZWAVE_JS_VALUE_NOTIFICATION_EVENT, async_describe_zwave_js_value_notification_event, )
Migrate existing entity if current one can't be found and an old one exists.
def async_migrate_old_entity( hass: HomeAssistant, ent_reg: EntityRegistry, registered_unique_ids: set[str], platform: str, device: DeviceEntry, unique_id: str, ) -> None: """Migrate existing entity if current one can't be found and an old one exists.""" # If we can find an existing entity with this unique ID, there's nothing to migrate if ent_reg.async_get_entity_id(platform, DOMAIN, unique_id): return value_id = ValueID.from_unique_id(unique_id) # Look for existing entities in the registry that could be the same value but on # a different endpoint existing_entity_entries: list[RegistryEntry] = [] for entry in async_entries_for_device(ent_reg, device.id): # If entity is not in the domain for this discovery info or entity has already # been processed, skip it if entry.domain != platform or entry.unique_id in registered_unique_ids: continue try: old_ent_value_id = ValueID.from_unique_id(entry.unique_id) # Skip non value ID based unique ID's (e.g. node status sensor) except IndexError: continue if value_id.is_same_value_different_endpoints(old_ent_value_id): existing_entity_entries.append(entry) # We can return early if we get more than one result if len(existing_entity_entries) > 1: return # If we couldn't find any results, return early if not existing_entity_entries: return entry = existing_entity_entries[0] state = hass.states.get(entry.entity_id) if not state or state.state == STATE_UNAVAILABLE: async_migrate_unique_id(ent_reg, platform, entry.unique_id, unique_id)
Check if entity with old unique ID exists, and if so migrate it to new ID.
def async_migrate_unique_id( ent_reg: EntityRegistry, platform: str, old_unique_id: str, new_unique_id: str ) -> None: """Check if entity with old unique ID exists, and if so migrate it to new ID.""" if entity_id := ent_reg.async_get_entity_id(platform, DOMAIN, old_unique_id): _LOGGER.debug( "Migrating entity %s from old unique ID '%s' to new unique ID '%s'", entity_id, old_unique_id, new_unique_id, ) try: ent_reg.async_update_entity(entity_id, new_unique_id=new_unique_id) except ValueError: _LOGGER.debug( ( "Entity %s can't be migrated because the unique ID is taken; " "Cleaning it up since it is likely no longer valid" ), entity_id, ) ent_reg.async_remove(entity_id)
Migrate unique ID for entity/entities tied to discovered value.
def async_migrate_discovered_value( hass: HomeAssistant, ent_reg: EntityRegistry, registered_unique_ids: set[str], device: DeviceEntry, driver: Driver, disc_info: ZwaveDiscoveryInfo, ) -> None: """Migrate unique ID for entity/entities tied to discovered value.""" new_unique_id = get_unique_id(driver, disc_info.primary_value.value_id) # On reinterviews, there is no point in going through this logic again for already # discovered values if new_unique_id in registered_unique_ids: return # Migration logic was added in 2021.3 to handle a breaking change to the value_id # format. Some time in the future, the logic to migrate unique IDs can be removed. # 2021.2.*, 2021.3.0b0, and 2021.3.0 formats old_unique_ids = [ get_unique_id(driver, value_id) for value_id in get_old_value_ids(disc_info.primary_value) ] if ( disc_info.platform == "binary_sensor" and disc_info.platform_hint == "notification" ): for state_key in disc_info.primary_value.metadata.states: # ignore idle key (0) if state_key == "0": continue new_bin_sensor_unique_id = f"{new_unique_id}.{state_key}" # On reinterviews, there is no point in going through this logic again # for already discovered values if new_bin_sensor_unique_id in registered_unique_ids: continue # Unique ID migration for old_unique_id in old_unique_ids: async_migrate_unique_id( ent_reg, disc_info.platform, f"{old_unique_id}.{state_key}", new_bin_sensor_unique_id, ) # Migrate entities in case upstream changes cause endpoint change async_migrate_old_entity( hass, ent_reg, registered_unique_ids, disc_info.platform, device, new_bin_sensor_unique_id, ) registered_unique_ids.add(new_bin_sensor_unique_id) # Once we've iterated through all state keys, we are done return # Unique ID migration for old_unique_id in old_unique_ids: async_migrate_unique_id( ent_reg, disc_info.platform, old_unique_id, new_unique_id ) # Migrate entities in case upstream changes cause endpoint change async_migrate_old_entity( hass, ent_reg, registered_unique_ids, disc_info.platform, device, new_unique_id ) registered_unique_ids.add(new_unique_id)
Get old value IDs so we can migrate entity unique ID.
def get_old_value_ids(value: ZwaveValue) -> list[str]: """Get old value IDs so we can migrate entity unique ID.""" value_ids = [] # Pre 2021.3.0 value ID command_class = value.command_class endpoint = value.endpoint or "00" property_ = value.property_ property_key_name = value.property_key_name or "00" value_ids.append( f"{value.node.node_id}.{value.node.node_id}-{command_class}-{endpoint}-" f"{property_}-{property_key_name}" ) endpoint = "00" if value.endpoint is None else value.endpoint property_key = "00" if value.property_key is None else value.property_key property_key_name = value.property_key_name or "00" value_id = ( f"{value.node.node_id}-{command_class}-{endpoint}-" f"{property_}-{property_key}-{property_key_name}" ) # 2021.3.0b0 and 2021.3.0 value IDs value_ids.extend([f"{value.node.node_id}.{value_id}", value_id]) return value_ids
Convert a dictionary of dictionaries to a value.
def convert_dict_of_dicts( statistics: ControllerStatisticsDataType | NodeStatisticsDataType, key: str ) -> Any: """Convert a dictionary of dictionaries to a value.""" keys = key.split(".") return statistics.get(keys[0], {}).get(keys[1], {}).get(keys[2])
Return the entity description for the given data.
def get_entity_description( data: NumericSensorDataTemplateData, ) -> SensorEntityDescription: """Return the entity description for the given data.""" data_description_key = data.entity_description_key or "" data_unit = data.unit_of_measurement or "" return ENTITY_DESCRIPTION_KEY_DEVICE_CLASS_MAP.get( (data_description_key, data_unit), ENTITY_DESCRIPTION_KEY_MAP.get( data_description_key, SensorEntityDescription( key="base_sensor", native_unit_of_measurement=data.unit_of_measurement ), ), )
Validate that if a parameter name is provided, bitmask is not as well.
def parameter_name_does_not_need_bitmask( val: dict[str, int | str | list[str]], ) -> dict[str, int | str | list[str]]: """Validate that if a parameter name is provided, bitmask is not as well.""" if ( isinstance(val[const.ATTR_CONFIG_PARAMETER], str) and const.ATTR_CONFIG_PARAMETER_BITMASK in val ): raise vol.Invalid( "Don't include a bitmask when a parameter name is specified", path=[const.ATTR_CONFIG_PARAMETER, const.ATTR_CONFIG_PARAMETER_BITMASK], ) return val
Check if value is a power of 2.
def check_base_2(val: int) -> int: """Check if value is a power of 2.""" if not math.log2(val).is_integer(): raise vol.Invalid("Value must be a power of 2.") return val
Validate that the service call is for a broadcast command.
def broadcast_command(val: dict[str, Any]) -> dict[str, Any]: """Validate that the service call is for a broadcast command.""" if val.get(const.ATTR_BROADCAST): return val raise vol.Invalid( "Either `broadcast` must be set to True or multiple devices/entities must be " "specified" )
Return valid responses from a list of results.
def get_valid_responses_from_results( zwave_objects: Sequence[T], results: Sequence[Any] ) -> Generator[tuple[T, Any], None, None]: """Return valid responses from a list of results.""" for zwave_object, result in zip(zwave_objects, results, strict=False): if not isinstance(result, Exception): yield zwave_object, result
Raise list of exceptions from a list of results.
def raise_exceptions_from_results( zwave_objects: Sequence[T], results: Sequence[Any] ) -> None: """Raise list of exceptions from a list of results.""" errors: Sequence[tuple[T, Any]] if errors := [ tup for tup in zip(zwave_objects, results, strict=True) if isinstance(tup[1], Exception) ]: lines = [ *( f"{zwave_object} - {error.__class__.__name__}: {error.args[0]}" for zwave_object, error in errors ) ] if len(lines) > 1: lines.insert(0, f"{len(errors)} error(s):") raise HomeAssistantError("\n".join(lines))
Return trigger platform.
def _get_trigger_platform(config: ConfigType) -> TriggerProtocol: """Return trigger platform.""" platform_split = config[CONF_PLATFORM].split(".", maxsplit=1) if len(platform_split) < 2 or platform_split[1] not in TRIGGERS: raise ValueError(f"Unknown Z-Wave JS trigger platform {config[CONF_PLATFORM]}") return TRIGGERS[platform_split[1]]
Ensure that Z-Wave JS add-on is updated and running.
def _get_addon_manager(hass: HomeAssistant) -> AddonManager: """Ensure that Z-Wave JS add-on is updated and running.""" addon_manager: AddonManager = get_addon_manager(hass) if addon_manager.task_in_progress(): raise ConfigEntryNotReady return addon_manager
Get parsed passed in arguments.
def get_arguments() -> argparse.Namespace: """Get parsed passed in arguments.""" parser = argparse.ArgumentParser(description="Z-Wave JS Fixture generator") parser.add_argument( "diagnostics_file", type=Path, help="Device diagnostics file to convert" ) parser.add_argument( "--file", action="store_true", help=( "Dump fixture to file in fixtures folder. By default, the fixture will be " "printed to standard output." ), ) return parser.parse_args()
Get path to fixtures directory.
def get_fixtures_dir_path(data: dict) -> Path: """Get path to fixtures directory.""" device_config = data["deviceConfig"] filename = slugify( f"{device_config['manufacturer']}-{device_config['label']}_state" ) path = Path(__file__).parents[1] index = path.parts.index("homeassistant") return Path( *path.parts[:index], "tests", *path.parts[index + 1 :], "fixtures", f"{filename}.json", )
Load file from path.
def load_file(path: Path) -> Any: """Load file from path.""" return json.loads(path.read_text("utf8"))
Extract fixture data from file.
def extract_fixture_data(diagnostics_data: Any) -> dict: """Extract fixture data from file.""" if ( not isinstance(diagnostics_data, dict) or "data" not in diagnostics_data or "state" not in diagnostics_data["data"] ): raise ValueError("Invalid diagnostics file format") state: dict = diagnostics_data["data"]["state"] if not isinstance(state["values"], list): values_dict: dict[str, dict] = state.pop("values") state["values"] = list(values_dict.values()) if not isinstance(state["endpoints"], list): endpoints_dict: dict[str, dict] = state.pop("endpoints") state["endpoints"] = list(endpoints_dict.values()) return state
Create a file for the state dump in the fixtures directory.
def create_fixture_file(path: Path, state_text: str) -> None: """Create a file for the state dump in the fixtures directory.""" path.write_text(state_text, "utf8")
Run the main script.
def main() -> None: """Run the main script.""" args = get_arguments() diagnostics_path: Path = args.diagnostics_file diagnostics = load_file(diagnostics_path) fixture_data = extract_fixture_data(diagnostics) fixture_text = json.dumps(fixture_data, indent=2) if args.file: fixture_path = get_fixtures_dir_path(fixture_data) create_fixture_file(fixture_path, fixture_text) return print(fixture_text)
Validate that a trigger for a non node event source has a config entry.
def validate_non_node_event_source(obj: dict) -> dict: """Validate that a trigger for a non node event source has a config entry.""" if obj[ATTR_EVENT_SOURCE] != "node" and ATTR_CONFIG_ENTRY_ID in obj: return obj raise vol.Invalid(f"Non node event triggers must contain {ATTR_CONFIG_ENTRY_ID}.")
Validate that a trigger has a valid event name.
def validate_event_name(obj: dict) -> dict: """Validate that a trigger has a valid event name.""" event_source = obj[ATTR_EVENT_SOURCE] event_name = obj[ATTR_EVENT] # the keys to the event source's model map are the event names if event_source == "controller": vol.In(CONTROLLER_EVENT_MODEL_MAP)(event_name) elif event_source == "driver": vol.In(DRIVER_EVENT_MODEL_MAP)(event_name) else: vol.In(NODE_EVENT_MODEL_MAP)(event_name) return obj
Validate that a trigger has a valid event data.
def validate_event_data(obj: dict) -> dict: """Validate that a trigger has a valid event data.""" # Return if there's no event data to validate if ATTR_EVENT_DATA not in obj: return obj event_source: str = obj[ATTR_EVENT_SOURCE] event_name: str = obj[ATTR_EVENT] event_data: dict = obj[ATTR_EVENT_DATA] try: if event_source == "controller": CONTROLLER_EVENT_MODEL_MAP[event_name](**event_data) elif event_source == "driver": DRIVER_EVENT_MODEL_MAP[event_name](**event_data) else: NODE_EVENT_MODEL_MAP[event_name](**event_data) except ValidationError as exc: # Filter out required field errors if keys can be missing, and if there are # still errors, raise an exception if errors := [ error for error in exc.errors() if error["type"] != "value_error.missing" ]: raise vol.MultipleInvalid(errors) from exc return obj
Return whether target zwave_js config entry is not loaded.
def async_bypass_dynamic_config_validation( hass: HomeAssistant, config: ConfigType ) -> bool: """Return whether target zwave_js config entry is not loaded.""" # If the config entry is not loaded for a zwave_js device, entity, or the # config entry ID provided, we can't perform dynamic validation dev_reg = dr.async_get(hass) ent_reg = er.async_get(hass) trigger_devices = config.get(ATTR_DEVICE_ID, []) trigger_entities = config.get(ATTR_ENTITY_ID, []) for entry in hass.config_entries.async_entries(DOMAIN): if entry.state != ConfigEntryState.LOADED and ( entry.entry_id == config.get(ATTR_CONFIG_ENTRY_ID) or any( device.id in trigger_devices for device in dr.async_entries_for_config_entry(dev_reg, entry.entry_id) ) or ( entity.entity_id in trigger_entities for entity in er.async_entries_for_config_entry(ent_reg, entry.entry_id) ) ): return True # The driver may not be ready when the config entry is loaded. client: ZwaveClient = hass.data[DOMAIN][entry.entry_id][DATA_CLIENT] if client.driver is None: return True return False
Return default aiohttp ClientSession. This method must be run in the event loop.
def async_get_clientsession( hass: HomeAssistant, verify_ssl: bool = True, family: int = 0 ) -> aiohttp.ClientSession: """Return default aiohttp ClientSession. This method must be run in the event loop. """ session_key = _make_key(verify_ssl, family) if DATA_CLIENTSESSION not in hass.data: sessions: dict[tuple[bool, int], aiohttp.ClientSession] = {} hass.data[DATA_CLIENTSESSION] = sessions else: sessions = hass.data[DATA_CLIENTSESSION] if session_key not in sessions: session = _async_create_clientsession( hass, verify_ssl, auto_cleanup_method=_async_register_default_clientsession_shutdown, family=family, ) sessions[session_key] = session else: session = sessions[session_key] return session
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.
def async_create_clientsession( hass: HomeAssistant, verify_ssl: bool = True, auto_cleanup: bool = True, family: int = 0, **kwargs: Any, ) -> aiohttp.ClientSession: """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. """ auto_cleanup_method = None if auto_cleanup: auto_cleanup_method = _async_register_clientsession_shutdown return _async_create_clientsession( hass, verify_ssl, auto_cleanup_method=auto_cleanup_method, family=family, **kwargs, )
Create a new ClientSession with kwargs, i.e. for cookies.
def _async_create_clientsession( hass: HomeAssistant, verify_ssl: bool = True, auto_cleanup_method: Callable[[HomeAssistant, aiohttp.ClientSession], None] | None = None, family: int = 0, **kwargs: Any, ) -> aiohttp.ClientSession: """Create a new ClientSession with kwargs, i.e. for cookies.""" clientsession = aiohttp.ClientSession( connector=_async_get_connector(hass, verify_ssl, family), json_serialize=json_dumps, response_class=HassClientResponse, **kwargs, ) # Prevent packages accidentally overriding our default headers # It's important that we identify as Home Assistant # If a package requires a different user agent, override it by passing a headers # dictionary to the request method. # pylint: disable-next=protected-access clientsession._default_headers = MappingProxyType( # type: ignore[assignment] {USER_AGENT: SERVER_SOFTWARE}, ) clientsession.close = warn_use( # type: ignore[method-assign] clientsession.close, WARN_CLOSE_MSG, ) if auto_cleanup_method: auto_cleanup_method(hass, clientsession) return clientsession
Register ClientSession close on Home Assistant shutdown or config entry unload. This method must be run in the event loop.
def _async_register_clientsession_shutdown( hass: HomeAssistant, clientsession: aiohttp.ClientSession ) -> None: """Register ClientSession close on Home Assistant shutdown or config entry unload. This method must be run in the event loop. """ @callback def _async_close_websession(*_: Any) -> None: """Close websession.""" clientsession.detach() unsub = hass.bus.async_listen_once( EVENT_HOMEASSISTANT_CLOSE, _async_close_websession ) if not (config_entry := config_entries.current_entry.get()): return config_entry.async_on_unload(unsub) config_entry.async_on_unload(_async_close_websession)
Register default ClientSession close on Home Assistant shutdown. This method must be run in the event loop.
def _async_register_default_clientsession_shutdown( hass: HomeAssistant, clientsession: aiohttp.ClientSession ) -> None: """Register default ClientSession close on Home Assistant shutdown. This method must be run in the event loop. """ @callback def _async_close_websession(event: Event) -> None: """Close websession.""" clientsession.detach() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, _async_close_websession)
Make a key for connector or session pool.
def _make_key(verify_ssl: bool = True, family: int = 0) -> tuple[bool, int]: """Make a key for connector or session pool.""" return (verify_ssl, family)
Return the connector pool for aiohttp. This method must be run in the event loop.
def _async_get_connector( hass: HomeAssistant, verify_ssl: bool = True, family: int = 0 ) -> aiohttp.BaseConnector: """Return the connector pool for aiohttp. This method must be run in the event loop. """ connector_key = _make_key(verify_ssl, family) if DATA_CONNECTOR not in hass.data: connectors: dict[tuple[bool, int], aiohttp.BaseConnector] = {} hass.data[DATA_CONNECTOR] = connectors else: connectors = hass.data[DATA_CONNECTOR] if connector_key in connectors: return connectors[connector_key] if verify_ssl: ssl_context: SSLContext = ssl_util.get_default_context() else: ssl_context = ssl_util.get_default_no_verify_context() connector = aiohttp.TCPConnector( family=family, enable_cleanup_closed=ENABLE_CLEANUP_CLOSED, ssl=ssl_context, limit=MAXIMUM_CONNECTIONS, limit_per_host=MAXIMUM_CONNECTIONS_PER_HOST, resolver=AsyncResolver(), ) connectors[connector_key] = connector async def _async_close_connector(event: Event) -> None: """Close connector pool.""" await connector.close() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, _async_close_connector) return connector
Get area registry.
def async_get(hass: HomeAssistant) -> AreaRegistry: """Get area registry.""" return cast(AreaRegistry, hass.data[DATA_REGISTRY])
Return entries that match a floor.
def async_entries_for_floor(registry: AreaRegistry, floor_id: str) -> list[AreaEntry]: """Return entries that match a floor.""" return registry.areas.get_areas_for_floor(floor_id)
Return entries that match a label.
def async_entries_for_label(registry: AreaRegistry, label_id: str) -> list[AreaEntry]: """Return entries that match a label.""" return registry.areas.get_areas_for_label(label_id)
Get category registry.
def async_get(hass: HomeAssistant) -> CategoryRegistry: """Get category registry.""" return cast(CategoryRegistry, hass.data[DATA_REGISTRY])
Map a collection to an entity component.
def sync_entity_lifecycle( hass: HomeAssistant, domain: str, platform: str, entity_component: EntityComponent[_EntityT], collection: StorageCollection | YamlCollection, entity_class: type[CollectionEntity], ) -> None: """Map a collection to an entity component.""" ent_reg = entity_registry.async_get(hass) _CollectionLifeCycle( domain, platform, entity_component, collection, entity_class, ent_reg, {} ).async_setup()
Append a TraceElement to trace[path].
def condition_trace_append(variables: TemplateVarsType, path: str) -> TraceElement: """Append a TraceElement to trace[path].""" trace_element = TraceElement(variables, path) trace_append_element(trace_element) return trace_element
Set the result of TraceElement at the top of the stack.
def condition_trace_set_result(result: bool, **kwargs: Any) -> None: """Set the result of TraceElement at the top of the stack.""" node = trace_stack_top(trace_stack_cv) # The condition function may be called directly, in which case tracing # is not setup if not node: return node.set_result(result=result, **kwargs)
Update the result of TraceElement at the top of the stack.
def condition_trace_update_result(**kwargs: Any) -> None: """Update the result of TraceElement at the top of the stack.""" node = trace_stack_top(trace_stack_cv) # The condition function may be called directly, in which case tracing # is not setup if not node: return node.update_result(**kwargs)
Trace condition evaluation.
def trace_condition(variables: TemplateVarsType) -> Generator[TraceElement, None, None]: """Trace condition evaluation.""" should_pop = True trace_element = trace_stack_top(trace_stack_cv) if trace_element and trace_element.reuse_by_child: should_pop = False trace_element.reuse_by_child = False else: trace_element = condition_trace_append(variables, trace_path_get()) trace_stack_push(trace_stack_cv, trace_element) try: yield trace_element except Exception as ex: trace_element.set_error(ex) raise finally: if should_pop: trace_stack_pop(trace_stack_cv)
Wrap a condition function to enable basic tracing.
def trace_condition_function(condition: ConditionCheckerType) -> ConditionCheckerType: """Wrap a condition function to enable basic tracing.""" @ft.wraps(condition) def wrapper(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool | None: """Trace condition.""" with trace_condition(variables): result = condition(hass, variables) condition_trace_update_result(result=result) return result return wrapper
Test a numeric state condition.
def 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: """Test a numeric state condition.""" return run_callback_threadsafe( hass.loop, async_numeric_state, hass, entity, below, above, value_template, variables, ).result()
Test a numeric state condition.
def 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: """Test a numeric state condition.""" if entity is None: raise ConditionErrorMessage("numeric_state", "no entity specified") if isinstance(entity, str): entity_id = entity if (entity := hass.states.get(entity)) is None: raise ConditionErrorMessage("numeric_state", f"unknown entity {entity_id}") else: entity_id = entity.entity_id if attribute is not None and attribute not in entity.attributes: condition_trace_set_result( False, message=f"attribute '{attribute}' of entity {entity_id} does not exist", ) return False value: Any = None if value_template is None: if attribute is None: value = entity.state else: value = entity.attributes.get(attribute) else: variables = dict(variables or {}) variables["state"] = entity try: value = value_template.async_render(variables) except TemplateError as ex: raise ConditionErrorMessage( "numeric_state", f"template error: {ex}" ) from ex # Known states or attribute values that never match the numeric condition if value in (None, STATE_UNAVAILABLE, STATE_UNKNOWN): condition_trace_set_result( False, message=f"value '{value}' is non-numeric and treated as False", ) return False try: fvalue = float(value) except (ValueError, TypeError) as ex: raise ConditionErrorMessage( "numeric_state", f"entity {entity_id} state '{value}' cannot be processed as a number", ) from ex if below is not None: if isinstance(below, str): if not (below_entity := hass.states.get(below)): raise ConditionErrorMessage( "numeric_state", f"unknown 'below' entity {below}" ) if below_entity.state in ( STATE_UNAVAILABLE, STATE_UNKNOWN, ): return False try: if fvalue >= float(below_entity.state): condition_trace_set_result( False, state=fvalue, wanted_state_below=float(below_entity.state), ) return False except (ValueError, TypeError) as ex: raise ConditionErrorMessage( "numeric_state", ( f"the 'below' entity {below} state '{below_entity.state}'" " cannot be processed as a number" ), ) from ex elif fvalue >= below: condition_trace_set_result(False, state=fvalue, wanted_state_below=below) return False if above is not None: if isinstance(above, str): if not (above_entity := hass.states.get(above)): raise ConditionErrorMessage( "numeric_state", f"unknown 'above' entity {above}" ) if above_entity.state in ( STATE_UNAVAILABLE, STATE_UNKNOWN, ): return False try: if fvalue <= float(above_entity.state): condition_trace_set_result( False, state=fvalue, wanted_state_above=float(above_entity.state), ) return False except (ValueError, TypeError) as ex: raise ConditionErrorMessage( "numeric_state", ( f"the 'above' entity {above} state '{above_entity.state}'" " cannot be processed as a number" ), ) from ex elif fvalue <= above: condition_trace_set_result(False, state=fvalue, wanted_state_above=above) return False condition_trace_set_result(True, state=fvalue) return True
Wrap action method with state based condition.
def async_numeric_state_from_config(config: ConfigType) -> ConditionCheckerType: """Wrap action method with state based condition.""" entity_ids = config.get(CONF_ENTITY_ID, []) attribute = config.get(CONF_ATTRIBUTE) below = config.get(CONF_BELOW) above = config.get(CONF_ABOVE) value_template = config.get(CONF_VALUE_TEMPLATE) @trace_condition_function def if_numeric_state( hass: HomeAssistant, variables: TemplateVarsType = None ) -> bool: """Test numeric state condition.""" if value_template is not None: value_template.hass = hass errors = [] for index, entity_id in enumerate(entity_ids): try: with trace_path(["entity_id", str(index)]), trace_condition(variables): if not async_numeric_state( hass, entity_id, below, above, value_template, variables, attribute, ): return False except ConditionError as ex: errors.append( ConditionErrorIndex( "numeric_state", index=index, total=len(entity_ids), error=ex ) ) # Raise the errors if no check was false if errors: raise ConditionErrorContainer("numeric_state", errors=errors) return True return if_numeric_state
Test if state matches requirements. Async friendly.
def state( hass: HomeAssistant, entity: None | str | State, req_state: Any, for_period: timedelta | None = None, attribute: str | None = None, variables: TemplateVarsType = None, ) -> bool: """Test if state matches requirements. Async friendly. """ if entity is None: raise ConditionErrorMessage("state", "no entity specified") if isinstance(entity, str): entity_id = entity if (entity := hass.states.get(entity)) is None: raise ConditionErrorMessage("state", f"unknown entity {entity_id}") else: entity_id = entity.entity_id if attribute is not None and attribute not in entity.attributes: condition_trace_set_result( False, message=f"attribute '{attribute}' of entity {entity_id} does not exist", ) return False assert isinstance(entity, State) if attribute is None: value: Any = entity.state else: value = entity.attributes.get(attribute) if not isinstance(req_state, list): req_state = [req_state] is_state = False for req_state_value in req_state: state_value = req_state_value if ( isinstance(req_state_value, str) and INPUT_ENTITY_ID.match(req_state_value) is not None ): if not (state_entity := hass.states.get(req_state_value)): raise ConditionErrorMessage( "state", f"the 'state' entity {req_state_value} is unavailable" ) state_value = state_entity.state is_state = value == state_value if is_state: break if for_period is None or not is_state: condition_trace_set_result(is_state, state=value, wanted_state=state_value) return is_state try: for_period = cv.positive_time_period(render_complex(for_period, variables)) except TemplateError as ex: raise ConditionErrorMessage("state", f"template error: {ex}") from ex except vol.Invalid as ex: raise ConditionErrorMessage("state", f"schema error: {ex}") from ex duration = dt_util.utcnow() - cast(timedelta, for_period) duration_ok = duration > entity.last_changed condition_trace_set_result(duration_ok, state=value, duration=duration) return duration_ok
Wrap action method with state based condition.
def state_from_config(config: ConfigType) -> ConditionCheckerType: """Wrap action method with state based condition.""" entity_ids = config.get(CONF_ENTITY_ID, []) req_states: str | list[str] = config.get(CONF_STATE, []) for_period = config.get(CONF_FOR) attribute = config.get(CONF_ATTRIBUTE) match = config.get(CONF_MATCH, ENTITY_MATCH_ALL) if not isinstance(req_states, list): req_states = [req_states] @trace_condition_function def if_state(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: """Test if condition.""" template_attach(hass, for_period) errors = [] result: bool = match != ENTITY_MATCH_ANY for index, entity_id in enumerate(entity_ids): try: with trace_path(["entity_id", str(index)]), trace_condition(variables): if state( hass, entity_id, req_states, for_period, attribute, variables ): result = True elif match == ENTITY_MATCH_ALL: return False except ConditionError as ex: errors.append( ConditionErrorIndex( "state", index=index, total=len(entity_ids), error=ex ) ) # Raise the errors if no check was false if errors: raise ConditionErrorContainer("state", errors=errors) return result return if_state
Test if current time matches sun requirements.
def sun( hass: HomeAssistant, before: str | None = None, after: str | None = None, before_offset: timedelta | None = None, after_offset: timedelta | None = None, ) -> bool: """Test if current time matches sun requirements.""" utcnow = dt_util.utcnow() today = dt_util.as_local(utcnow).date() before_offset = before_offset or timedelta(0) after_offset = after_offset or timedelta(0) sunrise = get_astral_event_date(hass, SUN_EVENT_SUNRISE, today) sunset = get_astral_event_date(hass, SUN_EVENT_SUNSET, today) has_sunrise_condition = SUN_EVENT_SUNRISE in (before, after) has_sunset_condition = SUN_EVENT_SUNSET in (before, after) after_sunrise = today > dt_util.as_local(cast(datetime, sunrise)).date() if after_sunrise and has_sunrise_condition: tomorrow = today + timedelta(days=1) sunrise = get_astral_event_date(hass, SUN_EVENT_SUNRISE, tomorrow) after_sunset = today > dt_util.as_local(cast(datetime, sunset)).date() if after_sunset and has_sunset_condition: tomorrow = today + timedelta(days=1) sunset = get_astral_event_date(hass, SUN_EVENT_SUNSET, tomorrow) # Special case: before sunrise OR after sunset # This will handle the very rare case in the polar region when the sun rises/sets # but does not set/rise. # However this entire condition does not handle those full days of darkness # or light, the following should be used instead: # # condition: # condition: state # entity_id: sun.sun # state: 'above_horizon' (or 'below_horizon') # if before == SUN_EVENT_SUNRISE and after == SUN_EVENT_SUNSET: wanted_time_before = cast(datetime, sunrise) + before_offset condition_trace_update_result(wanted_time_before=wanted_time_before) wanted_time_after = cast(datetime, sunset) + after_offset condition_trace_update_result(wanted_time_after=wanted_time_after) return utcnow < wanted_time_before or utcnow > wanted_time_after if sunrise is None and has_sunrise_condition: # There is no sunrise today condition_trace_set_result(False, message="no sunrise today") return False if sunset is None and has_sunset_condition: # There is no sunset today condition_trace_set_result(False, message="no sunset today") return False if before == SUN_EVENT_SUNRISE: wanted_time_before = cast(datetime, sunrise) + before_offset condition_trace_update_result(wanted_time_before=wanted_time_before) if utcnow > wanted_time_before: return False if before == SUN_EVENT_SUNSET: wanted_time_before = cast(datetime, sunset) + before_offset condition_trace_update_result(wanted_time_before=wanted_time_before) if utcnow > wanted_time_before: return False if after == SUN_EVENT_SUNRISE: wanted_time_after = cast(datetime, sunrise) + after_offset condition_trace_update_result(wanted_time_after=wanted_time_after) if utcnow < wanted_time_after: return False if after == SUN_EVENT_SUNSET: wanted_time_after = cast(datetime, sunset) + after_offset condition_trace_update_result(wanted_time_after=wanted_time_after) if utcnow < wanted_time_after: return False return True
Wrap action method with sun based condition.
def sun_from_config(config: ConfigType) -> ConditionCheckerType: """Wrap action method with sun based condition.""" before = config.get("before") after = config.get("after") before_offset = config.get("before_offset") after_offset = config.get("after_offset") @trace_condition_function def sun_if(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: """Validate time based if-condition.""" return sun(hass, before, after, before_offset, after_offset) return sun_if
Test if template condition matches.
def template( hass: HomeAssistant, value_template: Template, variables: TemplateVarsType = None ) -> bool: """Test if template condition matches.""" return run_callback_threadsafe( hass.loop, async_template, hass, value_template, variables ).result()
Test if template condition matches.
def async_template( hass: HomeAssistant, value_template: Template, variables: TemplateVarsType = None, trace_result: bool = True, ) -> bool: """Test if template condition matches.""" try: info = value_template.async_render_to_info(variables, parse_result=False) value = info.result() except TemplateError as ex: raise ConditionErrorMessage("template", str(ex)) from ex result = value.lower() == "true" if trace_result: condition_trace_set_result(result, entities=list(info.entities)) return result
Wrap action method with state based condition.
def async_template_from_config(config: ConfigType) -> ConditionCheckerType: """Wrap action method with state based condition.""" value_template = cast(Template, config.get(CONF_VALUE_TEMPLATE)) @trace_condition_function def template_if(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: """Validate template based if-condition.""" value_template.hass = hass return async_template(hass, value_template, variables) return template_if
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)".
def time( hass: HomeAssistant, before: dt_time | str | None = None, after: dt_time | str | None = None, weekday: None | str | Container[str] = None, ) -> bool: """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)". """ now = dt_util.now() now_time = now.time() if after is None: after = dt_time(0) elif isinstance(after, str): if not (after_entity := hass.states.get(after)): raise ConditionErrorMessage("time", f"unknown 'after' entity {after}") if after_entity.domain == "input_datetime": after = dt_time( after_entity.attributes.get("hour", 23), after_entity.attributes.get("minute", 59), after_entity.attributes.get("second", 59), ) elif after_entity.attributes.get( ATTR_DEVICE_CLASS ) == SensorDeviceClass.TIMESTAMP and after_entity.state not in ( STATE_UNAVAILABLE, STATE_UNKNOWN, ): after_datetime = dt_util.parse_datetime(after_entity.state) if after_datetime is None: return False after = dt_util.as_local(after_datetime).time() else: return False if before is None: before = dt_time(23, 59, 59, 999999) elif isinstance(before, str): if not (before_entity := hass.states.get(before)): raise ConditionErrorMessage("time", f"unknown 'before' entity {before}") if before_entity.domain == "input_datetime": before = dt_time( before_entity.attributes.get("hour", 23), before_entity.attributes.get("minute", 59), before_entity.attributes.get("second", 59), ) elif before_entity.attributes.get( ATTR_DEVICE_CLASS ) == SensorDeviceClass.TIMESTAMP and before_entity.state not in ( STATE_UNAVAILABLE, STATE_UNKNOWN, ): before_timedatime = dt_util.parse_datetime(before_entity.state) if before_timedatime is None: return False before = dt_util.as_local(before_timedatime).time() else: return False if after < before: condition_trace_update_result(after=after, now_time=now_time, before=before) if not after <= now_time < before: return False else: condition_trace_update_result(after=after, now_time=now_time, before=before) if before <= now_time < after: return False if weekday is not None: now_weekday = WEEKDAYS[now.weekday()] condition_trace_update_result(weekday=weekday, now_weekday=now_weekday) if ( isinstance(weekday, str) and weekday != now_weekday or now_weekday not in weekday ): return False return True
Wrap action method with time based condition.
def time_from_config(config: ConfigType) -> ConditionCheckerType: """Wrap action method with time based condition.""" before = config.get(CONF_BEFORE) after = config.get(CONF_AFTER) weekday = config.get(CONF_WEEKDAY) @trace_condition_function def time_if(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: """Validate time based if-condition.""" return time(hass, before, after, weekday) return time_if
Test if zone-condition matches. Async friendly.
def zone( hass: HomeAssistant, zone_ent: None | str | State, entity: None | str | State, ) -> bool: """Test if zone-condition matches. Async friendly. """ if zone_ent is None: raise ConditionErrorMessage("zone", "no zone specified") if isinstance(zone_ent, str): zone_ent_id = zone_ent if (zone_ent := hass.states.get(zone_ent)) is None: raise ConditionErrorMessage("zone", f"unknown zone {zone_ent_id}") if entity is None: raise ConditionErrorMessage("zone", "no entity specified") if isinstance(entity, str): entity_id = entity if (entity := hass.states.get(entity)) is None: raise ConditionErrorMessage("zone", f"unknown entity {entity_id}") else: entity_id = entity.entity_id if entity.state in ( STATE_UNAVAILABLE, STATE_UNKNOWN, ): return False latitude = entity.attributes.get(ATTR_LATITUDE) longitude = entity.attributes.get(ATTR_LONGITUDE) if latitude is None: raise ConditionErrorMessage( "zone", f"entity {entity_id} has no 'latitude' attribute" ) if longitude is None: raise ConditionErrorMessage( "zone", f"entity {entity_id} has no 'longitude' attribute" ) return zone_cmp.in_zone( zone_ent, latitude, longitude, entity.attributes.get(ATTR_GPS_ACCURACY, 0) )
Wrap action method with zone based condition.
def zone_from_config(config: ConfigType) -> ConditionCheckerType: """Wrap action method with zone based condition.""" entity_ids = config.get(CONF_ENTITY_ID, []) zone_entity_ids = config.get(CONF_ZONE, []) @trace_condition_function def if_in_zone(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: """Test if condition.""" errors = [] all_ok = True for entity_id in entity_ids: entity_ok = False for zone_entity_id in zone_entity_ids: try: if zone(hass, zone_entity_id, entity_id): entity_ok = True except ConditionErrorMessage as ex: errors.append( ConditionErrorMessage( "zone", ( f"error matching {entity_id} with {zone_entity_id}:" f" {ex.message}" ), ) ) if not entity_ok: all_ok = False # Raise the errors only if no definitive result was found if errors and not all_ok: raise ConditionErrorContainer("zone", errors=errors) return all_ok return if_in_zone
Validate numeric_state condition config.
def numeric_state_validate_config( hass: HomeAssistant, config: ConfigType ) -> ConfigType: """Validate numeric_state condition config.""" registry = er.async_get(hass) config = dict(config) config[CONF_ENTITY_ID] = er.async_validate_entity_ids( registry, cv.entity_ids_or_uuids(config[CONF_ENTITY_ID]) ) return config
Validate state condition config.
def state_validate_config(hass: HomeAssistant, config: ConfigType) -> ConfigType: """Validate state condition config.""" registry = er.async_get(hass) config = dict(config) config[CONF_ENTITY_ID] = er.async_validate_entity_ids( registry, cv.entity_ids_or_uuids(config[CONF_ENTITY_ID]) ) return config
Extract entities from a condition.
def async_extract_entities(config: ConfigType | Template) -> set[str]: """Extract entities from a condition.""" referenced: set[str] = set() to_process = deque([config]) while to_process: config = to_process.popleft() if isinstance(config, Template): continue condition = config[CONF_CONDITION] if condition in ("and", "not", "or"): to_process.extend(config["conditions"]) continue entity_ids = config.get(CONF_ENTITY_ID) if isinstance(entity_ids, str): entity_ids = [entity_ids] if entity_ids is not None: referenced.update(entity_ids) return referenced
Extract devices from a condition.
def async_extract_devices(config: ConfigType | Template) -> set[str]: """Extract devices from a condition.""" referenced = set() to_process = deque([config]) while to_process: config = to_process.popleft() if isinstance(config, Template): continue condition = config[CONF_CONDITION] if condition in ("and", "not", "or"): to_process.extend(config["conditions"]) continue if condition != "device": continue if (device_id := config.get(CONF_DEVICE_ID)) is not None: referenced.add(device_id) return referenced
Register flow for discovered integrations that not require auth.
def register_discovery_flow( domain: str, title: str, discovery_function: DiscoveryFunctionType[Awaitable[bool] | bool], ) -> None: """Register flow for discovered integrations that not require auth.""" class DiscoveryFlow(DiscoveryFlowHandler[Awaitable[bool] | bool]): """Discovery flow handler.""" def __init__(self) -> None: super().__init__(domain, title, discovery_function) config_entries.HANDLERS.register(domain)(DiscoveryFlow)
Register flow for webhook integrations.
def register_webhook_flow( domain: str, title: str, description_placeholder: dict, allow_multiple: bool = False ) -> None: """Register flow for webhook integrations.""" class WebhookFlow(WebhookFlowHandler): """Webhook flow handler.""" def __init__(self) -> None: super().__init__(domain, title, description_placeholder, allow_multiple) config_entries.HANDLERS.register(domain)(WebhookFlow)
Register an OAuth2 flow implementation for an integration.
def async_register_implementation( hass: HomeAssistant, domain: str, implementation: AbstractOAuth2Implementation ) -> None: """Register an OAuth2 flow implementation for an integration.""" implementations = hass.data.setdefault(DATA_IMPLEMENTATIONS, {}) implementations.setdefault(domain, {})[implementation.domain] = implementation
Add an implementation provider. If no implementation found, return None.
def async_add_implementation_provider( hass: HomeAssistant, provider_domain: str, async_provide_implementation: Callable[ [HomeAssistant, str], Awaitable[list[AbstractOAuth2Implementation]] ], ) -> None: """Add an implementation provider. If no implementation found, return None. """ hass.data.setdefault(DATA_PROVIDERS, {})[provider_domain] = ( async_provide_implementation )
JWT encode data.
def _encode_jwt(hass: HomeAssistant, data: dict) -> str: """JWT encode data.""" if (secret := hass.data.get(DATA_JWT_SECRET)) is None: secret = hass.data[DATA_JWT_SECRET] = secrets.token_hex() return jwt.encode(data, secret, algorithm="HS256")
JWT encode data.
def _decode_jwt(hass: HomeAssistant, encoded: str) -> dict[str, Any] | None: """JWT encode data.""" secret: str | None = hass.data.get(DATA_JWT_SECRET) if secret is None: return None try: return jwt.decode(encoded, secret, algorithms=["HS256"]) # type: ignore[no-any-return] except jwt.InvalidTokenError: return None
Validate it's a safe path.
def path(value: Any) -> str: """Validate it's a safe path.""" if not isinstance(value, str): raise vol.Invalid("Expected a string") try: raise_if_invalid_path(value) except ValueError as err: raise vol.Invalid("Invalid path") from err return value
Validate that at least one key exists.
def has_at_least_one_key(*keys: Any) -> Callable[[dict], dict]: """Validate that at least one key exists.""" key_set = set(keys) def validate(obj: dict) -> dict: """Test keys exist in dict.""" if not isinstance(obj, dict): raise vol.Invalid("expected dictionary") if not key_set.isdisjoint(obj): return obj expected = ", ".join(str(k) for k in keys) raise vol.Invalid(f"must contain at least one of {expected}.") return validate
Validate that zero keys exist or one key exists.
def has_at_most_one_key(*keys: Any) -> Callable[[dict], dict]: """Validate that zero keys exist or one key exists.""" def validate(obj: dict) -> dict: """Test zero keys exist or one key exists in dict.""" if not isinstance(obj, dict): raise vol.Invalid("expected dictionary") if len(set(keys) & set(obj)) > 1: expected = ", ".join(str(k) for k in keys) raise vol.Invalid(f"must contain at most one of {expected}.") return obj return validate
Validate and coerce a boolean value.
def boolean(value: Any) -> bool: """Validate and coerce a boolean value.""" if isinstance(value, bool): return value if isinstance(value, str): value = value.lower().strip() if value in ("1", "true", "yes", "on", "enable"): return True if value in ("0", "false", "no", "off", "disable"): return False elif isinstance(value, Number): # type ignore: https://github.com/python/mypy/issues/3186 return value != 0 # type: ignore[comparison-overlap] raise vol.Invalid(f"invalid boolean value {value}")
Validate result contains only whitespace.
def whitespace(value: Any) -> str: """Validate result contains only whitespace.""" if isinstance(value, str) and (value == "" or value.isspace()): return value raise vol.Invalid(f"contains non-whitespace: {value}")
Validate that value is a real device.
def isdevice(value: Any) -> str: """Validate that value is a real device.""" try: os.stat(value) return str(value) except OSError as err: raise vol.Invalid(f"No device at {value} found") from err
Validate that the value is a string that matches a regex.
def matches_regex(regex: str) -> Callable[[Any], str]: """Validate that the value is a string that matches a regex.""" compiled = re.compile(regex) def validator(value: Any) -> str: """Validate that value matches the given regex.""" if not isinstance(value, str): raise vol.Invalid(f"not a string value: {value}") if not compiled.match(value): raise vol.Invalid( f"value {value} does not match regular expression {compiled.pattern}" ) return value return validator
Validate that a string is a valid regular expression.
def is_regex(value: Any) -> re.Pattern[Any]: """Validate that a string is a valid regular expression.""" try: r = re.compile(value) except TypeError as err: raise vol.Invalid( f"value {value} is of the wrong type for a regular expression" ) from err except re.error as err: raise vol.Invalid(f"value {value} is not a valid regular expression") from err return r
Validate that the value is an existing file.
def isfile(value: Any) -> str: """Validate that the value is an existing file.""" if value is None: raise vol.Invalid("None is not file") file_in = os.path.expanduser(str(value)) if not os.path.isfile(file_in): raise vol.Invalid("not a file") if not os.access(file_in, os.R_OK): raise vol.Invalid("file not readable") return file_in
Validate that the value is an existing dir.
def isdir(value: Any) -> str: """Validate that the value is an existing dir.""" if value is None: raise vol.Invalid("not a directory") dir_in = os.path.expanduser(str(value)) if not os.path.isdir(dir_in): raise vol.Invalid("not a directory") if not os.access(dir_in, os.R_OK): raise vol.Invalid("directory not readable") return dir_in
Wrap value in list if it is not one.
def ensure_list(value: _T | None) -> list[_T] | list[Any]: """Wrap value in list if it is not one.""" if value is None: return [] return cast("list[_T]", value) if isinstance(value, list) else [value]
Validate Entity ID.
def entity_id(value: Any) -> str: """Validate Entity ID.""" str_value = string(value).lower() if valid_entity_id(str_value): return str_value raise vol.Invalid(f"Entity ID {value} is an invalid entity ID")
Validate Entity specified by entity_id or uuid.
def entity_id_or_uuid(value: Any) -> str: """Validate Entity specified by entity_id or uuid.""" with contextlib.suppress(vol.Invalid): return entity_id(value) with contextlib.suppress(vol.Invalid): return fake_uuid4_hex(value) raise vol.Invalid(f"Entity {value} is neither a valid entity ID nor a valid UUID")
Help validate entity IDs or UUIDs.
def _entity_ids(value: str | list, allow_uuid: bool) -> list[str]: """Help validate entity IDs or UUIDs.""" if value is None: raise vol.Invalid("Entity IDs cannot be None") if isinstance(value, str): value = [ent_id.strip() for ent_id in value.split(",")] validator = entity_id_or_uuid if allow_uuid else entity_id return [validator(ent_id) for ent_id in value]
Validate Entity IDs.
def entity_ids(value: str | list) -> list[str]: """Validate Entity IDs.""" return _entity_ids(value, False)
Validate entities specified by entity IDs or UUIDs.
def entity_ids_or_uuids(value: str | list) -> list[str]: """Validate entities specified by entity IDs or UUIDs.""" return _entity_ids(value, True)