Restarting WiFi on OpenWRT if the Link Goes Away

I put my WRT54G into a noisy electrical environment, and it seems to cause the wifi to fade out a couple times a week, sometimes permanently. (I did this after using a USB adapter on Windows proved too unstable.)

After some experimentation, this script below seems to do a reasonable job of keeping it up. Save it, and put it into the crontab. (You have to install the crond package.) The gateway is at 192.168.1.254.

#! /bin/sh

# Checks if the wifi conn is up.  If not, it tries to restart
# the wifi.  If that fails, then reboot.

if ping -c 1 192.168.1.254 > /dev/null
then
        echo nothing > /dev/null
else
        ifdown wifi
        ifup wifi
        killall wifi
        wifi
        /etc/init.d/S41wpa
        sleep 30
        if ping -c 192.168.1.254 > /dev/null
        then
                echo nothing > /dev/null
        else
                date >> /reboot.log
                reboot
        fi
fi

(Note that the date in reboot log will be the same, because the clock is not set right after booting.)