Last Motion template sensor with state unknown

This template sensor for Last Motion detection is working fine except at boot time it throws an error in the log. I believe this is because the Z-wave sensors are not up yet.

How can I fix it so I don’t get this error anymore?

    platform: template
      since_last_motion:
        friendly_name: 'Minutes since last motion'
        entity_id: sun.sun
        value_template: >
          {%- set sensors = [states.binary_sensor.pir_woonkamer, states.binary_sensor.pir_toilet, states.binary_sensor.pir_hal, states.binary_sensor.pir_badkamer, states.binary_sensor.door_trapkast] %}
          {% for sensor in sensors %}
            {% if as_timestamp(sensor.last_changed) == as_timestamp(sensors | map(attribute='last_changed') | max) %}
              {{ (( as_timestamp(now()) - as_timestamp(sensor.last_changed)) / 60 ) | int }}
            {% endif %}
          {% endfor %}

The error is: Could not render template Minutes since last motion, the state is unknown.

How about:

    platform: template
      since_last_motion:
        friendly_name: 'Minutes since last motion'
        value_template: >
          {% set sensors = [
                 states.binary_sensor.pir_woonkamer,
                 states.binary_sensor.pir_toilet,
                 states.binary_sensor.pir_hal,
                 states.binary_sensor.pir_badkamer,
                 states.binary_sensor.door_trapkast]
             |reject('none')|list %}
          {% if sensors|length > 0 %}
            {{ ((now() - sensors|map(attribute='last_changed')|max)
               .total_seconds()/60)|int }}
          {% else %}
            unknown
          {% endif %}

BTW, why did you have?

entity_id: sun.sun

That would cause this template sensor to only update when sun.sun updates. It should be perfectly capable of extracting the entity_id’s from this template and listen for those entities to change.

@pnbruckner Thanks Phil, I’ll be trying that!

The reason for entity sun.sun: it causes the sensor to update every minute (the sun sensor updates every minute). The entities in the template are motion sensors and they don’t update when there is no motion detected. So the first version of this template sensor would remain at 0 indefinitely, because it would only get updated right after motion was detected.