Zigbee2MQTT offline devices sensor

I’ve created a sensor for offline zigbee2mqtt devices to show in my network dashboard, the sensor relies on pyscript, subscribes to availability topics and counts the offline devices.
image

pyscript code:

import json
import re

zigbee2mqtt_offline_devices = {}

@state_trigger("sensor.offline_zigbee_devices")
def update_icon():
  sensor.offline_zigbee_devices.icon = "mdi:zigbee"
  sensor.offline_zigbee_devices.friendly_name = "Offline Zigbee Devices"
  sensor.offline_zigbee_devices.state_class = "measurement"

@mqtt_trigger("zigbee2mqtt/+/availability")
@task_unique("zigbee2mqtt_availability", kill_me=True)
def zigbee2mqtt_availability(topic,payload):
    offline = 0
    offline_devices = []
    device = re.search('zigbee2mqtt/(.*)/availability', topic).group(1)
    if(json.loads(payload)['state'] == "offline"):
        zigbee2mqtt_offline_devices[device] = 1
    else:
        zigbee2mqtt_offline_devices[device] = 0

    for dev in zigbee2mqtt_offline_devices:
        if zigbee2mqtt_offline_devices[dev] == 1:
            offline_devices.append(dev)
        offline += zigbee2mqtt_offline_devices[dev]
    sensor.offline_zigbee_devices = offline
    sensor.offline_zigbee_devices.devices = offline_devices
1 Like

Works great. I had to replace

if(json.loads(payload)['state'] == "offline"):

by

if payload == “offline”:

1 Like

Interesting! I’m receiving availability as {'state':'offline'} json.
You might wanna drop import json from your script then.

Why did you choose to monitor an MQTT topic using pyscript? An alternative approach would be to use a MQTT sensor, which is naive to Home Assistant.

And then you could make a counter:

{{ integration_entities('mqtt') 
  | select('search', '_network_state') 
  | expand 
  | selectattr('state', 'eq', 'off')
  | list 
  | count }}

That would’ve created a separate entity for each device, I have 150+ devices and only need to know which devices are offline. One sensor does the job without cluttering my system.
I also don’t need to add new sensors whenever I add a new device, this way it’s completely dynamic.