Home Assistant Unofficial Reference 2024.12.1
device_trigger.py
Go to the documentation of this file.
1 """Provides device automations for Nest."""
2 
3 from __future__ import annotations
4 
5 import voluptuous as vol
6 
8  DEVICE_TRIGGER_BASE_SCHEMA,
9  InvalidDeviceAutomationConfig,
10 )
11 from homeassistant.components.homeassistant.triggers import event as event_trigger
12 from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE
13 from homeassistant.core import CALLBACK_TYPE, HomeAssistant
14 from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
15 from homeassistant.helpers.typing import ConfigType
16 
17 from .const import DOMAIN
18 from .device_info import async_nest_devices_by_device_id
19 from .events import DEVICE_TRAIT_TRIGGER_MAP, NEST_EVENT
20 
21 DEVICE = "device"
22 
23 TRIGGER_TYPES = set(DEVICE_TRAIT_TRIGGER_MAP.values())
24 
25 TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
26  {
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 a Nest device."""
36  devices = async_nest_devices_by_device_id(hass)
37  if not (device := devices.get(device_id)):
38  raise InvalidDeviceAutomationConfig(f"Device not found {device_id}")
39  trigger_types = [
40  trigger_type
41  for trait in device.traits
42  if (trigger_type := DEVICE_TRAIT_TRIGGER_MAP.get(trait))
43  ]
44  return [
45  {
46  CONF_PLATFORM: DEVICE,
47  CONF_DEVICE_ID: device_id,
48  CONF_DOMAIN: DOMAIN,
49  CONF_TYPE: trigger_type,
50  }
51  for trigger_type in trigger_types
52  ]
53 
54 
56  hass: HomeAssistant,
57  config: ConfigType,
58  action: TriggerActionType,
59  trigger_info: TriggerInfo,
60 ) -> CALLBACK_TYPE:
61  """Attach a trigger."""
62  event_config = event_trigger.TRIGGER_SCHEMA(
63  {
64  event_trigger.CONF_PLATFORM: "event",
65  event_trigger.CONF_EVENT_TYPE: NEST_EVENT,
66  event_trigger.CONF_EVENT_DATA: {
67  CONF_DEVICE_ID: config[CONF_DEVICE_ID],
68  CONF_TYPE: config[CONF_TYPE],
69  },
70  }
71  )
72  return await event_trigger.async_attach_trigger(
73  hass, event_config, action, trigger_info, platform_type="device"
74  )
Mapping[str, Device] async_nest_devices_by_device_id(HomeAssistant hass)
Definition: device_info.py:95
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)