Restore state of trigger-based template after reload

Hi, I’m trying to create a sensor that calculates distance travelled by a device_tracker entity - in this particular example my car. The calculation part is easy - it fires whenever gps position updates, calculates distance between 2 points and then adds it to distance already travelled (stored by the very same sensor). That part’s easy.

What I have problem is is restoring the state after templates are reloaded. As it uses it’s own value in the template whenever I reload templates it gets reset to unknown which is then defaulted to 0 in float conversion.
I tried to add another state trigger that detects the sensor going to NULL state (also tried “NULL” and “unknown”) and then restore “from_state” value, but it doesn’t work. Am I doing something wrong or is it just not possible without creating another entity like input_number that would hold the state when templates are reloaded?

template:
  - trigger:
      - platform: state
        entity_id: device_tracker.leaf
        id: "tracker"
      - platform: state
        entity_id: sensor.leaf_przebyty_dystans
        to: NULL //Tried also "NULL" and "unknown"
        id: "reload"
    sensor:
      - name: "Leaf - przebyty dystans"
        state: >-
          {% if trigger.id == "tracker" %}
            {% set delta_lon = (trigger.from_state.attributes.longitude | float(0) - trigger.to_state.attributes.longitude | float (0)) | round(7) %}
            {% set delta_lat = (trigger.from_state.attributes.latitude  | float(0) - trigger.to_state.attributes.latitude  | float (0)) | round(7) %}
              
            {% set q = cos(states.device_tracker.leaf.attributes.longitude | float(0) ) %}
            {{ (float(states('sensor.leaf_przebyty_dystans'),0) + (sqrt(delta_lat**2 + (q**2 * delta_lon**2)) * 1.852 * 60)) | round(4) }} // This is where the sensor calls it's own state
          {% elif trigger.id == "reload" %}
            {{states('trigger.from_state')}}
          {% else %}
            0
          {% endif %}
          
        unit_of_measurement: "km"
        state_class: "total_increasing"

Add triggers to detect when Home Assistant starts and Template entities are reloaded.

    - platform: event
      event_type: event_template_reloaded
    - platform: homeassistant
      event: start

Modify your template to handle the case when the automation is triggered by either of the two triggers.

That’s what I use to ensure my Trigger-based Template Sensors report valid values on startup and whenever Reload Template Entities is executed.

1 Like

Thanks, but this is not the merit of the problem. I want the entity to restore it’s last state before the reload, but if I call it’s last state it is going to be null. Is there a template to invoke last valid value from history? The issue is the sensor uses its own value in calculation, so I can’t just use other values to restore the correct state

Template Sensors don’t work like that. The values they report are based on evaluating their template. That’s why a Trigger-based Template Sensor has no value on startup or on reload unless those two events are included in its trigger. When triggered, it re-computes its value and there are no templating functions to retrieve an entity’s previous value(s) from its history (database).

One thing you can try, is when triggered due to reload or restart, it gets its own existing value (in the state machine) using states('sensor.leaf_przebyty_dystans').

I haven’t tried this myself so I can’t guarantee it will work. It’s unlikely to work the first time a sensor is created because the state machine has no existing value for it but it might work the for the next reload. I doubt it will work for a restart.

Anyway, give it a try (reloading and restarting several times to see is, and when, it works) but if it fails, or only works partially, there’s no other workaround that I know of for the fundamental issue that Trigger-based Template Sensors always compute their value.


EDIT

Be advised that this behavior has changed since I made that statement over a year ago. The state value of a Trigger-based Template Sensor is restored on startup.

FWIW, this is an example of why users should rely on recent posts for information. Anything over a year old (perhaps even just a few months old) might be outdated due to Home Assistant’s rapid evolution.