Sensor Template: Last motion triggered

I have many motion sensors around the house to detect occupancy on each room. I were struggling to understand in which room someone is present or when (and if) someone was recently present.

So after lot of searching and adjusting, these are my sensors templates:

  • Last Motion Entity ID: report the Entity ID that has detected the last occupancy change
  • Last Motion Entity Name: report the Entity Name that has detected the last occupancy change
  • Last Motion Entity Elapsed: report the Elapsed time (minutes) from now to the last detected occupancy change

Just copy&paste this code on your configuration.yaml and replace the entities id you want to monitor on the set entities array.

  - platform: template
        friendly_name: "Last Motion Entity ID"
        value_template: >
            set entities = [
          {% for entity in entities %}
            {% if as_timestamp(entity.last_changed) == as_timestamp(entities | map(attribute='last_changed') | max) %}
              {{ entity.entity_id }}
            {% endif %}
          {% endfor %}
        friendly_name: 'Last Motion Entity Name'
        value_template: '{{ states[states.sensor.last_motion_entity_id.state].name }}'
        friendly_name: 'Last Motion Entity Elapsed'
        value_template: >
          {% set x = states('sensor.time') %}
          {{ (( as_timestamp(now()) - as_timestamp(states[states.sensor.last_motion_entity_id.state].last_changed)) / 60 ) | int }}
        unit_of_measurement: 'm'

Remember to reload your sensors configuration:

And finally add the new sensors to your Dashboard: