2015-12-16 10:52:33 -07:00
|
|
|
"""
|
2016-03-07 20:20:07 +01:00
|
|
|
Offer template automation rules.
|
2015-12-16 10:52:33 -07: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 12:18:58 -07:00
|
|
|
import voluptuous as vol
|
|
|
|
|
|
|
|
from homeassistant.const import (
|
2016-04-21 13:59:42 -07:00
|
|
|
CONF_VALUE_TEMPLATE, CONF_PLATFORM, MATCH_ALL)
|
2016-09-25 13:33:01 -07:00
|
|
|
from homeassistant.helpers import condition, template
|
2016-04-21 13:59:42 -07:00
|
|
|
from homeassistant.helpers.event import track_state_change
|
2016-04-04 12:18:58 -07:00
|
|
|
import homeassistant.helpers.config_validation as cv
|
|
|
|
|
2015-12-16 10:52:33 -07:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2016-04-04 12:18:58 -07:00
|
|
|
TRIGGER_SCHEMA = IF_ACTION_SCHEMA = vol.Schema({
|
|
|
|
vol.Required(CONF_PLATFORM): 'template',
|
|
|
|
vol.Required(CONF_VALUE_TEMPLATE): cv.template,
|
|
|
|
})
|
|
|
|
|
2015-12-16 10:52:33 -07:00
|
|
|
|
|
|
|
def trigger(hass, config, action):
|
2016-03-07 17:14:55 +01:00
|
|
|
"""Listen for state changes based on configuration."""
|
2016-09-25 13:33:01 -07:00
|
|
|
value_template = template.compile_template(
|
|
|
|
hass, config.get(CONF_VALUE_TEMPLATE))
|
2015-12-16 10:52:33 -07:00
|
|
|
|
2015-12-16 15:07:14 -07:00
|
|
|
# Local variable to keep track of if the action has already been triggered
|
|
|
|
already_triggered = False
|
|
|
|
|
2016-04-21 13:59:42 -07:00
|
|
|
def state_changed_listener(entity_id, from_s, to_s):
|
2016-03-07 20:20:07 +01:00
|
|
|
"""Listen for state changes and calls action."""
|
2015-12-16 15:07:14 -07:00
|
|
|
nonlocal already_triggered
|
2016-04-28 12:03:57 +02:00
|
|
|
template_result = condition.template(hass, value_template)
|
2015-12-16 10:52:33 -07:00
|
|
|
|
|
|
|
# Check to see if template returns true
|
2015-12-16 15:07:14 -07:00
|
|
|
if template_result and not already_triggered:
|
|
|
|
already_triggered = True
|
2016-04-21 13:59:42 -07:00
|
|
|
action({
|
|
|
|
'trigger': {
|
|
|
|
'platform': 'template',
|
|
|
|
'entity_id': entity_id,
|
|
|
|
'from_state': from_s,
|
|
|
|
'to_state': to_s,
|
|
|
|
},
|
|
|
|
})
|
2015-12-16 15:07:14 -07:00
|
|
|
elif not template_result:
|
|
|
|
already_triggered = False
|
2015-12-16 10:52:33 -07:00
|
|
|
|
2016-08-25 23:25:57 -07:00
|
|
|
return track_state_change(hass, MATCH_ALL, state_changed_listener)
|