Creating template sensor to show devices that have not been in contact for some time

Hi community,

I’m try to create a template sensor that looks at the last seen sensors in HA for zwave devices but the below does not seem to work. It’s supposed to add the sensor to the output if it’s not been seen for over 48 hours. But no devices show despite them being not seen for longer than the threshold. Any help would be appreciated code below.

{% set threshold = 172800 %}
{% set error_devices = [] %}

{% for entity in states.sensor if entity.entity_id.endswith('_last_seen') %}
  {% set last_seen_str = states(entity.entity_id) %}

  {% if last_seen_str is not none %}
    {% set last_seen = last_seen_str | as_datetime %}
    {% if last_seen is not none %}
      {% set time_diff = (now() - last_seen).total_seconds() %}

      {% if time_diff > threshold %}
        {% set error_devices = error_devices + [entity.entity_id] %}
      {% endif %}
    {% endif %}
  {% endif %}
{% endfor %}

{% if error_devices | length > 0 %}
  Error: {{ error_devices | join(', ') }} not seen in 48 hours
{% else %}
  All devices are active
{% endif %}

Use namespace to define the variable (error_devices) whose value will be changed inside the for-loop. It ensures the value is preserved outside the for-loop.

{% set threshold = 172800 %}
{% set ns = namespace(error_devices = []) %}

{% for entity in states.sensor if entity.entity_id.endswith('_last_seen') %}
  {% set last_seen_str = states(entity.entity_id) %}

  {% if last_seen_str is not none %}
    {% set last_seen = last_seen_str | as_datetime %}
    {% if last_seen is not none %}
      {% set time_diff = (now() - last_seen).total_seconds() %}

      {% if time_diff > threshold %}
        {% set ns.error_devices = ns.error_devices + [entity.entity_id] %}
      {% endif %}
    {% endif %}
  {% endif %}
{% endfor %}

{% if ns.error_devices | length > 0 %}
  Error: {{ ns.error_devices | join(', ') }} not seen in 48 hours
{% else %}
  All devices are active
{% endif %}

Any progress to report?

Thanks that works now!

1 Like