core/homeassistant/components/automation/template.py

68 lines
2.1 KiB
Python
Raw Normal View History

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
from homeassistant.const import CONF_VALUE_TEMPLATE, EVENT_STATE_CHANGED
2015-12-16 17:52:33 +00:00
from homeassistant.exceptions import TemplateError
2016-02-23 20:06:50 +00:00
from homeassistant.helpers import template
2015-12-16 17:52:33 +00:00
_LOGGER = logging.getLogger(__name__)
def trigger(hass, config, action):
2016-03-07 16:14:55 +00:00
"""Listen for state changes based on configuration."""
2015-12-16 17:52:33 +00:00
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is None:
_LOGGER.error("Missing configuration key %s", CONF_VALUE_TEMPLATE)
return False
2015-12-16 22:07:14 +00:00
# Local variable to keep track of if the action has already been triggered
already_triggered = False
def event_listener(event):
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
template_result = _check_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
2015-12-16 17:52:33 +00:00
action()
2015-12-16 22:07:14 +00:00
elif not template_result:
already_triggered = False
2015-12-16 17:52:33 +00:00
hass.bus.listen(EVENT_STATE_CHANGED, event_listener)
2015-12-16 17:52:33 +00:00
return True
def if_action(hass, config):
2016-03-07 19:20:07 +00:00
"""Wrap action method with state based condition."""
2015-12-16 17:52:33 +00:00
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is None:
_LOGGER.error("Missing configuration key %s", CONF_VALUE_TEMPLATE)
return False
return lambda: _check_template(hass, value_template)
def _check_template(hass, value_template):
2016-03-07 19:20:07 +00:00
"""Check if result of template is true."""
2015-12-16 17:52:33 +00:00
try:
value = template.render(hass, value_template, {})
2016-03-14 10:10:38 +00:00
except TemplateError as ex:
if ex.args and ex.args[0].startswith(
"UndefinedError: 'None' has no attribute"):
# Common during HA startup - so just a warning
_LOGGER.warning(ex)
else:
_LOGGER.error(ex)
2015-12-16 17:52:33 +00:00
return False
return value.lower() == 'true'