Restart Z2M addon when at least 5 devices are unavailable

It’s pretty much all in the title, don’t know how to trigger the automation…

For context, from time to time, z2m plugin stops working, my remotes have no effect, my thermometers show unavailable instead of their temperature… Restarting z2m from it’s own menu seems to do the trick, I guess it’s getting lost in the USB communication, probably because my PVE has paused the VM for a second to take a snapshot of HAOS… Regardless, I would like to add an automation to restart Z2M plugin if it’s entities are offline. Some entities might not show up as unavailable but when 5 of them are offline then it’s most probably this issue…

Can’t seem to find the “unavailable” state when building the automation with the GUI. I suspect I should first build a numeric counter counting the number of mqtt stuff that is offline, but that too I’d need help for.

If someone has the knowledge please feel free to help, I’ll be looking at the doc meanwhile but sadly “Filter” seems to mean some numeric transformation and not a search for entities so it’s not so intuitive for me.
Thanks in advance.

I get alerts using this sensor when zigbee2mqtt goes offline:

Sensor:

mqtt:
  binary_sensor:
    - name: "Z2MQTT Status"
      device_class: connectivity
      state_topic: "zigbee2mqtt/bridge/state"
      payload_on: 'online'
      payload_off: 'offline'
      qos: 1

Automation:

  trigger:
    platform: state
    entity_id: binary_sensor.z2mqtt_status
    from: 'on' 
    to: 'off'
    for: 60 # seconds
  action:
    - service: <do your reload here>

It depends how zigbee2mqtt is failing for you though. If it can still contact the mqtt broker this may not work.

Try creating the sensor and check it’s state next time you have the issue.