Last motion sensor triggered

Hi All,

Can anyone see why this isn’t working. it’s state is always ‘off’

  - platform: template
    sensors:
      template_last_motion:
        friendly_name: 'Last Sensor Triggered'
        value_template: >
          {%- set pirs = [states.sensor.sensor1, states.sensor.sensor2, states.sensor.sensor3, states.sensor.sensor4, states.sensor.pir1, states.sensor.pir2, states.sensor.pir3, states.sensor.pir4, states.sensor.pir5, states.sensor.pir6] %}
          {% for pir in pirs %}
            {% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
              {{ pir.name }}
            {% endif %}
          {% endfor %}

Is this under sensor: or binary_sensor:? If the latter, then that’s why. A template binary sensor is off unless value_template evaluates to the string true (which changed to all lower case.) I’m guessing you have it under binary_sensor: when you meant it to be under sensor:.

So thats what I have just realised, so i moved it, now it just says ‘unavailable’

I’m guessing the the template is causing an error. What happens if you copy that and put it in the Template Editor? What do you get?

BTW, you might want to take a look at this post:

Sorted. School boy error on my part. My sensors are binary i had defined them as sensors

working template;

          {%- set pirs = [states.binary_sensor.sensor1, states.binary_sensor.sensor2, states.binary_sensor.sensor3, states.binary_sensor.sensor4, states.binary_sensor.pir1, states.binary_sensor.pir2, states.binary_sensor.pir3, states.binary_sensor.pir4, states.binary_sensor.pir5, states.binary_sensor.pir6] %}
          {% for pir in pirs %}
            {% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
              {{ pir.name }}
            {% endif %}
          {% endfor %}

Glad you found the problem.

The post I pointed at has a slightly better/simpler way to do it. Also, in your solution you don’t need the as_timestamp() function. You can just compare the two Python datetime objects directly.