How to use greater than / less than properly in a trigger value template

Hey folks,

I’m stepping my way through understanding templating, and I’m trying to use the below to achieve

When humidity is greater than 55%, switch on fan, and when it’s less than 55% switch off fan. Can anyone suggest what daft mistake I’m making in the below?

trigger:
  - platform: template
    value_template: >-
      {% if state('sensor.main_bathroom_humidity') | float > 55 %}true{% endif
      %}
    id: Above 55% Humidity
  - platform: template
    value_template: >-
      {% if state('sensor.main_bathroom_humidity') | float < 55 %}true{% endif
      %}
    id: Below 55% Humidity
condition: []
action:
  - choose:
      - conditions:
          - condition: trigger
            id: Above 55% Humidity
        sequence:
          - service: switch.turn_on
            data: {}
            target:
              entity_id: switch.main_bathroom_fan
      - conditions:
          - condition: trigger
            id: Below 55% Humidity
        sequence:
          - service: switch.turn_off
            data: {}
            target:
              entity_id: switch.main_bathroom_fan
1 Like

You’ve just got a couple little issues…

  1. There is no reason to use an if statement for your examples.
  2. The function is states() not state()
  3. You need to provide a default value for many filters, including float.
trigger:
  - platform: template
    value_template: >-
      {{ states('sensor.main_bathroom_humidity') | float(0) > 55 }}
    id: Above 55% Humidity
  - platform: template
    value_template: >-
      {{ states('sensor.main_bathroom_humidity') | float(0) < 55 }}
    id: Below 55% Humidity

However, it’s not really necessary to use template triggers here, since the basic Numeric state trigger will work fine… And that will also allow you to easily add a for variable so your fan doesn’t bounce on and off if the humidity is hovering around your setpoint.

trigger:
  - platform: numeric_state
    entity_id: sensor.main_bathroom_humidity
    above: 55
    id: 'on'
    for: "00:01:00"
  - platform: numeric_state
    entity_id: sensor.main_bathroom_humidity
    below: 55
    id: 'off'
    for: "00:01:00"
condition: []
action:
  - service: switch.turn_{{ trigger.id }}
    target:
      entity_id: switch.main_bathroom_fan
6 Likes

I appreciate you taking the time to lay out the syntaxical issues with my initial approach, and then suggesting the simpler approach with the for variable - this has really helped my learning. Thanks Drew

3 Likes