Flaky WiFi dongle toggle script

By | 7 Apr 2024

After moving to a new place, I had to put my ADS-B handling Raspberry Pi 2B into a cupboard far from any network connection. So I’ve plugged in a cheap USB WiFi dongle and connected it to my WiFi.

However, I don’t know whether it’s the dongle or something specific to the RasPi2’s USB implementation, but the WiFi connection drops every once in a while. And for some reason, it doesn’t automatically join the network again most of the times. This meant having to go to the cupboard and restarting the RasPi manually – about twice a day minimum.

After a few weeks of this, I was fed up and came up with this script:



echo -n "$(date +"%Y-%m-%d %H:%M:%S") - "
ping -4 -c 1 -I $INTERFACE $HOST >/dev/null

if [ $RESULT -ne 0 ]; then
    echo "PING failed!"
    echo "  - Toggling WiFi OFF"
    nmcli radio wifi off
    sleep 5
    echo "  - Toggling WiFi ON"
    nmcli radio wifi on
    echo "OK"

This tries to ping the router and if it fails, just turns the WiFi dongle off, waits for 5 seconds and turns it back on again. This will trigger NetworkManager to search for known networks and rejoin my WiFi.

I’ve added this script to my root user’s crontab to run every 5 minutes:

*/5 * * * * /home/mbirth/wifi-watch.sh >> /tmp/wifi-watch.log 2>&1
01 21 * * * rm /tmp/wifi-watch.log

(All output of my script is logged into /tmp/wifi-watch.log and the second crontab line deletes this log at 21:10 every day so it doesn’t grow indefinitely.)

I didn’t have any issues with the WiFi connection since this script is running.

Leave a Reply