I prefer to disable most of the network auto configuration and connection management daemon stuff and deal with it myself. Here's a (bash) script that will keep the connection up as long as the network is there and you do not have a glitchy wifi driver or power issues; the idea is to ping the router every N seconds, and if that fails, re-connect:
#!/bin/bash
# make sure we aren't running already
what=`basename $0`
for p in `ps h -o pid -C $what`; do
if [ $p != $$ ]; then
exit 0
fi
done
# source configuration
. /etc/wifi.conf
exec 1> /dev/null
exec 2>> $log
echo $(date) > $log
# without check_interval set, we risk a 0 sleep = busy loop
if [ ! "$check_interval" ]; then
echo "No check interval set!" >> $log
exit 1
fi
startWifi () {
dhclient -v -r
# make really sure
killall dhclient
iwconfig $wlan essid $essid
dhclient -v $wlan
}
ifconfig $eth down
ifconfig $wlan up
startWifi
while [ 1 ]; do
ping -c 1 $router_ip & wait $!
if [ $? != 0 ]; then
echo $(date)" attempting restart..." >> $log
startWifi
sleep 1
else sleep $check_interval
fi
done
So, /etc/wifi.conf
in this case might contain:
router_ip=192.168.0.1
log=/var/log/wifi.log
wlan=wlan0
eth=eth0
essid=someNetwork
check_interval=5
This all presumes an open unencrypted network (if otherwise, you will have to add the appropriate commands). I've used this approach on various linux machines, including the pi, and it works flawlessly; it will keep a system online indefinitely, even if it periodically goes to sleep (which the pi cannot anyway).
A decent check interval is 3-5 seconds; this activity will not significantly impact system resources at all.
You absolutely do need to disable the network auto-configuration first, . including ifplugd
and other networking daemons, or this will interfere with your efforts:
How can I disable autoconfigured networking on Raspbian?
I in fact used apt-get remove ifplugd
.
To start networking at boot (since I use the pi headless), I have this set to run on raspbian from /etc/rc.local
:
wifi_mod=`lsmod | grep 8192cu`
if [ "$wifi_mod" ]; then
echo "Starting wifi..."
/usr/bin/nice -n -10 /usr/local/bin/wifi &
else
echo "Starting ethernet..."
/sbin/ifconfig eth0 up
/sbin/dhclient eth0
fi
/usr/local/bin/wifi
is the script. If you don't know what nice
is for, read man nice
.
The point of the if
is that if my wifi dongle is plugged into the pi, the 8192cu module will be loaded by the kernel at this point -- so wifi should start. If not, then it's assumed that the ethernet is plugged in and should be used (if it is isn't, dhclient will just crap out and there is no network access).
For this to work you will probably have to
So, this gets a headless pi onto the network at boot and keeps it there. If you wanted a way to switch to eth while running without logging in, you could do something with udev rules for pulling the wifi dongle out.