Hi, I am about two weeks into my Home Assistant setup, and I've run into a challenge trying to define a template sensor that overrides negative values with zero.
I have a hacked Curb device that uses ha-energycurb to incorporate circuit-level power consumption into HA. But it can't measure every circuit. So to get "other" consumption, I created a template sensor for "other" so that all individual circuits + "other" add up to total household consumption.
That's easy enough, except that sometimes due to either timing mismatches in sensor readings or inevitable inaccuracy in the CT current measurements, I'm ending up with negative "other" consumption values that I'd like to override with 0 to avoid confusion in charts and automation logic.
I've tried two different approaches that I found mentioned on this forum in various topics, but neither is working for me. (I'm ending up with "other" being "NA" in charts and "unavailable" in the entity configuration view with both approaches, so I'm fairly sure it's not basic syntax issues, e.g. bad indentation, etc.)
I expected one of these to work. Can anyone help me out with a solution?
(Try #1) Using if-then logic:
- name: curb_other_power
state: >
{{
iif(
states('sensor.curb_total_consumption_power' | float) - states('curb_all_circuits_power' | float) < 0,
0,
states('sensor.curb_total_consumption_power' | float) - states('curb_all_circuits_power' | float)
)
}}
device_class: "power"
unit_of_measurement: 'W'
(Try #2) Using a clever python trick to sort and take the second value:
- name: curb_other_power
state: >-
{% set total_cons = (states('sensor.curb_total_consumption_power') | float) | round | int %}
{% set all_circuits = (states('sensor.curb_all_circuits_power') | float) | round | int %}
{% set other = (total_cons - all_circuits) | int %}
{{ ([0, other] |sort) [1] }}
device_class: "power"
unit_of_measurement: 'W'