Sonoff PowR2 with ESPHome: Energy Utility Meter drops to "0" after reboot

I have changed my yaml, so that my utility meters do not drop to zero after reboot. The issue was that during reboot, ESPHome sends a zero to HomeAssistant and that resets the Utility Meter. (I still don’t understand, why it is like this, as the Utility Meter is state_class: total_increasing and should not drop to zero…)

For completness, I have asked my artificial friend to provide a summary on my changes.


1. Added: preferences Component (Top-Level)

A new top-level preferences block was introduced to explicitly configure the flash write interval. This controls how frequently buffered global variable changes are committed to flash memory.

preferences:
  flash_write_interval: 1min

The default value is already 1min; the block was added for documentation clarity and to allow easy future adjustment.


2. Added: globals Section

Two global variables were introduced to enable energy accumulation across device reboots:

globals:
  - id: energy_total_wh
    type: float
    restore_value: true      # Persisted to flash; survives power loss
    initial_value: '0.0'

  - id: energy_raw_last
    type: float
    restore_value: false     # Intentionally not persisted; resets to 0 on every boot
    initial_value: '0.0'
  • energy_total_wh holds the cumulative lifetime energy value and is restored from flash on boot.
  • energy_raw_last tracks the last raw CSE7766 register value within the current session only.

3. Modified: energy Sensor — Lambda Filter Added

The energy sub-sensor of the cse7766 platform received a delta-accumulation lambda filter.

energy:
  name: "Energy"
  state_class: total_increasing
  device_class: energy
  accuracy_decimals: 0
  filters:
    - throttle: ${update_interval}
    - lambda: |-
        float delta = x - id(energy_raw_last);
        id(energy_raw_last) = x;
        if (delta < 0) return id(energy_total_wh);  // Reboot detected → no deduction
        id(energy_total_wh) = id(energy_total_wh) + delta;
        return id(energy_total_wh);

The lambda computes the incremental delta between consecutive raw readings and accumulates it into energy_total_wh. A negative delta (indicating a chip reset after reboot) is silently ignored, preventing the published value from ever dropping to zero.