Home Assistant Unofficial Reference 2024.12.1
device_condition.py
Go to the documentation of this file.
1 """Provide the device automations for Vacuum."""
2 
3 from __future__ import annotations
4 
5 import voluptuous as vol
6 
7 from homeassistant.const import (
8  CONF_CONDITION,
9  CONF_DEVICE_ID,
10  CONF_DOMAIN,
11  CONF_ENTITY_ID,
12  CONF_TYPE,
13 )
14 from homeassistant.core import HomeAssistant, callback
15 from homeassistant.helpers import (
16  condition,
17  config_validation as cv,
18  entity_registry as er,
19 )
20 from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA
21 from homeassistant.helpers.typing import ConfigType, TemplateVarsType
22 
23 from . import DOMAIN, STATE_CLEANING, STATE_DOCKED, STATE_RETURNING
24 
25 CONDITION_TYPES = {"is_cleaning", "is_docked"}
26 
27 CONDITION_SCHEMA = DEVICE_CONDITION_BASE_SCHEMA.extend(
28  {
29  vol.Required(CONF_ENTITY_ID): cv.entity_id_or_uuid,
30  vol.Required(CONF_TYPE): vol.In(CONDITION_TYPES),
31  }
32 )
33 
34 
36  hass: HomeAssistant, device_id: str
37 ) -> list[dict[str, str]]:
38  """List device conditions for Vacuum devices."""
39  registry = er.async_get(hass)
40  conditions = []
41 
42  # Get all the integrations entities for this device
43  for entry in er.async_entries_for_device(registry, device_id):
44  if entry.domain != DOMAIN:
45  continue
46 
47  base_condition = {
48  CONF_CONDITION: "device",
49  CONF_DEVICE_ID: device_id,
50  CONF_DOMAIN: DOMAIN,
51  CONF_ENTITY_ID: entry.id,
52  }
53 
54  conditions += [{**base_condition, CONF_TYPE: cond} for cond in CONDITION_TYPES]
55 
56  return conditions
57 
58 
59 @callback
61  hass: HomeAssistant, config: ConfigType
62 ) -> condition.ConditionCheckerType:
63  """Create a function to test a device condition."""
64  if config[CONF_TYPE] == "is_docked":
65  test_states = [STATE_DOCKED]
66  else:
67  test_states = [STATE_CLEANING, STATE_RETURNING]
68 
69  registry = er.async_get(hass)
70  entity_id = er.async_resolve_entity_id(registry, config[CONF_ENTITY_ID])
71 
72  def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
73  """Test if an entity is a certain state."""
74  return (
75  entity_id is not None
76  and (state := hass.states.get(entity_id)) is not None
77  and state.state in test_states
78  )
79 
80  return test_is_state
condition.ConditionCheckerType async_condition_from_config(HomeAssistant hass, ConfigType config)
list[dict[str, str]] async_get_conditions(HomeAssistant hass, str device_id)