Home Assistant Unofficial Reference 2024.12.1
device_trigger.py
Go to the documentation of this file.
1 """Provides device triggers for Button."""
2 
3 from __future__ import annotations
4 
5 import voluptuous as vol
6 
7 from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
9  async_attach_trigger as async_attach_state_trigger,
10  async_validate_trigger_config as async_validate_state_trigger_config,
11 )
12 from homeassistant.const import (
13  CONF_DEVICE_ID,
14  CONF_DOMAIN,
15  CONF_ENTITY_ID,
16  CONF_PLATFORM,
17  CONF_TYPE,
18 )
19 from homeassistant.core import CALLBACK_TYPE, HomeAssistant
20 from homeassistant.helpers import config_validation as cv, entity_registry as er
21 from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
22 from homeassistant.helpers.typing import ConfigType
23 
24 from .const import DOMAIN
25 
26 TRIGGER_TYPES = {"pressed"}
27 
28 TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
29  {
30  vol.Required(CONF_ENTITY_ID): cv.entity_id_or_uuid,
31  vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
32  }
33 )
34 
35 
37  hass: HomeAssistant, device_id: str
38 ) -> list[dict[str, str]]:
39  """List device triggers for button devices."""
40  registry = er.async_get(hass)
41  return [
42  {
43  CONF_PLATFORM: "device",
44  CONF_DEVICE_ID: device_id,
45  CONF_DOMAIN: DOMAIN,
46  CONF_ENTITY_ID: entry.id,
47  CONF_TYPE: "pressed",
48  }
49  for entry in er.async_entries_for_device(registry, device_id)
50  if entry.domain == DOMAIN
51  ]
52 
53 
55  hass: HomeAssistant,
56  config: ConfigType,
57  action: TriggerActionType,
58  trigger_info: TriggerInfo,
59 ) -> CALLBACK_TYPE:
60  """Attach a trigger."""
61  state_config = {
62  CONF_PLATFORM: "state",
63  CONF_ENTITY_ID: config[CONF_ENTITY_ID],
64  }
65 
66  state_config = await async_validate_state_trigger_config(hass, state_config)
67  return await async_attach_state_trigger(
68  hass, state_config, action, trigger_info, platform_type="device"
69  )
CALLBACK_TYPE async_attach_trigger(HomeAssistant hass, ConfigType config, TriggerActionType action, TriggerInfo trigger_info)
list[dict[str, str]] async_get_triggers(HomeAssistant hass, str device_id)