core/homeassistant/components/automation/numeric_state.py

70 lines
2.3 KiB
Python
Raw Normal View History

"""
2016-03-07 19:20:07 +00:00
Offer numeric state listening automation rules.
2015-10-13 19:07:53 +00:00
For more details about this automation rule, please refer to the documentation
2015-11-09 12:12:18 +00:00
at https://home-assistant.io/components/automation/#numeric-state-trigger
"""
import asyncio
import logging
import voluptuous as vol
from homeassistant.const import (
CONF_VALUE_TEMPLATE, CONF_PLATFORM, CONF_ENTITY_ID,
CONF_BELOW, CONF_ABOVE)
2016-10-01 08:22:13 +00:00
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers import condition, config_validation as cv
TRIGGER_SCHEMA = vol.All(vol.Schema({
vol.Required(CONF_PLATFORM): 'numeric_state',
vol.Required(CONF_ENTITY_ID): cv.entity_ids,
CONF_BELOW: vol.Coerce(float),
CONF_ABOVE: vol.Coerce(float),
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
}), cv.has_at_least_one_key(CONF_BELOW, CONF_ABOVE))
_LOGGER = logging.getLogger(__name__)
2015-09-13 11:05:36 +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."""
entity_id = config.get(CONF_ENTITY_ID)
below = config.get(CONF_BELOW)
above = config.get(CONF_ABOVE)
2015-12-14 18:08:31 +00:00
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
value_template.hass = hass
@asyncio.coroutine
def state_automation_listener(entity, from_s, to_s):
2016-03-07 19:20:07 +00:00
"""Listen for state changes and calls action."""
if to_s is None:
return
variables = {
'trigger': {
'platform': 'numeric_state',
'entity_id': entity,
'below': below,
'above': above,
}
}
# If new one doesn't match, nothing to do
if not condition.async_numeric_state(
hass, to_s, below, above, value_template, variables):
return
# Only match if old didn't exist or existed but didn't match
# Written as: skip if old one did exist and matched
if from_s is not None and condition.async_numeric_state(
hass, from_s, below, above, value_template, variables):
return
variables['trigger']['from_state'] = from_s
variables['trigger']['to_state'] = to_s
hass.async_add_job(action, variables)
2016-10-01 08:22:13 +00:00
return async_track_state_change(hass, entity_id, state_automation_listener)