Home Assistant Unofficial Reference 2024.12.1
device_condition.py
Go to the documentation of this file.
1 """Provides device automations for Media player."""
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_BUFFERING,
15  STATE_IDLE,
16  STATE_OFF,
17  STATE_ON,
18  STATE_PAUSED,
19  STATE_PLAYING,
20 )
21 from homeassistant.core import HomeAssistant, callback
22 from homeassistant.helpers import (
23  condition,
24  config_validation as cv,
25  entity_registry as er,
26 )
27 from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA
28 from homeassistant.helpers.typing import ConfigType, TemplateVarsType
29 
30 from .const import DOMAIN
31 
32 CONDITION_TYPES = {
33  "is_on",
34  "is_off",
35  "is_buffering",
36  "is_idle",
37  "is_paused",
38  "is_playing",
39 }
40 
41 CONDITION_SCHEMA = DEVICE_CONDITION_BASE_SCHEMA.extend(
42  {
43  vol.Required(CONF_ENTITY_ID): cv.entity_id_or_uuid,
44  vol.Required(CONF_TYPE): vol.In(CONDITION_TYPES),
45  }
46 )
47 
48 
50  hass: HomeAssistant, device_id: str
51 ) -> list[dict[str, str]]:
52  """List device conditions for Media player devices."""
53  registry = er.async_get(hass)
54  conditions: list[dict[str, str]] = []
55 
56  # Get all the integrations entities for this device
57  for entry in er.async_entries_for_device(registry, device_id):
58  if entry.domain != DOMAIN:
59  continue
60 
61  # Add conditions for each entity that belongs to this integration
62  base_condition = {
63  CONF_CONDITION: "device",
64  CONF_DEVICE_ID: device_id,
65  CONF_DOMAIN: DOMAIN,
66  CONF_ENTITY_ID: entry.id,
67  }
68 
69  conditions += [{**base_condition, CONF_TYPE: cond} for cond in CONDITION_TYPES]
70 
71  return conditions
72 
73 
74 @callback
76  hass: HomeAssistant, config: ConfigType
77 ) -> condition.ConditionCheckerType:
78  """Create a function to test a device condition."""
79  if config[CONF_TYPE] == "is_buffering":
80  state = STATE_BUFFERING
81  elif config[CONF_TYPE] == "is_idle":
82  state = STATE_IDLE
83  elif config[CONF_TYPE] == "is_off":
84  state = STATE_OFF
85  elif config[CONF_TYPE] == "is_on":
86  state = STATE_ON
87  elif config[CONF_TYPE] == "is_paused":
88  state = STATE_PAUSED
89  else: # is_playing
90  state = STATE_PLAYING
91 
92  registry = er.async_get(hass)
93  entity_id = er.async_resolve_entity_id(registry, config[ATTR_ENTITY_ID])
94 
95  def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool:
96  """Test if an entity is a certain state."""
97  return condition.state(hass, entity_id, state)
98 
99  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)