2019-02-13 21:21:14 +01:00
|
|
|
"""Offer event listening automation rules."""
|
2015-02-23 19:23:25 -06:00
|
|
|
import logging
|
|
|
|
|
2016-04-28 12:03:57 +02:00
|
|
|
import voluptuous as vol
|
|
|
|
|
2017-05-06 23:52:39 -07:00
|
|
|
from homeassistant.const import CONF_PLATFORM
|
2019-12-08 17:29:39 +01:00
|
|
|
from homeassistant.core import callback
|
2016-04-28 12:03:57 +02:00
|
|
|
from homeassistant.helpers import config_validation as cv
|
|
|
|
|
2019-08-12 06:38:18 +03:00
|
|
|
# mypy: allow-untyped-defs
|
|
|
|
|
2019-07-31 12:25:30 -07:00
|
|
|
CONF_EVENT_TYPE = "event_type"
|
|
|
|
CONF_EVENT_DATA = "event_data"
|
2015-02-23 19:23:25 -06:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2019-07-31 12:25:30 -07:00
|
|
|
TRIGGER_SCHEMA = vol.Schema(
|
|
|
|
{
|
|
|
|
vol.Required(CONF_PLATFORM): "event",
|
|
|
|
vol.Required(CONF_EVENT_TYPE): cv.string,
|
|
|
|
vol.Optional(CONF_EVENT_DATA): dict,
|
|
|
|
}
|
|
|
|
)
|
2016-04-28 12:03:57 +02:00
|
|
|
|
2015-02-23 19:23:25 -06:00
|
|
|
|
2019-09-24 14:57:05 -07:00
|
|
|
async def async_attach_trigger(
|
|
|
|
hass, config, action, automation_info, *, platform_type="event"
|
|
|
|
):
|
2016-03-07 17:14:55 +01:00
|
|
|
"""Listen for events based on configuration."""
|
2015-02-23 19:23:25 -06:00
|
|
|
event_type = config.get(CONF_EVENT_TYPE)
|
2019-07-31 12:25:30 -07:00
|
|
|
event_data_schema = (
|
|
|
|
vol.Schema(config.get(CONF_EVENT_DATA), extra=vol.ALLOW_EXTRA)
|
|
|
|
if config.get(CONF_EVENT_DATA)
|
|
|
|
else None
|
|
|
|
)
|
2015-02-23 19:23:25 -06:00
|
|
|
|
2016-10-04 20:44:32 -07:00
|
|
|
@callback
|
2015-02-23 19:23:25 -06:00
|
|
|
def handle_event(event):
|
2016-03-07 20:20:07 +01:00
|
|
|
"""Listen for events and calls the action when data matches."""
|
2017-10-22 20:20:38 -04:00
|
|
|
if event_data_schema:
|
|
|
|
# Check that the event data matches the configured
|
|
|
|
# schema if one was provided
|
|
|
|
try:
|
|
|
|
event_data_schema(event.data)
|
|
|
|
except vol.Invalid:
|
|
|
|
# If event data doesn't match requested schema, skip event
|
|
|
|
return
|
2017-10-07 16:13:32 -04:00
|
|
|
|
2019-07-31 12:25:30 -07:00
|
|
|
hass.async_run_job(
|
|
|
|
action(
|
2019-09-24 14:57:05 -07:00
|
|
|
{"trigger": {"platform": platform_type, "event": event}},
|
2019-07-31 12:25:30 -07:00
|
|
|
context=event.context,
|
|
|
|
)
|
|
|
|
)
|
2015-02-23 19:23:25 -06:00
|
|
|
|
2016-10-01 01:22:13 -07:00
|
|
|
return hass.bus.async_listen(event_type, handle_event)
|