Add script logic into helper.

This commit is contained in:
Paulus Schoutsen committed 2016-04-21 21:06:05 -04:00
1 parent 4e568f8b99
commit f76d545a08
9 files changed
+219 -238

No files matched your search

+60 -21
View File
@@ -6,7 +6,8 @@ import voluptuous as vol
from homeassistant.loader import get_platform
from homeassistant.const import (
CONF_PLATFORM, CONF_SCAN_INTERVAL, TEMP_CELSIUS, TEMP_FAHRENHEIT)
CONF_PLATFORM, CONF_SCAN_INTERVAL, TEMP_CELSIUS, TEMP_FAHRENHEIT,
CONF_ALIAS)
from homeassistant.helpers.entity import valid_entity_id
import homeassistant.util.dt as dt_util
from homeassistant.util import slugify
@@ -23,6 +24,23 @@ longitude = vol.All(vol.Coerce(float), vol.Range(min=-180, max=180),
msg='invalid longitude')
# Adapted from:
# https://github.com/alecthomas/voluptuous/issues/115#issuecomment-144464666
def has_at_least_one_key(*keys):
"""Validator that at least one key exists."""
def validate(obj):
"""Test keys exist in dict."""
if not isinstance(obj, dict):
raise vol.Invalid('expected dictionary')
for k in obj.keys():
if k in keys:
return obj
raise vol.Invalid('must contain one of {}.'.format(', '.join(keys)))
return validate
def boolean(value):
"""Validate and coerce a boolean value."""
if isinstance(value, str):
@@ -72,10 +90,24 @@ def icon(value):
raise vol.Invalid('Icons should start with prefix "mdi:"')
def time_offset(value):
time_period_dict = vol.All(
dict, vol.Schema({
'days': vol.Coerce(int),
'hours': vol.Coerce(int),
'minutes': vol.Coerce(int),
'seconds': vol.Coerce(int),
'milliseconds': vol.Coerce(int),
}),
has_at_least_one_key('days', 'hours', 'minutes',
'seconds', 'milliseconds'),
lambda value: timedelta(**value))
def time_period_str(value):
"""Validate and transform time offset."""
if not isinstance(value, str):
raise vol.Invalid('offset should be a string')
raise vol.Invalid(
'offset {} should be format HH:MM or HH:MM:SS'.format(value))
negative_offset = False
if value.startswith('-'):
@@ -107,6 +139,9 @@ def time_offset(value):
return offset
time_period = vol.Any(time_period_str, timedelta, time_period_dict)
def match_all(value):
"""Validator that matches all values."""
return value
@@ -125,6 +160,13 @@ def platform_validator(domain):
return validator
def positive_timedelta(value):
"""Validate timedelta is positive."""
if value < timedelta(0):
raise vol.Invalid('Time period should be positive')
return value
def service(value):
"""Validate service."""
# Services use same format as entities so we can use same helper.
@@ -200,23 +242,6 @@ def key_dependency(key, dependency):
return validator
# Adapted from:
# https://github.com/alecthomas/voluptuous/issues/115#issuecomment-144464666
def has_at_least_one_key(*keys):
"""Validator that at least one key exists."""
def validate(obj):
"""Test keys exist in dict."""
if not isinstance(obj, dict):
raise vol.Invalid('expected dictionary')
for k in obj.keys():
if k in keys:
return obj
raise vol.Invalid('must contain one of {}.'.format(', '.join(keys)))
return validate
# Schemas
PLATFORM_SCHEMA = vol.Schema({
@@ -225,14 +250,28 @@ PLATFORM_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
EVENT_SCHEMA = vol.Schema({
vol.Optional(CONF_ALIAS): string,
vol.Required('event'): string,
'event_data': dict
vol.Optional('event_data'): dict,
})
SERVICE_SCHEMA = vol.All(vol.Schema({
vol.Optional(CONF_ALIAS): string,
vol.Exclusive('service', 'service name'): service,
vol.Exclusive('service_template', 'service name'): template,
vol.Optional('data'): dict,
vol.Optional('data_template'): {match_all: template},
vol.Optional('entity_id'): entity_ids,
}), has_at_least_one_key('service', 'service_template'))
# ----- SCRIPT
_DELAY_SCHEMA = vol.Schema({
vol.Optional(CONF_ALIAS): string,
vol.Required("delay"): vol.All(time_period, positive_timedelta)
})
SCRIPT_SCHEMA = vol.All(
ensure_list,
[vol.Any(SERVICE_SCHEMA, _DELAY_SCHEMA, EVENT_SCHEMA)],
)
+125
View File
@@ -0,0 +1,125 @@
"""Helpers to execute scripts."""
import logging
import threading
from itertools import islice
import homeassistant.util.dt as date_util
from homeassistant.const import EVENT_TIME_CHANGED
from homeassistant.helpers.event import track_point_in_utc_time
from homeassistant.helpers import service
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_ALIAS = "alias"
CONF_SERVICE = "service"
CONF_SERVICE_DATA = "data"
CONF_SEQUENCE = "sequence"
CONF_EVENT = "event"
CONF_EVENT_DATA = "event_data"
CONF_DELAY = "delay"
def call_from_config(hass, config):
"""Call a script based on a config entry."""
Script(hass, config).run()
class Script():
"""Representation of a script."""
# pylint: disable=too-many-instance-attributes
def __init__(self, hass, sequence, name=None, change_listener=None):
"""Initialize the script."""
self.hass = hass
self.sequence = cv.SCRIPT_SCHEMA(sequence)
self.name = name
self._change_listener = change_listener
self._cur = -1
self.last_action = None
self.can_cancel = any(CONF_DELAY in action for action
in self.sequence)
self._lock = threading.Lock()
self._delay_listener = None
@property
def is_running(self):
"""Return true if script is on."""
return self._cur != -1
def run(self):
"""Run script."""
with self._lock:
if self._cur == -1:
self._log('Running script')
self._cur = 0
# Unregister callback if we were in a delay but turn on is called
# again. In that case we just continue execution.
self._remove_listener()
for cur, action in islice(enumerate(self.sequence), self._cur,
None):
if CONF_DELAY in action:
# Call ourselves in the future to continue work
def script_delay(now):
"""Called after delay is done."""
self._delay_listener = None
self.run()
self._delay_listener = track_point_in_utc_time(
self.hass, script_delay,
date_util.utcnow() + action[CONF_DELAY])
self._cur = cur + 1
if self._change_listener:
self._change_listener()
return
elif service.validate_service_call(action) is None:
self._call_service(action)
elif CONF_EVENT in action:
self._fire_event(action)
self._cur = -1
self.last_action = None
if self._change_listener:
self._change_listener()
def stop(self):
"""Stop running script."""
with self._lock:
if self._cur == -1:
return
self._cur = -1
self._remove_listener()
if self._change_listener:
self._change_listener()
def _call_service(self, action):
"""Call the service specified in the action."""
self.last_action = action.get(CONF_ALIAS, 'call service')
self._log("Executing step %s", self.last_action)
service.call_from_config(self.hass, action, True)
def _fire_event(self, action):
"""Fire an event."""
self.last_action = action.get(CONF_ALIAS, action[CONF_EVENT])
self._log("Executing step %s", self.last_action)
self.hass.bus.fire(action[CONF_EVENT], action.get(CONF_EVENT_DATA))
def _remove_listener(self):
"""Remove point in time listener, if any."""
if self._delay_listener:
self.hass.bus.remove_listener(EVENT_TIME_CHANGED,
self._delay_listener)
self._delay_listener = None
def _log(self, msg, *substitutes):
"""Logger helper."""
if self.name is not None:
msg = "Script {}: {}".format(self.name, msg, *substitutes)
_LOGGER.info(msg)