2019-02-13 21:21:14 +01:00
|
|
|
"""Offer sun based automation rules."""
|
2015-09-15 00:02:54 -07:00
|
|
|
from datetime import timedelta
|
2016-04-04 12:18:58 -07:00
|
|
|
|
|
|
|
import voluptuous as vol
|
2015-09-15 00:02:54 -07:00
|
|
|
|
2016-05-02 22:05:09 -07:00
|
|
|
from homeassistant.const import (
|
2019-07-31 12:25:30 -07:00
|
|
|
CONF_EVENT,
|
|
|
|
CONF_OFFSET,
|
|
|
|
CONF_PLATFORM,
|
|
|
|
SUN_EVENT_SUNRISE,
|
|
|
|
)
|
2020-10-08 02:44:34 -05:00
|
|
|
from homeassistant.core import HassJob, callback
|
2016-04-04 12:18:58 -07:00
|
|
|
import homeassistant.helpers.config_validation as cv
|
2019-12-08 17:29:39 +01:00
|
|
|
from homeassistant.helpers.event import async_track_sunrise, async_track_sunset
|
2019-08-12 06:38:18 +03:00
|
|
|
|
|
|
|
# mypy: allow-untyped-defs, no-check-untyped-defs
|
|
|
|
|
2021-06-11 09:51:12 +02:00
|
|
|
TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
|
2019-07-31 12:25:30 -07: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 00:02:54 -07:00
|
|
|
|
|
|
|
|
2019-09-24 14:57:05 -07:00
|
|
|
async def async_attach_trigger(hass, config, action, automation_info):
|
2016-04-04 12:18:58 -07:00
|
|
|
"""Listen for events based on configuration."""
|
2021-09-04 03:25:51 +03:00
|
|
|
trigger_data = automation_info["trigger_data"]
|
2016-04-04 12:18:58 -07:00
|
|
|
event = config.get(CONF_EVENT)
|
|
|
|
offset = config.get(CONF_OFFSET)
|
2020-08-28 10:02:12 -05:00
|
|
|
description = event
|
|
|
|
if offset:
|
|
|
|
description = f"{description} with offset"
|
2020-10-08 02:44:34 -05:00
|
|
|
job = HassJob(action)
|
2015-09-15 00:02:54 -07:00
|
|
|
|
2016-10-04 20:44:32 -07:00
|
|
|
@callback
|
2016-04-21 13:59:42 -07:00
|
|
|
def call_action():
|
|
|
|
"""Call action with right context."""
|
2020-10-08 02:44:34 -05:00
|
|
|
hass.async_run_hass_job(
|
|
|
|
job,
|
2020-08-28 10:02:12 -05:00
|
|
|
{
|
|
|
|
"trigger": {
|
2021-06-14 17:09:20 +02:00
|
|
|
**trigger_data,
|
2020-08-28 10:02:12 -05:00
|
|
|
"platform": "sun",
|
|
|
|
"event": event,
|
|
|
|
"offset": offset,
|
|
|
|
"description": description,
|
|
|
|
}
|
|
|
|
},
|
2019-07-31 12:25:30 -07:00
|
|
|
)
|
2016-04-21 13:59:42 -07:00
|
|
|
|
2016-05-02 22:05:09 -07:00
|
|
|
if event == SUN_EVENT_SUNRISE:
|
2016-10-01 01:22:13 -07:00
|
|
|
return async_track_sunrise(hass, call_action, offset)
|
2017-07-05 20:02:16 -07:00
|
|
|
return async_track_sunset(hass, call_action, offset)
|