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
    sensors:
      last_motion_entity_id:
        friendly_name: "Last Motion Entity ID"
        value_template: >
          {%-
            set entities = [
            states.binary_sensor.movimentoingresso_occupancy,
            states.binary_sensor.movimentosala_occupancy,
            states.binary_sensor.movimentobagno_occupancy,
            states.binary_sensor.movimentostudio_occupancy
            ]
           %}
          {% for entity in entities %}
            {% if as_timestamp(entity.last_changed) == as_timestamp(entities | map(attribute='last_changed') | max) %}
              {{ entity.entity_id }}
            {% endif %}
          {% endfor %}
      last_motion_entity_name:
        friendly_name: 'Last Motion Entity Name'
        value_template: '{{ states[states.sensor.last_motion_entity_id.state].name }}'
      icon_template:mdi:motion-sensor
      last_motion_entity_elapsed:
        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: