How to restore sensor value on boot?

I have the following template sensor which is updated via a push button, but every time the esp device reboots, the sensor state changes to “unknown”, is it possible to restore the last state on boot?

Sensor

  - platform: template
    name: "Last Fed"
    device_class: timestamp
    id: lastfed

State

image

I would probably solve it in Home Assistant.
Set up an automation that triggers on this sensor with condition not unknown.
Then save the value to an input text/date.

Thanks, tried that but without the “not unknown” which got reset as well, will apply your recomendation.

Is it possible to use time conversion in Esphome as in HA?, see below.

Esphome Button

  - platform: template
    name: "Just Fed"
    on_press:
      then:
        lambda: |-
          return id(lastfed).publish_state(id(hass_time).now().timestamp);

Which returns 2022-04-28T19:01:35.511787+00:00, but I would like it to be a human readable date/time as below.

{{ as_timestamp(states.sensor.last_fed.state) | timestamp_custom('%-m/%-d %-I:%M%p', True) }}

Which returns 4/28 4:20PM

Not sure if ESP-Home has those kind of conversion available, it is probably possible.
But if you go down the route I suggest then you can do it in HA with that template before saving it to a input text

1 Like

Can you show this update automation?

Hey @tom_l, Either of the following works.

On Click

    on_click:
    - min_length: 2s
      max_length: 4s
      then:
        lambda: |-
          return id(lastfed).publish_state(id(hass_time).now().timestamp);

On Press

    on_press:
      then:
        lambda: |-
          return id(lastfed).publish_state(id(hass_time).now().timestamp);

Here is the actual physical push button config

binary_sensor:
  - platform: gpio
    pin:
      number: 33
      mode:
       input: true
       pullup: true
      inverted: true
    name: "Action Button"
    id: button
    on_press:
      then:
      - script.stop: alarm_script
      - if:
          condition:
            switch.is_on: buzzer
          then:
            - switch.turn_off: buzzer
    on_click:
    - min_length: 2s
      max_length: 4s
      then:
        lambda: |-
          return id(lastfed).publish_state(id(hass_time).now().timestamp);
    - min_length: 5s
      max_length: 7s
      then:
        lambda: |-
          return id(bbshatch).publish_state(id(hass_time).now().timestamp);

Any idea how I can convert the timestamp in Esphome, just to avoid creating additional sensors in HA?

I would like this 2022-04-28T19:01:35.511787+00:00, to be this 4/28 4:20PM in the following lambda, and not have to do the conversion in HA.

Esphome Lambda
return id(lastfed).publish_state(id(hass_time).now().timestamp);

HA Conversion
{{ as_timestamp(states.sensor.last_fed.state) | timestamp_custom('%-m/%-d %-I:%M%p', True) }}