How to automatically reconnect to the WiFi in Raspbian
- 2 minutes read - 330 wordsAt home, we have been connecting the garden, lights, doors, the TV, air conditioner, and even Higgs, our pet rabbit, but this last thing will be another post. We have a large variety of devices and sensors, with several Raspberry Pi 2 among them, connected to the WiFi network. Many times we have had to manually reboot the Raspis after a network connection outage because it looks like dhcpcd does not manage this situation.
After looking for a solution and finding some more or less complex solutions, my favorite one, for its simplicity, is this proposal by Alex Bain. So, I have adapted it to work with the distro I’m currently using, which is Raspbian Buster.
You will only need to create a script named /usr/local/bin/wifi_rebooter.sh, with a similar code to the one below, you may need to change the ping address and the interface name, which is typically called wlan0:
#!/bin/bash
# The IP for the server you wish to ping (192.168.1.1 is typically your router)
SERVER=192.168.1.1
# Only send two pings, sending output to /dev/null
ping -c2 ${SERVER} > /dev/null
# If the return code from ping ($?) is not 0 (meaning there was an error)
if [ $? != 0 ]
then
printf '#' >> /tmp/wirelesscount
ln=$(stat --printf="%s" /tmp/wirelesscount)
if [ $ln -gt 2 ]
then
# third time reboot raspi if everything else fails
cat /dev/null > /tmp/wirelesscount
reboot now
fi
# Restart the wireless interface
ip link set wlan0 down
ip link set wlan0 up
else
# reset count if it worked
cat /dev/null > /tmp/wirelesscount
fi
Then you give the script run permission:
sudo chmod +x /usr/local/bin/wifi_rebooter.sh
And you add a 5 minutes interval to run it in /etc/crontab, so it will restart the network interface whenever the connection is lost:
*/5 * * * * root /usr/local/bin/wifi_rebooter.sh
Now I no longer need to manually restart all our Raspberry Pi devices every time the connection has been broken for some time.
Makers gonna make.