Persisting old state of template sensor

Hi,

I have PIR sensor in my living room which sends movement detection status via MQTT. Now I am trying to show the time when the presence has been detected the last time by using the template sensor. My template sensor currently looks like this:

  - platform: template
    sensors:
      livingroom_lastmove:
        entity_id: binary_sensor.livingroommotion
        value_template: >-
          {% if is_state('binary_sensor.livingroommotion', 'on') %}
            {{ now() }}
          {% else %}
            {{ states.template.livingroom_lastmove }}
          {% endif %}

When PIR sensor is in the ‘on’ state, the state of livingroom_lastmove sensor is shown correctly but as soon as PIR changes to ‘off’ I lose the state of livingroom_lastmove.
How should I configure this in order to preserve the template sensor state?

Replace this:

            {{ states.template.livingroom_lastmove }}

with this:

            {{ states.sensor.livingroom_lastmove.state }}

or with this:

            {{ states('sensor.livingroom_lastmove') }}

Hi,

I’ve already tried all the combinations but seems that sensor value has already been lost at that point.

I don’t currently have the time to confirm it but I believe you are correct. I have a foggy recollection of attempting something similar with a template sensor and encountered a problem.

And were you able to overcome that? I still cannot.

No. I gave up trying.

In your case all you need to do is change the template. It appears all you want this Template Sensor to report is the last time motion was detected in the living room. That information is stored in the binary_sensor’s last_changed property.

  - platform: template
    sensors:
      livingroom_lastmove:
        value_template: "{{ states.binary_sensor.livingroommotion.last_changed.timestamp() | timestamp_custom('%b-%d %H:%S')}}"

The template uses timestamp_custom to format the date and time’s appearance (example: Jul-19 08:24).

You could simply use the following template but the date and time will be shown in the standard (less pretty) format.

value_template: "{{ states.binary_sensor.livingroommotion.last_changed }}"