Variable/condition evaluation

FWIW, here’s one of the more complicated automations I’ve created recently. It’s part of a system to restoring active timers that were interrupted by a restart. Before the advent of variables, it would not be possible to write this as a YAML automation (the original version was a python_script). It serves as an example of how variables can be used.

  • The modes variable, whose scope is the entire action, is defined once, outside the repeat. It could be defined outside the action but it’s not used anywhere other than within the action so that’s where I chose to define it.

  • The mode and timers_text variables are defined within the repeat and are redefined every repetition (just twice in all because count is 2).

  • The timers variable is defined within choose and is based on the timers_text variable.

  • The remaining three variables, t, id, and d, are defined within a nested repeat and their values are based on other variables.

- alias: 'Timers Restore'
  mode: single
  trigger:
    platform: homeassistant
    event: start
  action:
  - variables:
      modes:
      - active
      - paused
  - repeat:
      count: 2
      sequence:
      - variables:
          mode: '{{ modes[repeat.index-1] }}'
          timers_text: "{{ states('input_text.timers_' ~ mode) }}"
      - choose:
        - conditions: '{{ timers_text | length > 0 }}'
          sequence:
          - variables:
              timers: "{{ timers_text.split(',') }}"
          - repeat:
              count: '{{ timers | count }}'
              sequence:
              - variables:
                  t: '{{ timers[repeat.index-1].split() }}'
                  id: 'timer.{{t[0]}}'
                  d: "{{ t[1]|int - (now().timestamp()|int if mode == 'active' else 0) }}"
              - condition: template
                value_template: '{{ d > 0 }}'
              - service: timer.start
                data:
                  entity_id: '{{ id }}'
                  duration: '{{ d }}'
              - condition: template
                value_template: "{{ mode == 'paused' }}"
              - service: timer.pause
                data:
                  entity_id: '{{ id }}'