Water-meter with ESPHome and pulse_counter resets total to 0 upon reboot

So I dug a bit instead of blindly just trying some code I found somewhere (what I always end up with but normally it works better to start with :D…)

For others reading anytime, good summary of the difference between pulse_counter and pulse_meter: Pulse_counter vs pulse_meter - #2 by der-optimist

I simplified the definition to what is actually only needed, with some slightly better naming (for me at least):

esphome:
  name: water-meter
  friendly_name: water-meter
  on_boot:
    then:
      - pulse_meter.set_total_pulses: 
          id: water_pulse_meter
          value: !lambda 'return id(water_meter_total);'

esp8266:
  board: esp01_1m

preferences:
  flash_write_interval: 5min

globals:
  id: water_meter_total
  type: int
  restore_value: yes

# Enable Home Assistant API
api:
  encryption:
    key: "--redacted--"
  actions:
    - action: set_total_liters
      variables:
        new_total_liters: int
      then:
        - pulse_meter.set_total_pulses:
            id: water_pulse_meter
            value: !lambda 'return new_total_liters;'

...

sensor:
  - platform: pulse_meter
    pin: GPIO12
    name: "Water Meter Flow"
    id: water_pulse_meter
    unit_of_measurement: "liter/min"
    icon: "mdi:water"
    total:
      name: "Water Meter Total"
      unit_of_measurement: "m³"
      accuracy_decimals: 3
      device_class: water
      state_class: total_increasing
      filters:
        - lambda: |-
            id(water_meter_total) = id(water_pulse_meter).raw_state;
            return x / 1000.0;

This results into two sensors, one for the water flow, the other one for the measure on total consumption, which is exactly what is expected from such a device, nothing more, nothing less.

What I figured out:

  • The globals water_meter_total is still an integer, even if displayed divided by 1000 to get m3
  • I have 4 counters, the inductive sensor is on the fourth one but that one measures deciliters (dl), so its value is naturally to be excluded when presetting the total counter

So now my ESP8266 is flashed with this strip-down (and much more meaningful) version, nice!

  1. I install the device
  2. I set the initial total value
  3. Water has been used here and there and properly reported
  4. It’s more than 45 minutes since the installation
  5. I reboot the device by removing power supply and back

Result: total meter resets to 0. So it still doesn’t work!