Home Assistant Unofficial Reference 2024.12.1
device_condition.py
Go to the documentation of this file.
1 """Provides device automations for Device tracker."""
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_HOME,
15 )
16 from homeassistant.core import HomeAssistant, callback
17 from homeassistant.helpers import (
18  condition,
19  config_validation as cv,
20  entity_registry as er,
21 )
22 from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA
23 from homeassistant.helpers.typing import ConfigType, TemplateVarsType
24 
25 from .const import DOMAIN
26 
27 CONDITION_TYPES = {"is_home", "is_not_home"}
28 
29 CONDITION_SCHEMA = DEVICE_CONDITION_BASE_SCHEMA.extend(
30  {
31  vol.Required(CONF_ENTITY_ID): cv.entity_id_or_uuid,
32  vol.Required(CONF_TYPE): vol.In(CONDITION_TYPES),
33  }
34 )
35 
36 
38  hass: HomeAssistant, device_id: str
39 ) -> list[dict[str, str]]:
40  """List device conditions for Device tracker devices."""
41  registry = er.async_get(hass)
42  conditions = []
43 
44  # Get all the integrations entities for this device
45  for entry in er.async_entries_for_device(registry, device_id):
46  if entry.domain != DOMAIN:
47  continue
48 
49  # Add conditions for each entity that belongs to this integration
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  reverse = config[CONF_TYPE] == "is_not_home"
70 
71  @callback
72  def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
73  """Test if an entity is a certain state."""
74  result = condition.state(hass, entity_id, STATE_HOME)
75  if reverse:
76  result = not result
77  return result
78 
79  return test_is_state
list[dict[str, str]] async_get_conditions(HomeAssistant hass, str device_id)
condition.ConditionCheckerType async_condition_from_config(HomeAssistant hass, ConfigType config)