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/Kitchen motion sensor/availability
Step 2
You need to create a sensor for each of the devices. See MQTT Sensor - Home Assistant. But who has time for that!
Luckily, we have Jinja. Find the device name of your bridge, by default its Zigbee2MQTT Bridge. If you changed it, then also change it in the code below.
Copy and paste this code in âDeveloper toolsâ > âTemplate editorâ.
{% set id_zigbee_radio = device_id('Zigbee2MQTT Bridge') %}
mqtt:
binary_sensor:
{%- set ns = namespace(out=[]) -%}
{%- set device_ids = integration_entities('mqtt') | map('device_id') | unique | list -%}
{%- for device_id in device_ids -%}
{%- if device_attr(device_id, "via_device_id") == id_zigbee_radio %}
- device:
identifiers:
- {{ (device_attr(device_id, "identifiers")|first)[1] }}
enabled_by_default: true
entity_category: diagnostic
device_class: connectivity
icon: mdi:network
state_topic: zigbee2mqtt/{{ device_attr(device_id, "name") }}/availability
unique_id: {{ (device_attr(device_id, "identifiers")|first)[1] | replace('zigbee2mqtt_', '') }}_network_state
value_template: >
{{ "{{ " }} 'ON' if value_json.state == 'online' else 'OFF' {{ " }}" }}
name: network state
{%- endif %}
{%- endfor %}
Your output should look something like this.
mqtt:
binary_sensor:
- device:
identifiers:
- zigbee2mqtt_0x0000000000000000
enabled_by_default: true
entity_category: diagnostic
device_class: connectivity
icon: mdi:network
state_topic: zigbee2mqtt/Kitchen motion/availability
unique_id: 0x0000000000000000_network_state
value_template: >
{{ 'ON' if value_json.state == 'online' else 'OFF' }}
name: network state
- device:
identifiers:
- zigbee2mqtt_0x0000000000000000
enabled_by_default: true
entity_category: diagnostic
device_class: connectivity
icon: mdi:network
state_topic: zigbee2mqtt/Livingroom motion/availability
unique_id: 0x0000000000000000_network_state
value_template: >
{{ 'ON' if value_json.state == 'online' else 'OFF' }}
name: network state
Step 3
Copy output (!) and paste it in your configuration.yaml. Be sure to check your configuration.
Now click on âDeveloper toolsâ > âYAMLâ > âYAML configuration reloadingâ > âManually configured mqtt entities.â
Et voilĂ , every Z2M device has a sensor online/offline.
Hope this helps, kind regards,
- Ingrid
Edit: changed the sensor to a binary_sensor with device_class connectivity
