Recursive sum of a template sensor

in my power meter logger, based on ESP32 and RS485, I want to create a parameter in order to have daily power consumption.

starting from value read for RS485 device:

  • platform: modbus_controller
    modbus_controller_id: es32ls
    name: “Active Power”
    id: modbus_Active_Power
    register_type: holding
    address: 0xA
    unit_of_measurement: “KW”
    value_type: U_WORD
    accuracy_decimals: 2
    - multiply: 0.01

Then I’ve created a template sensor like this:

  • platform: template
    name: “Daily Power”
    id: daily_power
    lambda: |-
    static float partial_power=0;
    return partial_power += (id(modbus_Active_Power).state)/360;
    update_interval: 10s
    accuracy_decimals: 2
    unit_of_measurement: “KWh”

but it read is fixed to nan

second part of this project is to have a DAILY value, so every midnight I’ve to set this value to 0.
i’ve tried like this:


  • platform: sntp
    • seconds: 0
      minutes: 0
      hour: 0
      lambda: |-
      id (daily_power).state = 0;

and tried to declare a global float variables but error.

Looks like you want to get Energy (KWh) from a Power sensor (KW)?

HA uses Riemann integral for that.

Looks like ESPHome has something similar, apparently

Thanks Chris,
a part the result, Energy, i’d like to make the system works, in order to better understand how ESPHome can works, with maths.

The source is there if you want to really understand, but it is a Riemann integrator Riemann sum - Wikipedia