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