Home Assistant Unofficial Reference 2024.12.1
homeassistant.py
Go to the documentation of this file.
1 """Offer Home Assistant core automation rules."""
2 
3 import voluptuous as vol
4 
5 from homeassistant.const import CONF_EVENT, CONF_PLATFORM
6 from homeassistant.core import CALLBACK_TYPE, HassJob, HomeAssistant
7 from homeassistant.helpers import config_validation as cv
8 from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
9 from homeassistant.helpers.typing import ConfigType
10 
11 from ..const import DOMAIN
12 
13 EVENT_START = "start"
14 EVENT_SHUTDOWN = "shutdown"
15 
16 TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
17  {
18  vol.Required(CONF_PLATFORM): DOMAIN,
19  vol.Required(CONF_EVENT): vol.Any(EVENT_START, EVENT_SHUTDOWN),
20  }
21 )
22 
23 
25  hass: HomeAssistant,
26  config: ConfigType,
27  action: TriggerActionType,
28  trigger_info: TriggerInfo,
29 ) -> CALLBACK_TYPE:
30  """Listen for events based on configuration."""
31  trigger_data = trigger_info["trigger_data"]
32  event = config.get(CONF_EVENT)
33  job = HassJob(action, f"homeassistant trigger {trigger_info}")
34 
35  if event == EVENT_SHUTDOWN:
36  return hass.async_add_shutdown_job(
37  job,
38  {
39  "trigger": {
40  **trigger_data,
41  "platform": DOMAIN,
42  "event": event,
43  "description": "Home Assistant stopping",
44  }
45  },
46  )
47 
48  # Automation are enabled while hass is starting up, fire right away
49  # Check state because a config reload shouldn't trigger it.
50  if trigger_info["home_assistant_start"]:
51  hass.async_run_hass_job(
52  job,
53  {
54  "trigger": {
55  **trigger_data,
56  "platform": DOMAIN,
57  "event": event,
58  "description": "Home Assistant starting",
59  }
60  },
61  )
62 
63  return lambda: None
CALLBACK_TYPE async_attach_trigger(HomeAssistant hass, ConfigType config, TriggerActionType action, TriggerInfo trigger_info)