diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py index 65a9fe9ebd8..1dc0cc26b5c 100644 --- a/homeassistant/helpers/config_validation.py +++ b/homeassistant/helpers/config_validation.py @@ -376,7 +376,9 @@ CONDITION_SCHEMA = vol.Any( _SCRIPT_DELAY_SCHEMA = vol.Schema({ vol.Optional(CONF_ALIAS): string, - vol.Required("delay"): vol.All(time_period, positive_timedelta) + vol.Required("delay"): vol.Any( + vol.All(time_period, positive_timedelta), + template) }) SCRIPT_SCHEMA = vol.All( diff --git a/homeassistant/helpers/script.py b/homeassistant/helpers/script.py index 48a4bffc6a3..bc1382ef982 100644 --- a/homeassistant/helpers/script.py +++ b/homeassistant/helpers/script.py @@ -3,10 +3,12 @@ import logging import threading from itertools import islice +import voluptuous as vol + import homeassistant.util.dt as date_util from homeassistant.const import EVENT_TIME_CHANGED, CONF_CONDITION from homeassistant.helpers.event import track_point_in_utc_time -from homeassistant.helpers import service, condition +from homeassistant.helpers import service, condition, template import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -68,9 +70,17 @@ class Script(): self._delay_listener = None self.run(variables) + delay = action[CONF_DELAY] + + if isinstance(delay, str): + delay = vol.All( + cv.time_period, + cv.positive_timedelta)( + template.render(self.hass, delay)) + self._delay_listener = track_point_in_utc_time( self.hass, script_delay, - date_util.utcnow() + action[CONF_DELAY]) + date_util.utcnow() + delay) self._cur = cur + 1 if self._change_listener: self._change_listener() diff --git a/tests/helpers/test_script.py b/tests/helpers/test_script.py index 3fcb144ac1f..ba7255a8fe4 100644 --- a/tests/helpers/test_script.py +++ b/tests/helpers/test_script.py @@ -141,6 +141,38 @@ class TestScriptHelper(unittest.TestCase): assert not script_obj.is_running assert len(events) == 2 + def test_delay_template(self): + """Test the delay as a template.""" + event = 'test_evnt' + events = [] + + def record_event(event): + """Add recorded event to set.""" + events.append(event) + + self.hass.bus.listen(event, record_event) + + script_obj = script.Script(self.hass, [ + {'event': event}, + {'delay': '00:00:{{ 5 }}'}, + {'event': event}]) + + script_obj.run() + + self.hass.pool.block_till_done() + + assert script_obj.is_running + assert script_obj.can_cancel + assert script_obj.last_action == event + assert len(events) == 1 + + future = dt_util.utcnow() + timedelta(seconds=5) + fire_time_changed(self.hass, future) + self.hass.pool.block_till_done() + + assert not script_obj.is_running + assert len(events) == 2 + def test_cancel_while_delay(self): """Test the cancelling while the delay is present.""" event = 'test_event'