2015-12-16 17:52:33 +00:00
|
|
|
"""
|
2016-03-07 19:20:07 +00:00
|
|
|
Offer template automation rules.
|
2015-12-16 17:52:33 +00:00
|
|
|
|
|
|
|
For more details about this automation rule, please refer to the documentation
|
|
|
|
at https://home-assistant.io/components/automation/#template-trigger
|
|
|
|
"""
|
|
|
|
import logging
|
|
|
|
|
2016-04-04 19:18:58 +00:00
|
|
|
import voluptuous as vol
|
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
from homeassistant.core import callback
|
2016-09-28 04:29:55 +00:00
|
|
|
from homeassistant.const import CONF_VALUE_TEMPLATE, CONF_PLATFORM
|
|
|
|
from homeassistant.helpers import condition
|
2016-10-01 08:22:13 +00:00
|
|
|
from homeassistant.helpers.event import async_track_state_change
|
2016-04-04 19:18:58 +00:00
|
|
|
import homeassistant.helpers.config_validation as cv
|
|
|
|
|
2015-12-16 17:52:33 +00:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2016-04-04 19:18:58 +00:00
|
|
|
TRIGGER_SCHEMA = IF_ACTION_SCHEMA = vol.Schema({
|
|
|
|
vol.Required(CONF_PLATFORM): 'template',
|
|
|
|
vol.Required(CONF_VALUE_TEMPLATE): cv.template,
|
|
|
|
})
|
|
|
|
|
2015-12-16 17:52:33 +00:00
|
|
|
|
2016-10-01 08:22:13 +00:00
|
|
|
def async_trigger(hass, config, action):
|
2016-03-07 16:14:55 +00:00
|
|
|
"""Listen for state changes based on configuration."""
|
2016-09-28 04:29:55 +00:00
|
|
|
value_template = config.get(CONF_VALUE_TEMPLATE)
|
|
|
|
value_template.hass = hass
|
2015-12-16 17:52:33 +00:00
|
|
|
|
2015-12-16 22:07:14 +00:00
|
|
|
# Local variable to keep track of if the action has already been triggered
|
|
|
|
already_triggered = False
|
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
@callback
|
2016-04-21 20:59:42 +00:00
|
|
|
def state_changed_listener(entity_id, from_s, to_s):
|
2016-03-07 19:20:07 +00:00
|
|
|
"""Listen for state changes and calls action."""
|
2015-12-16 22:07:14 +00:00
|
|
|
nonlocal already_triggered
|
2016-09-28 04:29:55 +00:00
|
|
|
template_result = condition.async_template(hass, value_template)
|
2015-12-16 17:52:33 +00:00
|
|
|
|
|
|
|
# Check to see if template returns true
|
2015-12-16 22:07:14 +00:00
|
|
|
if template_result and not already_triggered:
|
|
|
|
already_triggered = True
|
2016-10-05 03:44:32 +00:00
|
|
|
hass.async_run_job(action, {
|
2016-04-21 20:59:42 +00:00
|
|
|
'trigger': {
|
|
|
|
'platform': 'template',
|
|
|
|
'entity_id': entity_id,
|
|
|
|
'from_state': from_s,
|
|
|
|
'to_state': to_s,
|
|
|
|
},
|
|
|
|
})
|
2015-12-16 22:07:14 +00:00
|
|
|
elif not template_result:
|
|
|
|
already_triggered = False
|
2015-12-16 17:52:33 +00:00
|
|
|
|
2016-10-01 08:22:13 +00:00
|
|
|
return async_track_state_change(hass, value_template.extract_entities(),
|
|
|
|
state_changed_listener)
|