Utility meter counting double after restart of HA

For measuring rain I have build a rain gauge using a Zigbee door contact. For each amount of rain I get a pulse, that works fine

sensor:
# rain meter
  - platform: history_stats
    name: Regenmeter_puls
    entity_id: binary_sensor.regenmeter
    state: 'off'
    type: count
    start: '{{ now().replace(hour=0, minute=0, second=0) }}'
    end: '{{ now() }}'
    
  - platform: template
    sensors:
      regenval_in_mm:
        friendly_name: Regenval in mm
        unit_of_measurement: "mm"
        icon_template: 'mdi:weather-pouring'
        value_template: >
          {{ (states('sensor.regenmeter_puls') | float * 0.254) | round(1) }}

Then I use utility meter for some interval counters:

utility_meter:
# rain meter
  regen_per_kwartier:
    source: sensor.regenval_in_mm
    cycle: quarter-hourly
  regen_per_dag:
    source: sensor.regenval_in_mm
    cycle: daily
  regen_per_maand:
    source: sensor.regenval_in_mm
    cycle: monthly

This also seems to work. But when I restart HA you see the correct values shown but after a few seconds the values are doubled.

What’s going wrong??? Thanks for any advice.

This is because sensors take time to initialise.

Say you had a pulse count of 5 in your utility meter (and the template sensor).

You restart home assistant.

The history stats sensor starts as unknown which is converted to 0 by the |float filter in the template sensor, then is restored to 5.

The utility meter sees this as an increase of 5, updating itself to 10 (double what it was)

You should be able to prevent this by including an availability template in your template sensor. Try this:

  - platform: template
    sensors:
      regenval_in_mm:
        friendly_name: Regenval in mm
        unit_of_measurement: "mm"
        icon_template: 'mdi:weather-pouring'
        value_template: >
          {{ (states('sensor.regenmeter_puls') | float * 0.254) | round(1) }}
        availability_template: "{{ states('sensor.regenmeter_puls') not in ['unknown', 'unavailable', 'none'] }}"
3 Likes

Thanks. But now the sensor reports ‘Unavailable’ long after restarting.
If I check

"{{ states('sensor.regenmeter_puls') not in ['unknown', 'unavailable', 'none'] }}"

it returns ‘True’. So I guess it should report a value.
When I check the sensor ‘sensor.regenmeter_puls’ it reports 44

Sorry, problem solved, I also included the double quotes in the formula and they should not be there. Now it seems to be ok.

Can I also avoid this for input_numbers?