Trigger-Based Template Sensor + History

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?

In my original example, the attribute’s name is openings and so the attribute referenced by the template is also openings.

In your version, you changed the attribute’s name to motion. That’s fine but the attribute referenced in the template should also be motion but your example uses occupancy. That attribute name doesn’t exist so that’s why you’re not seeing any history of state-changes recorded other than the most recent one.

Change the word occupancy to motion.

{% set current = this.attributes.get('motion', []) %}

Well how stupid and silly can I feel right now. Ugh! Yep, that did it.

It’s always the little things that bite you in the ass lol.

Thanks for your help jumping in so soon. Much apreciated.

1 Like

You’re welcome!

No worries, it happens to us all. Overlook to change one thing somewhere and it either fails or does something unexpected. It often takes another pair of eyes to spot the culprit.