Template sensor showing negative value

Things are getting a bit complicated for me to solve on my own. Hope some of you guys can help me.

I have created a template sensor as below, reading a Shelly 3EM power meter. It measures my house consumption. Since I have solar panels I also get the exported/imported value from the inverter meter itself every 5 second…
By calculating house consumption + total exported energy (the value is negative when exporting electricity), I manage to calculate the house power consumed, despite production.

template:
  - sensor:
      - name: "Stora huset total power"
        unique_id: a5d98578-d6dc-4ff6-b57a-79e69dac3d83
        state: >-
          {{ (states('sensor.solaredge_ac_power') | float(0) +
              states('sensor.sh_power1') | float(0) +
              states('sensor.sh_power2') | float(0) +
              states('sensor.sh_power3') | float(0)) | round(0) }}
        availability: >-
          {{ not 'unavailable' in 
            [ states('sensor.sh_power1'), 
              states('sensor.sh_power2'),
              states('sensor.sh_power3') ] }} 
        unit_of_measurement: W
        device_class: power
        state_class: measurement

Now to the problem:


Inverter sensor updates every 5:second, and when a sudden loss in solar production occurs, the template sensor get a negative spike.
a) is there a way to set like a scan_interval for this sensor?
b) or even better, can the sensor be forbidden to show a negative value?

I found that time_pattern is the correct term to us in templating.
One question remains though, can i prohibit the sensor to show/read negative values?

template:
  - trigger:
      - platform: time_pattern
        seconds: "/10"
    sensor:
      - name: "Stora huset total power"
        unique_id: a5d98578-d6dc-4ff6-b57a-79e69dac3d83
        state: >-
          {{ (states('sensor.solaredge_ac_power') | float(0) +
              states('sensor.sh_power1') | float(0) +
              states('sensor.sh_power2') | float(0) +
              states('sensor.sh_power3') | float(0)) | round(0) }}
        availability: >-
          {{ not 'unavailable' in 
            [ states('sensor.sh_power1'), 
              states('sensor.sh_power2'),
              states('sensor.sh_power3') ] }} 
        unit_of_measurement: W
        device_class: power
        state_class: measurement

try this:

state: >-
  {% set new_state = (states('sensor.solaredge_ac_power') | float(0) +
       states('sensor.sh_power1') | float(0) +
       states('sensor.sh_power2') | float(0) +
       states('sensor.sh_power3') | float(0)) | round(0) %}
  {% if new_state | float >= 0 %}
    {{ new_state }}
  {% else %}
    {{ states('sensor.stora_huset_total_power') }}
  {% endif %}
3 Likes

Thank you, I had never figured out this myself. I’ll implement the code and give it a try.

1 Like