Sum sensor

Hi all,
I have a sensor instantValueSensor that receive data (energy consumption) from a device at no specified time interval (it is a random time).

I want to create a new sensor sumSensor with the sum of every value from instantvaluesensor. I don’t want to use statistic sensor, because I do not have a specific time interval for instantValueSensor and so I risk to miss some values. I do not want to use automation also.

Something like

template:
  - sensor:
      - name: "sumsensor"
        unit_of_measurement: "kWh"
        device_class: energy
        state_class: measurement        
        state: "{{ (states('sensor.sumsensor') | float) + (states('instantvaluesensor') | float) }}"
        attributes:         
          last_reset: '1970-01-01T00:00:00+00:00'          

Obviously it doesn’t work. Give not coherent data.

Any ideas?

1 Like

I’ll assume that ‘instantvaluesensor’ is an example, because that’s not a valid entity id. But you might try:

template:
  - sensor:
      - name: "sumsensor"
        unit_of_measurement: "kWh"
        device_class: energy
        state_class: measurement        
        state: "{{ states('sensor.sumsensor') | float(0) +  states('instantvaluesensor') | float(0)  }}"
    trigger:
      - platform: state
        entity_id: instantvaluesensor

This should adjust the state of state of states.sumsensor everytime the state of instantvaluesensor changes. Using float(0) causes only numeric state values to be respected.

Just a guess, have not tried it.

Great! It works!

Here my complete sensor

template:
  - trigger:
     - platform: state
       entity_id: sensor.potenza_media_1_piano_in_un_minuto
    sensor:
      - name: "Energia elettrica 1 Piano"
        unit_of_measurement: "kWh"
        device_class: energy
        state_class: measurement  
        state: {{ (states('sensor.energia_elettrica_1_piano') | float) + ((states('sensor.potenza_media_1_piano_in_un_minuto')|float / (1000 * 60)) ) | round(5) }}
        attributes:         
          last_reset: '1970-01-01T00:00:00+00:00'   

Suitable for energy metering

1 Like

The only issue is that the sensor return to 0 where Hass restart. Why?

Hi Paolo, did you figure this out?

Btw: This type of sensor can now easily be created as „Helper“ from UI.