Home Assistant Unofficial Reference 2024.12.1
trigger.py
Go to the documentation of this file.
1 """Offer persistent_notifications triggered automation rules."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Final
7 
8 import voluptuous as vol
9 
10 from homeassistant.const import CONF_PLATFORM
11 from homeassistant.core import CALLBACK_TYPE, HassJob, HomeAssistant, callback
13 from homeassistant.helpers.trigger import TriggerActionType, TriggerData, TriggerInfo
14 from homeassistant.helpers.typing import ConfigType
15 
16 from . import Notification, UpdateType, async_register_callback
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
21 CONF_NOTIFICATION_ID: Final = "notification_id"
22 CONF_UPDATE_TYPE: Final = "update_type"
23 
24 TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
25  {
26  vol.Required(CONF_PLATFORM): "persistent_notification",
27  vol.Optional(CONF_NOTIFICATION_ID): str,
28  vol.Optional(CONF_UPDATE_TYPE): vol.All(
29  cv.ensure_list, [vol.Coerce(UpdateType)]
30  ),
31  }
32 )
33 
34 
36  hass: HomeAssistant,
37  config: ConfigType,
38  action: TriggerActionType,
39  trigger_info: TriggerInfo,
40 ) -> CALLBACK_TYPE:
41  """Listen for state changes based on configuration."""
42  trigger_data: TriggerData = trigger_info["trigger_data"]
43  job = HassJob(action)
44 
45  persistent_notification_id = config.get(CONF_NOTIFICATION_ID)
46  update_types = config.get(CONF_UPDATE_TYPE)
47 
48  @callback
49  def persistent_notification_listener(
50  update_type: UpdateType, notifications: dict[str, Notification]
51  ) -> None:
52  """Listen for persistent_notification updates."""
53 
54  for notification in notifications.values():
55  if update_types and update_type not in update_types:
56  continue
57  if (
58  persistent_notification_id
59  and notification[CONF_NOTIFICATION_ID] != persistent_notification_id
60  ):
61  continue
62 
63  hass.async_run_hass_job(
64  job,
65  {
66  "trigger": {
67  **trigger_data,
68  "platform": "persistent_notification",
69  "update_type": update_type,
70  "notification": notification,
71  }
72  },
73  )
74 
75  _LOGGER.debug(
76  "Attaching persistent_notification trigger for ID: '%s', update_types: %s",
77  persistent_notification_id,
78  update_types,
79  )
80 
81  return async_register_callback(hass, persistent_notification_listener)
CALLBACK_TYPE async_attach_trigger(HomeAssistant hass, ConfigType config, TriggerActionType action, TriggerInfo trigger_info)
Definition: trigger.py:40
CALLBACK_TYPE async_register_callback(HomeAssistant hass, Callable[[UpdateType, dict[str, Notification]], None] _callback)
Definition: __init__.py:71