How to calculate energy based on time?

Hi,
I want to calculate the energy consumed for my electric floor heating and show it on the Energy panel.

Now, I have this solution:
Calculate the time how much has been turned on:

sensor:
  - platform: history_stats
    name: Heating time Living floor
    entity_id: binary_sensor.heating_living_floor
    state: "on"
    type: time
    start: "{{ 0 }}"
    end: "{{ now() }}"

Then, calculate consumed the energy (based on linear consumption of 2100 W):

template:
  - sensor:
      - name: "Energy Heating Living floor today"
        device_class: energy
        state_class: total_increasing
        unit_of_measurement: "kWh"
        state: "{{ float(states.sensor.heating_time_living_floor.state) * 2.1 }}"

But…:
The entity Energy Heating Living floor worked well for some first days but after some weeks it starts to calculate bad results - see screenshot below:


So, it calculates negative consumption. I think it’s because of those jumps down every day. And I think it’s because of erasure based on recorder.auto_purge. it will probably go wrong heating_time_living_floor sensor. I’m on the right track?

Please how can I correctly calculate this energy consumption (based on time) to work properly on Energy panel?

Thank you!

I’d only track today’s heating time.

    start: "{{ today_at("00:00") }}"

This is no longer recommended. Use this instead:

states('sensor.heating_time_living_floor')

Can’t you use the Reimann sum integral Integration? I do all of mine with that (unless im missing something in your question )

Integration - Riemann sum integral - Home Assistant (home-assistant.io)

1 Like

Yes, that what I do. For a spiky load like this use the “Left” method.

Today’s entity is not recommended - see New template Sensors for Energy start new day with negative value - #2 by Burningstone (I used today’s entity before, but I have the same “negative value” problem).

That shouldn’t happen with state_class: total_increasing.