Template switch - scripts with delay

Hey

I have a template switch that uses two scripts as its turn off/turn on like so:

  - platform: template
    switches:
      heating:
        value_template: "{{ is_state('input_boolean.heating', 'on')}}"
        turn_on:
          - service: script.heating
          - service: input_boolean.turn_on
            entity_id: input_boolean.heating
            
        turn_off:
          - service: script.cooling
          - service: input_boolean.turn_off
            entity_id: input_boolean.heating

Im trying to add a 2 hour delay into the scripts but this seems to have stopped my switch from toggling properly. Am i right in thinking that the switch wont change state until the script has completed? Any ideas for a work around for this? Iā€™d like to be able to toggle the switch within this 2 hour delay and have the switches state change and the delay restart.

As your state feedback is the input boolean, just put that before the script:

  - platform: template
    switches:
      heating:
        value_template: "{{ is_state('input_boolean.heating', 'on')}}"
        turn_on:
          - service: input_boolean.turn_on
            entity_id: input_boolean.heating
          - service: script.heating
        turn_off:
          - service: input_boolean.turn_off
            entity_id: input_boolean.heating
          - service: script.cooling

This will give you the correct state feedback for the switch. However what happens when you toggle the switch during the 2 hour delay is unpredictable.

If the switch is on (script.heating running) and you switch it off, all that happens is that the script.cooling is started. script.heating will still be running.

A way around this would be to turn of the other script as the first service call in each of the scripts. Likewise you could move the input boolean switching to the scripts next service call too if you wanted:

Switch:

  - platform: template
    switches:
      heating:
        value_template: "{{ is_state('input_boolean.heating', 'on')}}"
        turn_on:
          - service: script.heating
        turn_off:
          - service: script.cooling

Scripts:


heating:
  sequence:
    - service: script.turn_off
      entity_id: script.cooling
    - service: input_boolean.turn_on
      entity_id: input_boolean.heating
    - #... rest of your script inc. delay
  
cooling:
  sequence:
    - service: script.turn_off
      entity_id: script.heating
    - service: input_boolean.turn_off
      entity_id: input_boolean.heating
    - #... rest of your script inc. delay
1 Like

Brilliant! Thanks very much. That makes sense.