-
-
Notifications
You must be signed in to change notification settings - Fork 31k
/
script.py
1800 lines (1539 loc) · 63.6 KB
/
script.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Helpers to execute scripts."""
from __future__ import annotations
import asyncio
from collections.abc import Callable, Mapping, Sequence
from contextlib import asynccontextmanager, suppress
from contextvars import ContextVar
from copy import copy
from datetime import datetime, timedelta
from functools import partial
import itertools
import logging
from types import MappingProxyType
from typing import Any, TypedDict, TypeVar, cast
import async_timeout
import voluptuous as vol
from homeassistant import exceptions
from homeassistant.components import scene
from homeassistant.components.device_automation import action as device_action
from homeassistant.components.logger import LOGSEVERITY
from homeassistant.const import (
ATTR_AREA_ID,
ATTR_DEVICE_ID,
ATTR_ENTITY_ID,
CONF_ALIAS,
CONF_CHOOSE,
CONF_CONDITION,
CONF_CONDITIONS,
CONF_CONTINUE_ON_ERROR,
CONF_CONTINUE_ON_TIMEOUT,
CONF_COUNT,
CONF_DEFAULT,
CONF_DELAY,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ELSE,
CONF_ENABLED,
CONF_ERROR,
CONF_EVENT,
CONF_EVENT_DATA,
CONF_EVENT_DATA_TEMPLATE,
CONF_FOR_EACH,
CONF_IF,
CONF_MODE,
CONF_PARALLEL,
CONF_REPEAT,
CONF_RESPONSE_VARIABLE,
CONF_SCENE,
CONF_SEQUENCE,
CONF_SERVICE,
CONF_SERVICE_DATA,
CONF_SERVICE_DATA_TEMPLATE,
CONF_STOP,
CONF_TARGET,
CONF_THEN,
CONF_TIMEOUT,
CONF_UNTIL,
CONF_VARIABLES,
CONF_WAIT_FOR_TRIGGER,
CONF_WAIT_TEMPLATE,
CONF_WHILE,
EVENT_HOMEASSISTANT_STOP,
SERVICE_TURN_ON,
)
from homeassistant.core import (
Context,
Event,
HassJob,
HomeAssistant,
callback,
)
from homeassistant.util import slugify
from homeassistant.util.dt import utcnow
from . import condition, config_validation as cv, service, template
from .condition import ConditionCheckerType, trace_condition_function
from .dispatcher import async_dispatcher_connect, async_dispatcher_send
from .event import async_call_later, async_track_template
from .script_variables import ScriptVariables
from .trace import (
TraceElement,
async_trace_path,
script_execution_set,
trace_append_element,
trace_id_get,
trace_path,
trace_path_get,
trace_path_stack_cv,
trace_set_result,
trace_stack_cv,
trace_stack_pop,
trace_stack_push,
trace_stack_top,
trace_update_result,
)
from .trigger import async_initialize_triggers, async_validate_trigger_config
from .typing import ConfigType
# mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs
_T = TypeVar("_T")
SCRIPT_MODE_PARALLEL = "parallel"
SCRIPT_MODE_QUEUED = "queued"
SCRIPT_MODE_RESTART = "restart"
SCRIPT_MODE_SINGLE = "single"
SCRIPT_MODE_CHOICES = [
SCRIPT_MODE_PARALLEL,
SCRIPT_MODE_QUEUED,
SCRIPT_MODE_RESTART,
SCRIPT_MODE_SINGLE,
]
DEFAULT_SCRIPT_MODE = SCRIPT_MODE_SINGLE
CONF_MAX = "max"
DEFAULT_MAX = 10
CONF_MAX_EXCEEDED = "max_exceeded"
_MAX_EXCEEDED_CHOICES = list(LOGSEVERITY) + ["SILENT"]
DEFAULT_MAX_EXCEEDED = "WARNING"
ATTR_CUR = "current"
ATTR_MAX = "max"
DATA_SCRIPTS = "helpers.script"
DATA_SCRIPT_BREAKPOINTS = "helpers.script_breakpoints"
DATA_NEW_SCRIPT_RUNS_NOT_ALLOWED = "helpers.script_not_allowed"
RUN_ID_ANY = "*"
NODE_ANY = "*"
_LOGGER = logging.getLogger(__name__)
_LOG_EXCEPTION = logging.ERROR + 1
_TIMEOUT_MSG = "Timeout reached, abort script."
_SHUTDOWN_MAX_WAIT = 60
ACTION_TRACE_NODE_MAX_LEN = 20 # Max length of a trace node for repeated actions
SCRIPT_BREAKPOINT_HIT = "script_breakpoint_hit"
SCRIPT_DEBUG_CONTINUE_STOP = "script_debug_continue_stop_{}_{}"
SCRIPT_DEBUG_CONTINUE_ALL = "script_debug_continue_all"
script_stack_cv: ContextVar[list[int] | None] = ContextVar("script_stack", default=None)
def action_trace_append(variables, path):
"""Append a TraceElement to trace[path]."""
trace_element = TraceElement(variables, path)
trace_append_element(trace_element, ACTION_TRACE_NODE_MAX_LEN)
return trace_element
@asynccontextmanager
async def trace_action(hass, script_run, stop, variables):
"""Trace action execution."""
path = trace_path_get()
trace_element = action_trace_append(variables, path)
trace_stack_push(trace_stack_cv, trace_element)
trace_id = trace_id_get()
if trace_id:
key = trace_id[0]
run_id = trace_id[1]
breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS]
if key in breakpoints and (
(
run_id in breakpoints[key]
and (
path in breakpoints[key][run_id]
or NODE_ANY in breakpoints[key][run_id]
)
)
or (
RUN_ID_ANY in breakpoints[key]
and (
path in breakpoints[key][RUN_ID_ANY]
or NODE_ANY in breakpoints[key][RUN_ID_ANY]
)
)
):
async_dispatcher_send(hass, SCRIPT_BREAKPOINT_HIT, key, run_id, path)
done = asyncio.Event()
@callback
def async_continue_stop(command=None):
if command == "stop":
stop.set()
done.set()
signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
remove_signal1 = async_dispatcher_connect(hass, signal, async_continue_stop)
remove_signal2 = async_dispatcher_connect(
hass, SCRIPT_DEBUG_CONTINUE_ALL, async_continue_stop
)
tasks = [hass.async_create_task(flag.wait()) for flag in (stop, done)]
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in tasks:
task.cancel()
remove_signal1()
remove_signal2()
try:
yield trace_element
except _AbortScript as ex:
trace_element.set_error(ex.__cause__ or ex)
raise ex
except _ConditionFail as ex:
# Clear errors which may have been set when evaluating the condition
trace_element.set_error(None)
raise ex
except _StopScript as ex:
raise ex
except Exception as ex:
trace_element.set_error(ex)
raise ex
finally:
trace_stack_pop(trace_stack_cv)
def make_script_schema(
schema: Mapping[Any, Any], default_script_mode: str, extra: int = vol.PREVENT_EXTRA
) -> vol.Schema:
"""Make a schema for a component that uses the script helper."""
return vol.Schema(
{
**schema,
vol.Optional(CONF_MODE, default=default_script_mode): vol.In(
SCRIPT_MODE_CHOICES
),
vol.Optional(CONF_MAX, default=DEFAULT_MAX): vol.All(
vol.Coerce(int), vol.Range(min=2)
),
vol.Optional(CONF_MAX_EXCEEDED, default=DEFAULT_MAX_EXCEEDED): vol.All(
vol.Upper, vol.In(_MAX_EXCEEDED_CHOICES)
),
},
extra=extra,
)
STATIC_VALIDATION_ACTION_TYPES = (
cv.SCRIPT_ACTION_CALL_SERVICE,
cv.SCRIPT_ACTION_DELAY,
cv.SCRIPT_ACTION_WAIT_TEMPLATE,
cv.SCRIPT_ACTION_FIRE_EVENT,
cv.SCRIPT_ACTION_ACTIVATE_SCENE,
cv.SCRIPT_ACTION_VARIABLES,
cv.SCRIPT_ACTION_STOP,
)
async def async_validate_actions_config(
hass: HomeAssistant, actions: list[ConfigType]
) -> list[ConfigType]:
"""Validate a list of actions."""
return await asyncio.gather(
*(async_validate_action_config(hass, action) for action in actions)
)
async def async_validate_action_config(
hass: HomeAssistant, config: ConfigType
) -> ConfigType:
"""Validate config."""
action_type = cv.determine_script_action(config)
if action_type in STATIC_VALIDATION_ACTION_TYPES:
pass
elif action_type == cv.SCRIPT_ACTION_DEVICE_AUTOMATION:
config = await device_action.async_validate_action_config(hass, config)
elif action_type == cv.SCRIPT_ACTION_CHECK_CONDITION:
config = await condition.async_validate_condition_config(hass, config)
elif action_type == cv.SCRIPT_ACTION_WAIT_FOR_TRIGGER:
config[CONF_WAIT_FOR_TRIGGER] = await async_validate_trigger_config(
hass, config[CONF_WAIT_FOR_TRIGGER]
)
elif action_type == cv.SCRIPT_ACTION_REPEAT:
if CONF_UNTIL in config[CONF_REPEAT]:
conditions = await condition.async_validate_conditions_config(
hass, config[CONF_REPEAT][CONF_UNTIL]
)
config[CONF_REPEAT][CONF_UNTIL] = conditions
if CONF_WHILE in config[CONF_REPEAT]:
conditions = await condition.async_validate_conditions_config(
hass, config[CONF_REPEAT][CONF_WHILE]
)
config[CONF_REPEAT][CONF_WHILE] = conditions
config[CONF_REPEAT][CONF_SEQUENCE] = await async_validate_actions_config(
hass, config[CONF_REPEAT][CONF_SEQUENCE]
)
elif action_type == cv.SCRIPT_ACTION_CHOOSE:
if CONF_DEFAULT in config:
config[CONF_DEFAULT] = await async_validate_actions_config(
hass, config[CONF_DEFAULT]
)
for choose_conf in config[CONF_CHOOSE]:
conditions = await condition.async_validate_conditions_config(
hass, choose_conf[CONF_CONDITIONS]
)
choose_conf[CONF_CONDITIONS] = conditions
choose_conf[CONF_SEQUENCE] = await async_validate_actions_config(
hass, choose_conf[CONF_SEQUENCE]
)
elif action_type == cv.SCRIPT_ACTION_IF:
config[CONF_IF] = await condition.async_validate_conditions_config(
hass, config[CONF_IF]
)
config[CONF_THEN] = await async_validate_actions_config(hass, config[CONF_THEN])
if CONF_ELSE in config:
config[CONF_ELSE] = await async_validate_actions_config(
hass, config[CONF_ELSE]
)
elif action_type == cv.SCRIPT_ACTION_PARALLEL:
for parallel_conf in config[CONF_PARALLEL]:
parallel_conf[CONF_SEQUENCE] = await async_validate_actions_config(
hass, parallel_conf[CONF_SEQUENCE]
)
else:
raise ValueError(f"No validation for {action_type}")
return config
class _HaltScript(Exception):
"""Throw if script needs to stop executing."""
class _AbortScript(_HaltScript):
"""Throw if script needs to abort because of an unexpected error."""
class _ConditionFail(_HaltScript):
"""Throw if script needs to stop because a condition evaluated to False."""
class _StopScript(_HaltScript):
"""Throw if script needs to stop."""
class _ScriptRun:
"""Manage Script sequence run."""
def __init__(
self,
hass: HomeAssistant,
script: Script,
variables: dict[str, Any],
context: Context | None,
log_exceptions: bool,
) -> None:
self._hass = hass
self._script = script
self._variables = variables
self._context = context
self._log_exceptions = log_exceptions
self._step = -1
self._action: dict[str, Any] | None = None
self._stop = asyncio.Event()
self._stopped = asyncio.Event()
def _changed(self) -> None:
if not self._stop.is_set():
self._script._changed() # pylint: disable=protected-access
async def _async_get_condition(self, config):
# pylint: disable-next=protected-access
return await self._script._async_get_condition(config)
def _log(
self, msg: str, *args: Any, level: int = logging.INFO, **kwargs: Any
) -> None:
self._script._log( # pylint: disable=protected-access
msg, *args, level=level, **kwargs
)
def _step_log(self, default_message, timeout=None):
self._script.last_action = self._action.get(CONF_ALIAS, default_message)
_timeout = (
"" if timeout is None else f" (timeout: {timedelta(seconds=timeout)})"
)
self._log("Executing step %s%s", self._script.last_action, _timeout)
async def async_run(self) -> None:
"""Run script."""
# Push the script to the script execution stack
if (script_stack := script_stack_cv.get()) is None:
script_stack = []
script_stack_cv.set(script_stack)
script_stack.append(id(self._script))
try:
self._log("Running %s", self._script.running_description)
for self._step, self._action in enumerate(self._script.sequence):
if self._stop.is_set():
script_execution_set("cancelled")
break
await self._async_step(log_exceptions=False)
else:
script_execution_set("finished")
except _AbortScript:
script_execution_set("aborted")
# Let the _AbortScript bubble up if this is a sub-script
if not self._script.top_level:
raise
except _ConditionFail:
script_execution_set("aborted")
except _StopScript:
script_execution_set("finished")
# Let the _StopScript bubble up if this is a sub-script
if not self._script.top_level:
raise
except Exception:
script_execution_set("error")
raise
finally:
# Pop the script from the script execution stack
script_stack.pop()
self._finish()
async def _async_step(self, log_exceptions):
continue_on_error = self._action.get(CONF_CONTINUE_ON_ERROR, False)
with trace_path(str(self._step)):
async with trace_action(self._hass, self, self._stop, self._variables):
if self._stop.is_set():
return
action = cv.determine_script_action(self._action)
if not self._action.get(CONF_ENABLED, True):
self._log(
"Skipped disabled step %s", self._action.get(CONF_ALIAS, action)
)
trace_set_result(enabled=False)
return
try:
handler = f"_async_{action}_step"
await getattr(self, handler)()
except Exception as ex: # pylint: disable=broad-except
self._handle_exception(
ex, continue_on_error, self._log_exceptions or log_exceptions
)
def _finish(self) -> None:
self._script._runs.remove(self) # pylint: disable=protected-access
if not self._script.is_running:
self._script.last_action = None
self._changed()
self._stopped.set()
async def async_stop(self) -> None:
"""Stop script run."""
self._stop.set()
await self._stopped.wait()
def _handle_exception(
self, exception: Exception, continue_on_error: bool, log_exceptions: bool
) -> None:
if not isinstance(exception, _HaltScript) and log_exceptions:
self._log_exception(exception)
if not continue_on_error:
raise exception
# An explicit request to stop the script has been raised.
if isinstance(exception, _StopScript):
raise exception
# These are incorrect scripts, and not runtime errors that need to
# be handled and thus cannot be stopped by `continue_on_error`.
if isinstance(
exception,
(
vol.Invalid,
exceptions.TemplateError,
exceptions.ServiceNotFound,
exceptions.InvalidEntityFormatError,
exceptions.NoEntitySpecifiedError,
exceptions.ConditionError,
),
):
raise exception
# Only Home Assistant errors can be ignored.
if not isinstance(exception, exceptions.HomeAssistantError):
raise exception
def _log_exception(self, exception):
action_type = cv.determine_script_action(self._action)
error = str(exception)
level = logging.ERROR
if isinstance(exception, vol.Invalid):
error_desc = "Invalid data"
elif isinstance(exception, exceptions.TemplateError):
error_desc = "Error rendering template"
elif isinstance(exception, exceptions.Unauthorized):
error_desc = "Unauthorized"
elif isinstance(exception, exceptions.ServiceNotFound):
error_desc = "Service not found"
elif isinstance(exception, exceptions.HomeAssistantError):
error_desc = "Error"
else:
error_desc = "Unexpected error"
level = _LOG_EXCEPTION
self._log(
"Error executing script. %s for %s at pos %s: %s",
error_desc,
action_type,
self._step + 1,
error,
level=level,
)
def _get_pos_time_period_template(self, key):
try:
return cv.positive_time_period(
template.render_complex(self._action[key], self._variables)
)
except (exceptions.TemplateError, vol.Invalid) as ex:
self._log(
"Error rendering %s %s template: %s",
self._script.name,
key,
ex,
level=logging.ERROR,
)
raise _AbortScript from ex
async def _async_delay_step(self):
"""Handle delay."""
delay = self._get_pos_time_period_template(CONF_DELAY)
self._step_log(f"delay {delay}")
delay = delay.total_seconds()
self._changed()
trace_set_result(delay=delay, done=False)
try:
async with async_timeout.timeout(delay):
await self._stop.wait()
except asyncio.TimeoutError:
trace_set_result(delay=delay, done=True)
async def _async_wait_template_step(self):
"""Handle a wait template."""
if CONF_TIMEOUT in self._action:
timeout = self._get_pos_time_period_template(CONF_TIMEOUT).total_seconds()
else:
timeout = None
self._step_log("wait template", timeout)
self._variables["wait"] = {"remaining": timeout, "completed": False}
trace_set_result(wait=self._variables["wait"])
wait_template = self._action[CONF_WAIT_TEMPLATE]
wait_template.hass = self._hass
# check if condition already okay
if condition.async_template(self._hass, wait_template, self._variables, False):
self._variables["wait"]["completed"] = True
return
@callback
def async_script_wait(entity_id, from_s, to_s):
"""Handle script after template condition is true."""
wait_var = self._variables["wait"]
if to_context and to_context.deadline:
wait_var["remaining"] = to_context.deadline - self._hass.loop.time()
else:
wait_var["remaining"] = timeout
wait_var["completed"] = True
done.set()
to_context = None
unsub = async_track_template(
self._hass, wait_template, async_script_wait, self._variables
)
self._changed()
done = asyncio.Event()
tasks = [
self._hass.async_create_task(flag.wait()) for flag in (self._stop, done)
]
try:
async with async_timeout.timeout(timeout) as to_context:
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
except asyncio.TimeoutError as ex:
self._variables["wait"]["remaining"] = 0.0
if not self._action.get(CONF_CONTINUE_ON_TIMEOUT, True):
self._log(_TIMEOUT_MSG)
trace_set_result(wait=self._variables["wait"], timeout=True)
raise _AbortScript from ex
finally:
for task in tasks:
task.cancel()
unsub()
async def _async_run_long_action(self, long_task: asyncio.Task[_T]) -> _T | None:
"""Run a long task while monitoring for stop request."""
async def async_cancel_long_task() -> None:
# Stop long task and wait for it to finish.
long_task.cancel()
with suppress(Exception):
await long_task
# Wait for long task while monitoring for a stop request.
stop_task = self._hass.async_create_task(self._stop.wait())
try:
await asyncio.wait(
{long_task, stop_task}, return_when=asyncio.FIRST_COMPLETED
)
# If our task is cancelled, then cancel long task, too. Note that if long task
# is cancelled otherwise the CancelledError exception will not be raised to
# here due to the call to asyncio.wait(). Rather we'll check for that below.
except asyncio.CancelledError:
await async_cancel_long_task()
raise
finally:
stop_task.cancel()
if long_task.cancelled():
raise asyncio.CancelledError
if long_task.done():
# Propagate any exceptions that occurred.
return long_task.result()
# Stopped before long task completed, so cancel it.
await async_cancel_long_task()
return None
async def _async_call_service_step(self):
"""Call the service specified in the action."""
self._step_log("call service")
params = service.async_prepare_call_from_config(
self._hass, self._action, self._variables
)
running_script = (
params[CONF_DOMAIN] == "automation"
and params[CONF_SERVICE] == "trigger"
or params[CONF_DOMAIN] in ("python_script", "script")
)
response_variable = self._action.get(CONF_RESPONSE_VARIABLE)
trace_set_result(params=params, running_script=running_script)
response_data = await self._async_run_long_action(
self._hass.async_create_task(
self._hass.services.async_call(
**params,
blocking=True,
context=self._context,
return_response=(response_variable is not None),
)
),
)
if response_variable:
self._variables[response_variable] = response_data
async def _async_device_step(self):
"""Perform the device automation specified in the action."""
self._step_log("device automation")
await device_action.async_call_action_from_config(
self._hass, self._action, self._variables, self._context
)
async def _async_scene_step(self):
"""Activate the scene specified in the action."""
self._step_log("activate scene")
trace_set_result(scene=self._action[CONF_SCENE])
await self._hass.services.async_call(
scene.DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: self._action[CONF_SCENE]},
blocking=True,
context=self._context,
)
async def _async_event_step(self):
"""Fire an event."""
self._step_log(self._action.get(CONF_ALIAS, self._action[CONF_EVENT]))
event_data = {}
for conf in (CONF_EVENT_DATA, CONF_EVENT_DATA_TEMPLATE):
if conf not in self._action:
continue
try:
event_data.update(
template.render_complex(self._action[conf], self._variables)
)
except exceptions.TemplateError as ex:
self._log(
"Error rendering event data template: %s", ex, level=logging.ERROR
)
trace_set_result(event=self._action[CONF_EVENT], event_data=event_data)
self._hass.bus.async_fire(
self._action[CONF_EVENT], event_data, context=self._context
)
async def _async_condition_step(self):
"""Test if condition is matching."""
self._script.last_action = self._action.get(
CONF_ALIAS, self._action[CONF_CONDITION]
)
cond = await self._async_get_condition(self._action)
try:
trace_element = trace_stack_top(trace_stack_cv)
if trace_element:
trace_element.reuse_by_child = True
check = cond(self._hass, self._variables)
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'condition' evaluation:\n%s", ex)
check = False
self._log("Test condition %s: %s", self._script.last_action, check)
trace_update_result(result=check)
if not check:
raise _ConditionFail
def _test_conditions(self, conditions, name, condition_path=None):
if condition_path is None:
condition_path = name
@trace_condition_function
def traced_test_conditions(hass, variables):
try:
with trace_path(condition_path):
for idx, cond in enumerate(conditions):
with trace_path(str(idx)):
if cond(hass, variables) is False:
return False
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in '%s[%s]' evaluation: %s", name, idx, ex)
return None
return True
result = traced_test_conditions(self._hass, self._variables)
return result
@async_trace_path("repeat")
async def _async_repeat_step(self): # noqa: C901
"""Repeat a sequence."""
description = self._action.get(CONF_ALIAS, "sequence")
repeat = self._action[CONF_REPEAT]
saved_repeat_vars = self._variables.get("repeat")
def set_repeat_var(
iteration: int, count: int | None = None, item: Any = None
) -> None:
repeat_vars = {"first": iteration == 1, "index": iteration}
if count:
repeat_vars["last"] = iteration == count
if item is not None:
repeat_vars["item"] = item
self._variables["repeat"] = repeat_vars
# pylint: disable-next=protected-access
script = self._script._get_repeat_script(self._step)
async def async_run_sequence(iteration, extra_msg=""):
self._log("Repeating %s: Iteration %i%s", description, iteration, extra_msg)
with trace_path("sequence"):
await self._async_run_script(script)
if CONF_COUNT in repeat:
count = repeat[CONF_COUNT]
if isinstance(count, template.Template):
try:
count = int(count.async_render(self._variables))
except (exceptions.TemplateError, ValueError) as ex:
self._log(
"Error rendering %s repeat count template: %s",
self._script.name,
ex,
level=logging.ERROR,
)
raise _AbortScript from ex
extra_msg = f" of {count}"
for iteration in range(1, count + 1):
set_repeat_var(iteration, count)
await async_run_sequence(iteration, extra_msg)
if self._stop.is_set():
break
elif CONF_FOR_EACH in repeat:
try:
items = template.render_complex(repeat[CONF_FOR_EACH], self._variables)
except (exceptions.TemplateError, ValueError) as ex:
self._log(
"Error rendering %s repeat for each items template: %s",
self._script.name,
ex,
level=logging.ERROR,
)
raise _AbortScript from ex
if not isinstance(items, list):
self._log(
"Repeat 'for_each' must be a list of items in %s, got: %s",
self._script.name,
items,
level=logging.ERROR,
)
raise _AbortScript("Repeat 'for_each' must be a list of items")
count = len(items)
for iteration, item in enumerate(items, 1):
set_repeat_var(iteration, count, item)
extra_msg = f" of {count} with item: {repr(item)}"
if self._stop.is_set():
break
await async_run_sequence(iteration, extra_msg)
elif CONF_WHILE in repeat:
conditions = [
await self._async_get_condition(config) for config in repeat[CONF_WHILE]
]
for iteration in itertools.count(1):
set_repeat_var(iteration)
try:
if self._stop.is_set():
break
if not self._test_conditions(conditions, "while"):
break
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'while' evaluation:\n%s", ex)
break
await async_run_sequence(iteration)
elif CONF_UNTIL in repeat:
conditions = [
await self._async_get_condition(config) for config in repeat[CONF_UNTIL]
]
for iteration in itertools.count(1):
set_repeat_var(iteration)
await async_run_sequence(iteration)
try:
if self._stop.is_set():
break
if self._test_conditions(conditions, "until") in [True, None]:
break
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'until' evaluation:\n%s", ex)
break
if saved_repeat_vars:
self._variables["repeat"] = saved_repeat_vars
else:
self._variables.pop("repeat", None) # Not set if count = 0
async def _async_choose_step(self) -> None:
"""Choose a sequence."""
# pylint: disable=protected-access
choose_data = await self._script._async_get_choose_data(self._step)
with trace_path("choose"):
for idx, (conditions, script) in enumerate(choose_data["choices"]):
with trace_path(str(idx)):
try:
if self._test_conditions(conditions, "choose", "conditions"):
trace_set_result(choice=idx)
with trace_path("sequence"):
await self._async_run_script(script)
return
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'choose' evaluation:\n%s", ex)
if choose_data["default"] is not None:
trace_set_result(choice="default")
with trace_path(["default"]):
await self._async_run_script(choose_data["default"])
async def _async_if_step(self) -> None:
"""If sequence."""
# pylint: disable=protected-access
if_data = await self._script._async_get_if_data(self._step)
test_conditions = False
try:
with trace_path("if"):
test_conditions = self._test_conditions(
if_data["if_conditions"], "if", "condition"
)
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'if' evaluation:\n%s", ex)
if test_conditions:
trace_set_result(choice="then")
with trace_path("then"):
await self._async_run_script(if_data["if_then"])
return
if if_data["if_else"] is not None:
trace_set_result(choice="else")
with trace_path("else"):
await self._async_run_script(if_data["if_else"])
async def _async_wait_for_trigger_step(self):
"""Wait for a trigger event."""
if CONF_TIMEOUT in self._action:
timeout = self._get_pos_time_period_template(CONF_TIMEOUT).total_seconds()
else:
timeout = None
self._step_log("wait for trigger", timeout)
variables = {**self._variables}
self._variables["wait"] = {"remaining": timeout, "trigger": None}
trace_set_result(wait=self._variables["wait"])
done = asyncio.Event()
async def async_done(variables, context=None):
wait_var = self._variables["wait"]
if to_context and to_context.deadline:
wait_var["remaining"] = to_context.deadline - self._hass.loop.time()
else:
wait_var["remaining"] = timeout
wait_var["trigger"] = variables["trigger"]
done.set()
def log_cb(level, msg, **kwargs):
self._log(msg, level=level, **kwargs)
to_context = None
remove_triggers = await async_initialize_triggers(
self._hass,
self._action[CONF_WAIT_FOR_TRIGGER],
async_done,
self._script.domain,
self._script.name,
log_cb,
variables=variables,
)
if not remove_triggers:
return
self._changed()
tasks = [
self._hass.async_create_task(flag.wait()) for flag in (self._stop, done)
]
try:
async with async_timeout.timeout(timeout) as to_context:
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
except asyncio.TimeoutError as ex:
self._variables["wait"]["remaining"] = 0.0
if not self._action.get(CONF_CONTINUE_ON_TIMEOUT, True):
self._log(_TIMEOUT_MSG)
trace_set_result(wait=self._variables["wait"], timeout=True)
raise _AbortScript from ex
finally:
for task in tasks:
task.cancel()
remove_triggers()
async def _async_variables_step(self):
"""Set a variable value."""
self._step_log("setting variables")
self._variables = self._action[CONF_VARIABLES].async_render(
self._hass, self._variables, render_as_defaults=False
)
async def _async_stop_step(self):
"""Stop script execution."""
stop = self._action[CONF_STOP]
error = self._action[CONF_ERROR]
trace_set_result(stop=stop, error=error)
if error:
self._log("Error script sequence: %s", stop)
raise _AbortScript(stop)
self._log("Stop script sequence: %s", stop)
raise _StopScript(stop)