Template sensor and filtering out occasional negative results from calculation

Hi All, I have a template sensor (home power) that derives it value from a subtraction from two other sensors (total power - ev charger power). The two source sensor values each come from a different integration so from a timing perspective the calculation sometimes yields a negative result.

Its not a huge problem just that the resultant graphs I create from it look a little odd with the occasional negative value.

Is there some way to filter negative results OR perhaps there is some other logical way of approaching this problem?

- platform: template
  sensors:
    power_house_consumption:
      friendly_name: House Consumption
      unit_of_measurement: "W"
      value_template: >-
        {% set total_consumption = (states('sensor.fronius_house_load') | float * -1) | round | int %}
        {% set tesla_consumption = states('sensor.twcmanager_1524_charger_load_w') | int %}

        {% set house_consumption = (total_consumption - tesla_consumption) | int %}

        {{ house_consumption }}
- platform: template
  sensors:
    power_house_consumption:
      friendly_name: House Consumption
      unit_of_measurement: "W"
      value_template: >-
        {% set total_consumption = (states('sensor.fronius_house_load') | float * -1) | round | int %}
        {% set tesla_consumption = states('sensor.twcmanager_1524_charger_load_w') | int %}
        {% set house_consumption = (total_consumption - tesla_consumption) | int %}
        {{ ([0, house_consumption, 50000] |sort) [1] }}

See here for explanation-

1 Like

Thanks for this, it works well in so far as negative values are stopped. Very elegant! The reality is that power consumption in the house would never fall to zero (unless there is a power cut of course :wink: so I dreamed up a new way of filtering out what are effectively transient conditions (only lasting a single 60 second sample period) by feeding the template sensor “itself” (effectively its previous value) when the resulting computation is <=0.

- platform: template
  sensors:
    power_house_consumption:
      friendly_name: House Consumption
      unit_of_measurement: "W"
      value_template: >-
        {% set total_consumption = (states('sensor.fronius_house_load') | float * -1) | round | int %}
        {% set tesla_consumption = states('sensor.twcmanager_1524_charger_load_w') | int %}

        {% set house_consumption = (total_consumption - tesla_consumption) | int %}

        {% if house_consumption <= 0 %}
          {{ states('sensor.power_house_consumption') }}
        {% else %}
          {{ house_consumption }}
        {% endif %}