How to maintain state value over reboot?

I have created a state from a rest post (REST API | Home Assistant Developer Docs) to hold the value of a battery charge (from a garmin watch). Every 30mins or so the garmin watch updates the state successfully through the REST API.

When homeassistant reboots, the state is not available until the watch next provides an update.

Is it possible to restore the state from the history database?

Should I create a custom sensor integration to achieve this? I found some instructions at example-custom-config/custom_components/example_sensor at master · home-assistant/example-custom-config · GitHub but would prefer not to go diwn this path unless I have to…?

Hello zilched,

The way to do that is write an automation that triggers on the homeassistant_start action, and update the sensor when HA starts. You cannot ‘store’ the value, you have to refresh it.

Thank you @Sir_Goodenough … I cannot pull data from the watch, it is currently pushing to hass. Would the automation have access to the state history so I could refresh from there?

If not, I think the best option could be to refresh the sensor every five minutes (ie make a REST POST call to hass every five minutes. Really just looking for a way to minimise the number of these calls)

Otherwise… I could always store the value in a separate microservice somewhere outside hass and ask hass to get from there… but seems overkill !?

I would have to look at bit more, but with an integration, you can have a restore entity which maintains its value between reboots. I would wonder if one of the helper entities does that, that you could use to push the value to and use this then with a template sensor for your actual entity. Getting from state history can be tricky.

You can make a Trigger-based Template Sensor that simply duplicates the value of the sensor that reports battery level.

A Trigger-based Template Sensor’s state survives a restart.

Example

template:
  - trigger:
      - platform: state
        entity_id: sensor.your_garmin_watch_battery
        not_to:
          - unavailable
          - unknown
    sensor:
      - name: Watch Battery
        state: '{{ trigger.to_state.state }}'
        device_class: battery

Either a template as already mentioned or an automation perhaps which copies the value into a input_number entity would be my go-to solutions.

Thank you all - the template sensor is working :+1:

Final code in case it helps anyone in the future - the sensor I create from the POST request is called sensor.venu2_battery and the trigger sensor is called sensor.venu2_battery_display

template
  - trigger:
    - platform: state
      entity_id: sensor.venu2_battery
      not_to:
        - unavailable
        - unknown
    sensor:
    - name: venu2_battery_display
      device_class: battery
      state: '{{ trigger.to_state.state }}'