Capture last non-zero state of sensor in another sensor

I’ve spent way to much time searching for an example of how to do this and it seems to me that a template-based trigger is the answer but I just can’t get it to work.

Scenario is that I have a sensor for my car that often reports as ‘0’ likely because it has gone to sleep and Kia no longer polls a real value for it. I’d like to create and update another sensor based on the last non-zero value. It’s not a perfect solution but it’s the only thing I can think of.

My code is:

  - triggers:
      - trigger: state
        entity_id: sensor.sportage_ev_range
        condition:
          - condition: template
            value_template: "{{ states('sensor.sportage_ev_range') > '0' }}"
    sensor:
      - name: Sportage EV Range Real
        state: '{{ trigger.to_state.state }}'
        device_class: distance
        unit_of_measurement: 'KM'

This may or may not work but it also throws the following error after a configuration check or template reload:

 Invalid config for 'template' at template.yaml, line 1: two or more values in the same group of exclusion 'to' '<to>', got None
* Invalid config for 'template' at template.yaml, line 1: expected str for dictionary value 'not_to', got None
* Invalid config for 'template' at template.yaml, line 12: 'device' is an invalid option for 'template', check: sensor->0->device
* Invalid config for 'template' at template.yaml, line 2: 'condition' is an invalid option for 'template', check: condition

I tried using:

- triggers:
    - trigger: state
      entity_id: sensor.sportage_ev_range
      not_to: 
        - '0'
  sensor:
    - name: Sportage EV Range Real
      state: '{{ trigger.to_state.state }}'
      device_class: distance
      unit_of_measurement: 'KM'

While that didn’t throw any errors it also seemed to be updating the new sensor even when the source sensor was 0.

So what am I doing wrong here or am I barking up the wrong tree entirely?

template:
  - sensor:
      - name: Sportage EV Range Real
        state: >
          {% if states('sensor.sportage_ev_range')|float(0) > 0 %}
            {{ states('sensor.sportage_ev_range') }}
          {% else %}
            {{ this.state }}
          {% endif %}
        device_class: distance
        state_class: measurement # <- If you want long term stats
        unit_of_measurement: 'km' 

Please take note of the unit letter case, it must match one of the units listed in the device class docs exactly, https://www.home-assistant.io/integrations/sensor#device-class

{{ this.state }} is the previous value. Which will be kept if the returned value is 0 (or less, or unavailable).

The template will update whenever sensor.sportage_ev_range changes, no need for a trigger.

Wow, thanks so much. I’ll give this one a shot!