Use template logic to turn on a switch from a script

Hi everyone
I have a script which calls multiple services, however two of these services (unrelated to each other) require a little logic to make sense. The first of these is to set the temperature on the climate service which works but I cannot figure out how to do something similar with a switch.

This is my working climate code:

- service: climate.set_temperature
      data_template:
        entity_id: climate.heating
        temperature: >
          {% if states('input_select.system_mode') == 'Home' or states('input_select.system_mode') == 'Pets only' %}
            {{states('input_number.heating_daytime_temperature')}}
          {% endif %}

The following is pseudocode of what I want to achieve:

- service: switch.turn_on
  target:
    entity_id: >
      {% if states('sensor.bathroom_humidity') > states('input_number.bathroom_humidity_upper_trigger') %}
        switch.bathroom_fan
      {% endif %}

I think this should be possible but I cannot find the syntax in the docs for this one.

Thanks

You can use a condition template:

sequence:
  - condition: template
    value_template: "{{ (states('sensor.bathroom_humidity') | float) > (states('input_number.bathroom_humidity_upper_trigger') | float )}}"
  - service: switch.turn_on
    entity_id: switch.bathroom_fan

if you want the script to conditionally run that service but also continue on, you have to use choose or if then.

- if: >
    {{ states('sensor.bathroom_humidity') | float > states('input_number.bathroom_humidity_upper_trigger') | float }}
  then:
  - service: switch.turn_on
    entity_id: switch.bathroom_fan

If you use a condition before an action, the condition will stop the entire script. However, when using an if or choose, this does not happen.

1 Like

Thanks @petro
Your solution worked for me.

1 Like