ESPHome Timer for switch

Hello i need to create a timer where it will record the total ON time of a specific GPIO switch of ESPHOME. When the switch goes OFF it should record the time (hh:mm) on flash memmory (non volatile). Netxt time the switch is ON again it should continue from last value.

Also i would need a function where i can send an MQTT command (MQTT is already set up) where i would be able to erase this timer and start from 0.

Any help would be greatly appreciated.

This information is all available in home assistant.

If you (like me) need to have a timer regardless of whether HA is connected or not then the code snippet below may point you in the right direction. This is part of my standalone proofing cupboard that accepts commands and displays via a front panel, but is also controllable by HA.

For this to work some form of internet connection is still required.

# time form SNTP, this means that we need to be conect to the internet but
# not neccesarily HA
time:
  - platform: sntp
    id: sntp_time
    # count time in enabled state every minute
    on_time:
      - seconds: 0
        minutes: /1
        then:
          - lambda: |-
              if (id(enabled).state) {
                id(time_on_mins) += 1;
              }

Otherwise - as nickrout suggested just use HA to perform this function.

Just a quick idea:

You could use two global variables. A of time long for the total seconds the switch was on and one of type “int” for the timestamp the switch was turned on.

In the on_turn_on trigger of the switch set the global timestamp the current timestamp (from a time boject like zoogara posted it)) . In the on_turn_off trigger add the difference between the current timestamp and the “turn on”-timestamp to the total seconds global variable.

Set the store to flash option for global variables.