What would be the best way to create template sensor of old value from another sensor.
I have sensor A which has a numeric* value. Whenever this value changes to another numeric value, I want to store the old/from nuumeric value in sensor B.
*ofc I know, that every value is a string, but wanted to point out, that I’m not interested in changes from sensor A to or from unknown/unavailable/whatever, but only need the last numeric number from this source sensor.
Starting point template sensor, so it get restored after restart for the case that A is not available and because there are no changes at this point of time.
But then? I thought about storing every change in the attribute and then iterate over so finde the last numeric state, etc. etc. But I assume, that is far easier and I only can’t see it.
Tested this: I think it does what you want, where B is a “latching” version of A, retaining numeric values across unavailability; and C is the prior version of B:
template:
- trigger:
- platform: state
entity_id: sensor.a
to: null
sensor:
- name: B
state: >
{% if trigger.to_state.state|float('x') is number %}
{{ trigger.to_state.state }}
{% else %}
{{ this.state }}
{% endif %}
- trigger:
- platform: state
entity_id: sensor.b
to: null
sensor:
- name: C
state: >
{% if trigger.from_state.state|float('x') is number %}
{{ trigger.from_state.state }}
{% else %}
{{ this.state }}
{% endif %}
The to: null prevents it triggering off changed last_changed attributes as described here.
Thanks again. Will test it. Thought about a helper as well and was only wondering, if it is possible with only one template sensor.
Know this null. But is it really needed for such “internal” attributes as well? Thought it is only needed if I want to suppress triggering of “real” attributes. If yes, every sensor would trigger on every last_updated as well I was not aware that this is happening.
Happy to be proved wrong, but I don’t think so. From your example:
Let’s assume A has this values in a time row:
1, unavailable, 2, unavailable, 2, unavailable
Now assume a 3 comes in next. Where is the prior 2 stored?
Try it without and see what happens. In my testing, it was necessary, but I was using all sort of faked-up sensors with an input_boolean as an unavailability switch.