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"