Resetting pulse_meter from current value on boot

So I’ve set up the pulse_meter sensor to read out my gas meter and I’m trying to figure out how I can persist the total number of pulses between reboots / updates, since the total value returned by the sensor resets to 0 when I update the esp. I’ve tried setting the target sensor up as a platform: homeassistant sensor and reading it back from there but I always get back a value of MAX_INT, presumably because at the time I’m trying to read it in, the sensor is marked as unavailable. I’m kind of stumped at this point as always having to manually reset the total number of pulses after every install is very tedious and I was wondering if there are some other ways I could persist a value through a reinstall of the esp?

You need to create a persisted global variable and always mirror the pulse count to that.
Then on boot you write the content of that variable back to the sensor.

On ESP8266 you need to enable writing the values to flash. When enabled per default the globals are writen to flash every 60sec. You can increase that - but it will wear out your flash, or decrease it. I opted for 5min. So in the worst case I loose 5min of data - which I can live with. :slight_smile:

Here are the important parts as an example for pulse_meter. Same works for pulse_counter.

esphome:
  on_boot:
    then:
      - pulse_meter.set_total_pulses:
          id: your_gas_id
          value: !lambda "return id(total_pulses);"

esp8266:
  restore_from_flash: true 

globals:
  - id: total_pulses
    type: float
    restore_value: yes

sensor:
  - platform: pulse_meter
...
    total:
...
      filters:
        - lambda: |-
            id(total_pulses) = id(your_gas_id).raw_state;
            return x;
1 Like

This works, thanks!

I also opted for 5 minutes flash write interval:

preferences:
  flash_write_interval: 5min

For those running Home Assistant Glow and found this thread, “your_gas_id” is "sensor_energy_pulse_meter"in the above code.

The final lambda filter under total is:

- lambda: id(total_pulses) = id(sensor_total_energy).raw_state;
    return x * (1.0 / ${pulse_rate});

Hey, thanks for that. It seems exactly what I am looking for.

Excuse my ignorance (doing HA since 3 months), but what does “your_gas_id” refer to above? I cannot make this to work no matter what I try.

Hey! Do you think you could post the entire ESP file that works for you?

I get a seemingly random (but low, i.e. <100) number stored in the flash instead of the total at the time of writing. :frowning: