Subtract SensorValue2 from SensorValue1, but only when SensorValue2 is less than SensorValue1

Hi all,

I’m tinkering with template sensors and I’m having a little trouble getting my syntax correct. I’ve followed a few other examples from the forums, but I’m new to templates and can’t quite figure out what I’m doing wrong.

I have two CT clamps measuring power consumption - one on my mains circuit into the house, the other to a sub-board I have downstairs. I also have another sub-board for upstairs power. I’m trying to calculate upstairs power consumption by subtracting downstairs usage (SensorValue2) from the mains (SensorValue1).

Because the values from the CT clamps don’t update in unison, sometimes the downstairs consumption can exceed mains consumption (say when I turn something on downstairs with a large initial draw, like an oven or a dishwasher). This can cause a negative value to be calculated until the mains sensor (SensorValue1) updates.

Here’s what I’ve cobbled together so far, which is not working:

# Template.yaml

- sensor: 

    - name: Upstairs Power
      value_template: >
        {% set mains = states('sensor.efergy_796024') | float %}
        {% set downstairs = states('sensor.efergy_829605') | float %}
        {% if mains > downstairs }
          {{ mains - downstairs }}
        {% endif %}
      unit_of_measurement: "W"
      device-class: power

Based on the examples I’m following, this should be working. But I don’t know enough to be able to see why it isn’t :sweat_smile:

- sensor: 
    - name: "Upstairs Power"
      unit_of_measurement: "W"
      device_class: power
      state: >-
        {% set mains = states('sensor.efergy_796024') | float %}
        {% set downstairs = states('sensor.efergy_829605') | float %}
        {{ (mains - downstairs) if (mains > downstairs) else 0 }}

The above code assumes you are using the modern template sensor format.

You can review the documentation once more to check the configuration variables that are accepted by template sensor.

1 Like