Prevent ESPHome sensor from incrementing pulses on connection loss

Hi there,

I am using an ESP8266 on my gas meter. Unfortunately, the wifi is rather bad so the ESP often loses connection. My ESPHome code looks like this:

  - id: gas_total_pulses
    type: int
    restore_value: true
    initial_value: '525984'  # hier kann der Gaszählerstand initialisiert werden

  - platform: gpio
    id: internal_pulse_counter
      number: GPIO5
      mode: INPUT_PULLUP
    name: "Gaszählerpulse"
      - delayed_on: 10ms
        - lambda: id(gas_total_pulses) += 1;

  - platform: template
    name: "Gaszählerstand"
    device_class: gas
    unit_of_measurement: "m³"
    state_class: "total_increasing"
    icon: "mdi:fire"
    update_interval: 5s
    accuracy_decimals: 2
    lambda: |-
      return id(gas_total_pulses) * 0.01;

The problem I am having is that if the current pulse output is high on connection re-establishing it is considered as new pulse even though the gas meter is not moving at all, see the example image:

In this example the counts only come from the connection re-establishing and are wrong.
How can I prevent this to happen? E.g. only increment if the previous state was low or something like this?

Thanks and best regards