Online client detection

Hello everyone,
I am in need of a (b)ash script that basicly makes the online status of some devices available to my MQTT broker. It controls some of my HomeAssistant instance. I know there is a HomeAssistant Plugin for that but thats not really usable since I would have to put my admin credentials on the IoT-Box...

Anyways I came up with a script that extracts the mac adresses from associated interfaces:

#!/bin/ash

1=false
2=false

for interface in `iw dev | grep Interface | cut -f 2 -s -d" "`
do
 for mac in $maclist
  do
    if [ "$mac" == "44:00:bc:57:de:21" ]; then
        echo "dev1 is online."
        1=true
    fi
    if [ "$mac" == "dd:fd:24:ef:66:4b" ]; then
        echo "dev2 is online."
        2=true
    fi
  done
done
if ! $1; then
    echo "dev1 is offline".
fi
if ! $2; then
    echo "dev2 is offline".
fi

This can then be pushed to mqtt or whatever. Anyways it it quite easy to call it on any new connection appearing from /etc/dnsmasq.conf with the line dhcp-script=/tmp/clients.sh.
But I don't want it to run all day so would there be a similar trick to get a callback on a disconnecting client?

Or am I overthinking this and there is a different simple way?
Thanks in advance (and I btw hope this is the correct subforums)

You can listen to ubus events for your own interfaces.

https://openwrt.org/docs/techref/ubus

For wireless clients, consider following the hostap and/or wpa_supplicant logs.

For that matter, you can send your logs to another host and process them there, as well as getting the benefit of logs stored on nonvolatile memory. There should be enough information there for both your interfaces as well as wireless clients.

I'm not sure about notifications. Maybe you could modify hostapd to send ubus notifications?

Regarding parsing iw output, it may be better to use ubus and JSON format, e.g.
ubus call iwinfo assoclist '{ "device": "wlan0" }'
and optional JSON parsing using jsonfilter.