Activate the last_seen
attribute via the Zigbee2MQTT interface. Go to Settings → Advanced → Last seen → Choose ISO_8601
Per default, the last seen
sensor is disabled for all Home Assistant entities. To enable the last_seen
attribute for all devices, add the following lines via VS Code in homeassistant → zigbee2mqtt → configuration.yaml
device_options:
legacy: false
homeassistant:
last_seen:
enabled_by_default: true
Now you must either restart Home Assistant or activate the entity manually: Go to Settings → Devices & services → Entities and adjust your Filter like this:
- Integrations: Select “MQTT”
- Status: Select “Disabled”
Then search for last seen
, click on select all
(right next to the filter button) and choose Enable selected
in the context menu when clicking on the three dots in the top right corner.
Now the last_seen
entity values should be visible, and you can use this new entity to detect an offline device. For example, by using this blueprint or by creating a template sensor like it is described here (related YT video).
{% set result = namespace(sensors=[]) %}
{% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %}
{% if 'last_seen' in state.entity_id and (states(state.entity_id) == 'unavailable' or ((as_timestamp(now()) - as_timestamp(states(state.entity_id))) > ((24 | int) * 60 * 60))) %}
{% set result.sensors = result.sensors + [state.name | regex_replace(find=' last seen', replace='') ~ ' (' ~ relative_time(strptime(states(state.entity_id), '%Y-%m-%dT%H:%M:%S%z', 'unavailable')) ~ ')'] %}
{% endif %}
{% endfor %}
{{ result.sensors | join('\n') | truncate(254, True) }}
The template sensor can be put somewhere on your dashboard or used in an automation. Following the automation I’m using:
alias: Notify when zigbee device goes offline using last_seen
description: ""
trigger:
- platform: state
entity_id:
- sensor.offline_zigbee_devices
from: null
to: null
for:
hours: 0
minutes: 10
seconds: 0
condition: []
action:
- service: notify.mobile_app_mi_8
metadata: {}
data:
title: |-
{% if not states('sensor.offline_zigbee_devices') %}
All Zigbee Devices Online!
{% else %}
The following Zigbee Devices are offline:
{% endif %}
message: >-
{% for entity in expand('sensor.offline_zigbee_devices') | map(attribute='entity_id') | list %}
{{ states(entity) }}
{% endfor %}
mode: single
I also recommend excluding the last_seen
sensors from the Logbook, because else the Logbook is flooded with changes. To do this, simply add the following lines in your configuration.yaml file:
logbook:
exclude:
entity_globs:
- sensor.*_last_seen
Brilliant guide – especially the part about how to enable last_seen without restarting Home Assistant. Thanks!