Logic in scripts?

EDIT: Whilst the script as given below is not correct, I now think my issue is the conditional delay.
I have found entries here on the forum that seem to imply it can’t be done without comparing times. i.e. compare the time the trigger occurs and the time it will be after the required delay.

That seems a bit cumbersome to me but I’ll work on that for now until I hear otherwise!

=====================================

Is it possible to have logic in a script?

I would like to cause a delay if an input_boolean is ‘On’ and I would like that delay to be for the amount set in an input_number. Else the delay should be 15 seconds.

To illustrate, this is what I have now but is only one of many attempts I have had at doing this.

irrigation_cycle:
  alias: "Irrigation cycle"
  sequence:
    # Open valve
    - service: homeassistant.turn_on
      entity_id: switch.test_sonoff_basic
    # If included in cycle, delay for 'zone 1 duration'
    #   else delay for 15 seconds
    - service_template: >
        {% if is_state('input_boolean.water_zone1', 'on') %}
          delay: '00:{{ state('input_number.zone1_duration') }}:00'
        {% else %}
          delay: '00:00:15'
        {% endif %}
    # close valve
    - service: homeassistant.turn_off
      entity_id: switch.test_sonoff_basic
    # delay for 15 seconds
    - delay: '00:00:15'

(For clarity, input_number.zone1_duration is a number between 1 and 59 and there is intended to be a further delay of 15 seconds at the end)

Delay is separate to service template. I don’t know if it will work how you want it to, but if it will it would be something like…

irrigation_cycle:
  alias: "Irrigation cycle"
  sequence:
    # Open valve
    - service: homeassistant.turn_on
      entity_id: switch.test_sonoff_basic
    # If included in cycle, delay for 'zone 1 duration'
    #   else delay for 15 seconds
    - delay: >
        {% if is_state('input_boolean.water_zone1', 'on') %}
          '00:{{ state('input_number.zone1_duration') }}:00'
        {% else %}
          '00:00:15'
        {% endif %}
    # close valve
    ...... 

Thanks but unfortunately that doesn’t seem to work, although the script editor doesn’t complain. I think I am going to have to rethink the entire way I was doing this. Which is a shame because it feels like something quite trivial.

Is there a way to conditionally ‘call’ a script?

Yeah, use a service template to decide which script to call, or put a condition block at the start of each script.

Ah ha! Condition block in the script! That could do it.

Out of interest though what would be the syntax using a service template? I couldn’t get that to work.

Run script one when boolean turned on, run script two when off…

trigger:
  platform: state 
  entity_id: input_boolean.test
action:
  service_template: >
    {% if is_state('input_boolean.test' , 'on') %} script.one
    {% else %} script.two {% endif %}

Thanks.
Again.

1 Like