Utility Meter with diff value instead sumatory for totals

The utility meter calcule the value with sumatory of deltas. Normally works fine but, if you restart HA, you lost some values and get worng total value.

In total incresase sensors a simple solution is use the diff actual value and first value of period.

I am emulating this using a template sensor with trigger each hour that “copy” the value and another template sensor that calculate the diff the actual value and the first template.

  - trigger:
      - platform: time_pattern
        minutes: 0
        seconds: 0
    sensor:
      - name: "This hour start"
        unique_id: this_hour_start
        state: "{{ states('sensor.grid_consumption') | float(0) }}"
        unit_of_measurement: "kWh"
        state_class: total_increasing
        

  - sensor:
     - name: "This hour"
       unique_id: "this_hour"
       unit_of_measurement: "kWh"
       state: "{{ ((states('sensor.grid_exported') | float(0) - states('sensor.this_hour_start') }}"

Now I get a perfect calculate value if I don’t restart HA between hour change…