Help needed with an If / Then in a Template Sensor

Hi all

I need help with the following If / Then part of the following Template Sensor

template:
  - sensor:
      - name: "heat_power"
        unique_id: "heat_power"
        unit_of_measurement: W
        state_class: measurement
        device_class: power
        state: >
          {% set t_flow = states('sensor.ebusd_hmu_flowtemp') | float %}
          {% set t_return = states('sensor.ebusd_hmu_returntemp_temps2') | float %}
          {% set flow_rate = states('sensor.ebusd_hmu_waterthroughput') | float %}
          {% set heat_power = flow_rate / 3600 * (t_flow - t_return) * 4186  %}
          **{% if states('heat_power') | float < 7500 %}**
**            {{ 'heat_power' }}**
**          {% endif %}**

heat_power is a value in Watts. I want to return the value if it’s less than 7500 watts, because sometime I get a spurious value of many 1000’s greater than this. So without the If and Endif, with just {{ ‘heat_power’ }} it returns the value for heat_power fine. But with the attached config, it won’t return a value at all.

I’m sure it’s something stupidly small, but I just don’t see it. I also tried {{ states (‘heat_power’) }} without success

Thanks in advance

It is indeed rather simple, use an else to return this.state (the original state of the sensor):

template:
  - sensor:
      - name: "heat_power"
        unique_id: "heat_power"
        unit_of_measurement: W
        state_class: measurement
        device_class: power
        availability: |
          {{ has_value('sensor.ebusd_hmu_flowtemp') and 
             has_value('sensor.ebusd_hmu_returntemp_temps2') and 
             has_value('sensor.ebusd_hmu_waterthroughput') }}
        state: >
          {% set t_flow = states('sensor.ebusd_hmu_flowtemp') | float(0) %}
          {% set t_return = states('sensor.ebusd_hmu_returntemp_temps2') | float(0) %}
          {% set flow_rate = states('sensor.ebusd_hmu_waterthroughput') | float(0) %}
          {% set heat_power = flow_rate / 3600 * (t_flow - t_return) * 4186  %}
          {% if heat_power < 7500 %}
            {{ heat_power }}
          {% else %}
            {{ this.state }}
          {% endif %}

I fixed a few other flaws (quotes in wrong places, use of states where you didn’t mean to) and potential problems for you, such as adding an availability template. (That may have even be the cause of the weird values). Havent tested it, so I may have made some mistakes of my own.

Many thanks Edwin,

If heat_power is GREATER than 7500, then what is returned with “this.state” ?

Whatever the state was before that. This.state is the state of the template sensor before assigning a new value. If you’d rather have the sensor is unavailable, then you could add the test for 7500 to the availability template.