core/homeassistant/components/sun/trigger.py

56 lines
1.6 KiB
Python
Raw Normal View History

"""Offer sun based automation rules."""
2015-09-15 07:02:54 +00:00
from datetime import timedelta
import voluptuous as vol
2015-09-15 07:02:54 +00:00
2016-05-03 05:05:09 +00:00
from homeassistant.const import (
2019-07-31 19:25:30 +00:00
CONF_EVENT,
CONF_OFFSET,
CONF_PLATFORM,
SUN_EVENT_SUNRISE,
)
from homeassistant.core import HassJob, callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_sunrise, async_track_sunset
# mypy: allow-untyped-defs, no-check-untyped-defs
TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
2019-07-31 19:25:30 +00:00
{
vol.Required(CONF_PLATFORM): "sun",
vol.Required(CONF_EVENT): cv.sun_event,
vol.Required(CONF_OFFSET, default=timedelta(0)): cv.time_period,
}
)
2015-09-15 07:02:54 +00:00
async def async_attach_trigger(hass, config, action, automation_info):
"""Listen for events based on configuration."""
trigger_data = automation_info["trigger_data"]
event = config.get(CONF_EVENT)
offset = config.get(CONF_OFFSET)
description = event
if offset:
description = f"{description} with offset"
job = HassJob(action)
2015-09-15 07:02:54 +00:00
@callback
def call_action():
"""Call action with right context."""
hass.async_run_hass_job(
job,
{
"trigger": {
**trigger_data,
"platform": "sun",
"event": event,
"offset": offset,
"description": description,
}
},
2019-07-31 19:25:30 +00:00
)
2016-05-03 05:05:09 +00:00
if event == SUN_EVENT_SUNRISE:
2016-10-01 08:22:13 +00:00
return async_track_sunrise(hass, call_action, offset)
return async_track_sunset(hass, call_action, offset)