core/homeassistant/components/automation/state.py

58 lines
1.5 KiB
Python
Raw Normal View History

2015-01-16 07:32:27 +00:00
"""
homeassistant.components.automation.state
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Offers state listening automation rules.
"""
import logging
2015-08-04 16:13:35 +00:00
from homeassistant.helpers.event import track_state_change
2015-01-16 07:32:27 +00:00
from homeassistant.const import MATCH_ALL
2015-09-15 05:05:40 +00:00
CONF_ENTITY_ID = "entity_id"
CONF_FROM = "from"
CONF_TO = "to"
2015-09-14 05:25:42 +00:00
CONF_STATE = "state"
2015-01-16 07:32:27 +00:00
2015-09-14 05:25:42 +00:00
def trigger(hass, config, action):
2015-01-16 07:32:27 +00:00
""" Listen for state changes based on `config`. """
entity_id = config.get(CONF_ENTITY_ID)
if entity_id is None:
logging.getLogger(__name__).error(
2015-09-14 05:25:42 +00:00
"Missing trigger configuration key %s", CONF_ENTITY_ID)
2015-01-16 07:32:27 +00:00
return False
from_state = config.get(CONF_FROM, MATCH_ALL)
to_state = config.get(CONF_TO, MATCH_ALL)
def state_automation_listener(entity, from_s, to_s):
""" Listens for state changes and calls action. """
action()
2015-08-04 16:13:35 +00:00
track_state_change(
hass, entity_id, state_automation_listener, from_state, to_state)
2015-01-16 07:32:27 +00:00
return True
2015-09-14 05:25:42 +00:00
def if_action(hass, config, action):
""" Wraps action method with state based condition. """
2015-09-15 05:05:40 +00:00
entity_id = config.get(CONF_ENTITY_ID)
2015-09-14 05:25:42 +00:00
state = config.get(CONF_STATE)
if entity_id is None or state is None:
logging.getLogger(__name__).error(
2015-09-15 01:22:49 +00:00
"Missing if-condition configuration key %s or %s",
CONF_IF_ENTITY_ID, CONF_STATE)
2015-09-14 05:25:42 +00:00
return action
def state_if():
""" Execute action if state matches. """
if hass.states.is_state(entity_id, state):
action()
return state_if