badr
(Badr)
January 7, 2025, 4:13pm
1
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.
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
badr
(Badr)
January 10, 2025, 7:04pm
3
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.
Hi everyone,
If this is a duplicate, please let me know. I was just reading and saw multiple questions about adding an availability sensor.
This can easily be achieved!
Step 1
In your z2m configuration, make sure you select MQTT version 5, this is needed for message retention. And make sure you have availability: enabled: true. This is disabled by default.
Restart if needed.
Now z2m publishes the network state (online/offline) of each device in it own topic, for instance: zigbee2mqtt/Kitch…
And then you could make a counter:
{{ integration_entities('mqtt')
| select('search', '_network_state')
| expand
| selectattr('state', 'eq', 'off')
| list
| count }}
badr
(Badr)
January 27, 2025, 2:19pm
5
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.