Retain total values of pulse_meter

Hi there,

i’m using esphome with home assistant for a while now. My last project was making my watermeter a smart one. I used a wemos d1 mini an an inductive sensor on my meter and it works quite well. Since I made a few restarts of the wemos I discovered that my “total”-values were not stored. So I wanted to fix this but somehow I am doing something wrong.
This ist my esphome config file for the metering device:

esphome:
  name: metering-esp
  friendly_name: metering_esp

esp8266:
  board: d1_mini

# Enable logging
logger:

# Enable Home Assistant API
api:
  encryption:
    key: "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
  services:
    - service: set_total
      variables:
        new_total: int
      then:
        - pulse_meter.set_total_pulses:
            id: watermeter
            value: !lambda 'return new_total;'

ota:
  password: "xxxxxxx"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Metering-Esp Fallback Hotspot"
    password: "xxxxxxxxxxxxxxxxxx"

captive_portal:
  
sensor:
  - platform: pulse_meter
    id: "watermeter"
    pin: 12
    name: "Wasserzähler Durchflus"
    unit_of_measurement: "liter/min"
    total:
      name: "Wasserzähler Total"
      unit_of_measurement: "m³"
      accuracy_decimals: 3
      device_class: water
      state_class: total_increasing
      filters:
        - multiply: 0.001

switch:
  - platform: restart
    name: "Restart metering-esp"

So this api service is not working and I don’t get it why. Do I have to define a helper in HA to retain the value and enter it for the “int” or anything other wrong? I read some other threads but still I did not figure out how it could work. My goal is to synchronize the value shown on the real meter and HA.

Any hints for me?

I don’t believe I have had any luck trying to change a sensor type once it was defined. IIRC when the energy dash was introduced, I wound up giving them another name and just creating a new sensor.

The aim of my yaml was not to change the sensor type. The aim was to set it’s init-value after a reboot of the esp for example. It must be damn simple, but actually I don’t get it…

You’ll need to store the value. To do this on the esp you can use either the number component or a global variable.

Thanks for the links and suggesting to save the values to the esp flash memory. I just wonder if this will survive a firmware update of the esp. With my - maybe a little naive - approach I tried to save the current value (total) to HA and send it back to the esp as a new init value after booting (could be solved by storing it in the flash memory) or even an update of the esp firmware (probably not solved by flash storage).

With the global variable, the restore value option

image

States that it is stored in rtc as well as flash.

Thanks for your example. I try to implement the write to flash story in a few days.