Home Assistant Unofficial Reference 2024.12.1
device_trigger.py
Go to the documentation of this file.
1 """Provides device automations for Arcam FMJ Receiver control."""
2 
3 from __future__ import annotations
4 
5 import voluptuous as vol
6 
7 from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
8 from homeassistant.const import (
9  ATTR_ENTITY_ID,
10  CONF_DEVICE_ID,
11  CONF_DOMAIN,
12  CONF_ENTITY_ID,
13  CONF_PLATFORM,
14  CONF_TYPE,
15 )
16 from homeassistant.core import CALLBACK_TYPE, Event, HassJob, HomeAssistant, callback
17 from homeassistant.helpers import config_validation as cv, entity_registry as er
18 from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
19 from homeassistant.helpers.typing import ConfigType
20 
21 from .const import DOMAIN, EVENT_TURN_ON
22 
23 TRIGGER_TYPES = {"turn_on"}
24 TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
25  {
26  vol.Required(CONF_ENTITY_ID): cv.entity_id_or_uuid,
27  vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES),
28  }
29 )
30 
31 
33  hass: HomeAssistant, device_id: str
34 ) -> list[dict[str, str]]:
35  """List device triggers for Arcam FMJ Receiver control devices."""
36  entity_registry = er.async_get(hass)
37 
38  return [
39  {
40  CONF_PLATFORM: "device",
41  CONF_DEVICE_ID: device_id,
42  CONF_DOMAIN: DOMAIN,
43  CONF_ENTITY_ID: entry.id,
44  CONF_TYPE: "turn_on",
45  }
46  for entry in er.async_entries_for_device(entity_registry, device_id)
47  if entry.domain == "media_player"
48  ]
49 
50 
52  hass: HomeAssistant,
53  config: ConfigType,
54  action: TriggerActionType,
55  trigger_info: TriggerInfo,
56 ) -> CALLBACK_TYPE:
57  """Attach a trigger."""
58  trigger_data = trigger_info["trigger_data"]
59  job = HassJob(action)
60 
61  if config[CONF_TYPE] == "turn_on":
62  registry = er.async_get(hass)
63  entity_id = er.async_resolve_entity_id(registry, config[ATTR_ENTITY_ID])
64 
65  @callback
66  def _handle_event(event: Event) -> None:
67  if event.data[ATTR_ENTITY_ID] == entity_id:
68  hass.async_run_hass_job(
69  job,
70  {
71  "trigger": {
72  **trigger_data,
73  **config,
74  "description": f"{DOMAIN} - {entity_id}",
75  "entity_id": entity_id,
76  }
77  },
78  event.context,
79  )
80 
81  return hass.bus.async_listen(EVENT_TURN_ON, _handle_event)
82 
83  return lambda: None
list[dict[str, str]] async_get_triggers(HomeAssistant hass, str device_id)
CALLBACK_TYPE async_attach_trigger(HomeAssistant hass, ConfigType config, TriggerActionType action, TriggerInfo trigger_info)