Help with checking for a value within range with a Template Sensor

I am using mqtt to bring a value from a pressure sensor into HA, and it works most of the time; however, sometimes the decimal of the float value gets disregarded and number ends up being x1000. So I wanted to check the value with a template and only keep the values less than 30.0. I am attempted to read in the mqtt data sensor.pool_sand_filter_pressure, check that it is below 30.0 with an if statement. When the IF statement is true pass the value to the variable filtered_press, then assign it to the template sensor This my latest attempt. Can someone point out whats wrong?

template:
  - sensor:
      - name: Filter Pressure Template
      - unit_of_measurement: "PSI"
        state: >
          {% if states("sensor.pool_sand_filter_pressure") | float <= 30.0 %}
            set filtered_press = states("sensor.pool_sand_filter_pressure") | float
          {% endif %}
          {{filtered_press}}

I get the following log message but I don’t understand what it means

Logger: homeassistant.config
Source: config.py:864
First occurred: 3:47:45 PM (1 occurrences)
Last logged: 3:47:45 PM

Invalid config for [template]: required key not provided @ data['sensor'][0]['state']. Got None. (See /config/configuration.yaml, line 80).
template:
  - trigger:
      - platform: state
        entity_id: sensor.pool_sand_filter_pressure
        not_to:
          - unavailable
          - unknown
    sensor:
      - name: Filter Pressure Template
        unit_of_measurement: "PSI"
        state: >
            {{ trigger.to_state.state if trigger.to_state.state | float <= 30.0 else this.state }}

Thanks Drew, but I sorted it out with a simple if statement in Node Red. However; I am curious about all the different things going on in this template

You have too many dashes in the sensor section. You’re trying to make 2 sensors with the config and only one has the state key, the second one. So the first one errors when it doesn’t see the state key. Hence the key missing error.

The template is just a 1 line if/then/else statement. It boils down to “If the source sensor’s new value is less than or equal to 30, set that as the value for this sensor. Otherwise, keep the previous value of this sensor.”

It could also be written out long-form:

{% if trigger.to_state.state | float <= 30.0 %}
  {{ trigger.to_state.state }}
{% else %}
  {{ this.state }}
{% endif %}
1 Like