Automation with if condition

I need help. I want that my fan is controlled with a switch and a slider. When the slider is higher then 0 the fan should turn of after …minutes(the slider goes from 0 to 10). But when the slider is on 0 I want the fan to turn on “forever”.

automation:
  - alias: vent_timer
    trigger:
    - platform: state
      entity_id: switch.ventilator_ventilator
      to: 'on'
      for:
        minutes: "{{ states('input_number.vent_time')|int }}"
    action:
      - entity_id: switch.ventilator_ventilator
        service_template: <
            {%- if input_number.vent_time > 0 -%}
                service: switch.turn_off
            {% endif %} 

I’m a little concerned about the 0 minutes case creating a loop of listeners, but try it and see:

automation:
  - alias: vent_timer
    trigger:
    - platform: state
      entity_id: switch.ventilator_ventilator
      to: 'on'
      for:
        minutes: "{{ states('input_number.vent_time')|int }}"
    action:
      - entity_id: switch.ventilator_ventilator
        service_template: >
            {% if states('input_number.vent_time')int > 0 %}
                service: switch.turn_off
            {% else %}
                service: switch.turn_on
            {% endif %} 

When I check the Config it says this:

Invalid config for [automation]: invalid template (TemplateSyntaxError: expected token 'end of statement block', got 'int') for dictionary value @ data['action'][0]['service_template']. Got None. (See /config/configuration.yaml, line 27). 

Remove “service:” from the template results.

automation:
  - alias: vent_timer
    trigger:
    - platform: state
      entity_id: switch.ventilator_ventilator
      to: 'on'
      for:
        minutes: "{{ states('input_number.vent_time')|int }}"
    action:
      - entity_id: switch.ventilator_ventilator
        service_template: >
            {% if states('input_number.vent_time')int > 0 %}
              switch.turn_off
            {% else %}
              switch.turn_on
            {% endif %} 

Same issue

Invalid config for [automation]: [template] is an invalid option for [automation]. Check: automation->action->0->template. (See /config/configuration.yaml, line 46). 

I

Missing the filter character before int:

        service_template: >
            {% if states('input_number.vent_time')|int > 0 %}
              switch.turn_off
            {% else %}
              switch.turn_on
            {% endif %} 

Thank you very much.
It works

1 Like