October 16, 2021

Raspberry, restart network, or reboot, at ping failure


Using a Raspberry Pi Zero(RPi), with wifi, I sometimes have problem that the WiFi connection is lost. This is due to that, at our boat, we are using the Teltonika RUT 240 router. The router just have one receiver/transmitter, LAN and WAN WiFi are shared, and in some use cases the WiFi will temporarily be disconnected. To restart the WiFi quick the following solution is used.

This post will cover a solution, a bash script, with inspiration from this blogpost, but with some fine tuning. 😉
 
Another way could be using the watchdog function, described here, with reboot.


Bash script
Start checking which interfaces you have and which you want to monitor. Use command

ip addr


In my case I wanted to monitor the interface "wlan0"


I created a file with name "interfaceCheck.sh", stored in folder "/usr/local/sbin", on the RPi and containing this code


# Check wifi connection...
ping home -I wlan0 -c4
# '$?' is the exit code of previous ping command
if [ $? != 0 ] # => failure
then
logger "No network connection, restarting wlan0"
# Take WiFi down
ip link set dev wlan0 down
sleep 5
# Take WiFi up
ip link set dev wlan0 up
fi


Explanation

I'm using the ping command, host "home"(or a IP adress), and are qualifying the interface. It could be that you have more than one interface active?


If the "ping" results in a failure then I'm first writing the text "No network connection, restarting wlan0" to syslog and then reactivating "wlan0".


Testing

The easiest way to test the script is to use a RPi with more than one interface. Force the "wlan0" down with the command


sudo ip link set dev wlan0 down


check status with "ip addr" and then run the script with 


sudo bash interfaceCheck.sh


check with  "ip addr" again and if you want to see the whole process use 


tail -n 20 /var/log/syslog


Automagic

With the built in scheduler you can run the "interfaceCheck.sh" program, for example, every 5 minutes, using the command 


crontab -e


and adding the line


*/5 * * * * sudo bash interfaceCheck.sh


Round up

Reboot ?

It could be that you prefer to reboot the RPi instead, at a interface failure, and then you just change the last lines in the script to 


then
logger "No network connection, rebooting"
# Reboot
sudo reboot now
fi


How many restarts/reboots are done ?

Use the command 


cat  /var/log/syslog | grep "No network"


No comments:

Post a Comment

Feel free to leave a comment ! ... but due to a lot of spam comments I have to moderate them. Will reply ASAP !