Home Assistant Unofficial Reference 2024.12.1
trigger.py
Go to the documentation of this file.
1 """Offer sun based automation rules."""
2 
3 from datetime import timedelta
4 
5 import voluptuous as vol
6 
7 from homeassistant.const import (
8  CONF_EVENT,
9  CONF_OFFSET,
10  CONF_PLATFORM,
11  SUN_EVENT_SUNRISE,
12 )
13 from homeassistant.core import CALLBACK_TYPE, HassJob, HomeAssistant, callback
15 from homeassistant.helpers.event import async_track_sunrise, async_track_sunset
16 from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
17 from homeassistant.helpers.typing import ConfigType
18 
19 TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
20  {
21  vol.Required(CONF_PLATFORM): "sun",
22  vol.Required(CONF_EVENT): cv.sun_event,
23  vol.Required(CONF_OFFSET, default=timedelta(0)): cv.time_period,
24  }
25 )
26 
27 
29  hass: HomeAssistant,
30  config: ConfigType,
31  action: TriggerActionType,
32  trigger_info: TriggerInfo,
33 ) -> CALLBACK_TYPE:
34  """Listen for events based on configuration."""
35  trigger_data = trigger_info["trigger_data"]
36  event = config.get(CONF_EVENT)
37  offset = config.get(CONF_OFFSET)
38  description = event
39  if offset:
40  description = f"{description} with offset"
41  job = HassJob(action)
42 
43  @callback
44  def call_action() -> None:
45  """Call action with right context."""
46  hass.async_run_hass_job(
47  job,
48  {
49  "trigger": {
50  **trigger_data,
51  "platform": "sun",
52  "event": event,
53  "offset": offset,
54  "description": description,
55  }
56  },
57  )
58 
59  if event == SUN_EVENT_SUNRISE:
60  return async_track_sunrise(hass, call_action, offset)
61  return async_track_sunset(hass, call_action, offset)
CALLBACK_TYPE async_attach_trigger(HomeAssistant hass, ConfigType config, TriggerActionType action, TriggerInfo trigger_info)
Definition: trigger.py:33
CALLBACK_TYPE async_track_sunset(HomeAssistant hass, Callable[[], None] action, timedelta|None offset=None)
Definition: event.py:1776
CALLBACK_TYPE async_track_sunrise(HomeAssistant hass, Callable[[], None] action, timedelta|None offset=None)
Definition: event.py:1760