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.