Rather than necro-post on an old thread, I decided to post a new conversation.
I am trying to get a card to show the last time the state was changed for a variety of sensors (some motion/presence, contact…etc) and I found some useful info in this thread.
The problem is that, while it appears to work in presenting the last sensor change, it only ever shows the last sensor change for the most recent sensor that changed, not the last time the state changed for ALL of my listed sensors so I suspect I am screwing something up.
Here is the trigger template sensor code in my configuration.yaml file (testing motion sensors to start)…
- trigger:
- platform: state
entity_id:
- binary_sensor.powder_room_occupancy
- binary_sensor.meross_presence_sensor_2_sensor_presence_motion
- binary_sensor.pantry_motion_occupancy
- binary_sensor.kitchen_motion_occupancy
from: 'off'
to: 'on'
sensor:
- name: Recent Motion
state: "{{ now().timestamp() | timestamp_custom() }}"
attributes:
motion: >
{% set current = this.attributes.get('occupancy', []) %}
{% set new = [{
"name": trigger.to_state.name,
"time": now().isoformat() }] %}
{{ (new + current)[:10] }}
When I use the following code in a Markdown card, I get that single entry for whichever sensor was the last one with a state change to “on”…
|Name||Time|
|:----|:-:|:----|
{% for x in state_attr('sensor.recent_motion', 'motion') | default([], true) -%}
|{{x.name}}||{{x.time|as_timestamp|timestamp_custom}}|
{% endfor -%}
That results in something like this (only shows the most recent entity with the state change to “on”)…
What I really want is to have a line for each of the sensors in the template with the last time motion was detected (state changed from “off” to “on”).
Anyone here know where I went wrong?