swizzard
Posts: 28
Joined: Wed Jul 25, 2012 11:47 pm
Location: Brooklyn, NY

Persistent/reconnecting wifi

Tue Aug 27, 2013 4:36 pm

I have a wifi adapter for my Pi (NetGear, Inc. WNA1000M 802.11bgn [Realtek RTL8188CUS]), and it works just fine, except sometimes it just disconnects from my wifi network. I suspect this has at least as much to do with my network cutting out as it does with the adapter itself, but regardless, sometimes my Pi disconnects, and then I have to manually restart the whole Pi, which is a pain in the butt if I'm at a coffeeshop or wherever. So, two questions:
1) Is there a better way to reconnect to a wifi network than restarting the whole Pi? I don't really know that much bash. Will

Code: Select all

ifup wlan0
do it?
2) Is there a script that will persistently check if my Pi's connected and, if it's not, try to reconnect? As I said, I don't know all that much bash, and the wifi-related Python packages I've found seem pretty beta and/or ill-documented. I'd like something like

Code: Select all

def persist():
	try:
		#check connection
		r = requests.get("http://www.google.com")
	except requests.exception.ConnectionError:
		##do something to restart the wifi
		persist()
while True:
persist()
time.sleep(6000)
Thanks!

paulv
Posts: 558
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Persistent/reconnecting wifi

Tue Aug 27, 2013 6:58 pm

You stumbled on something that is not uncommon.
You're almost there with your idea.

Here is a solution in Python that I use:

Code: Select all

import subprocess
WLAN_check_flg = False

def WLAN_check():
    '''
    This function checks if the WLAN is still up by pinging the router.
    If there is no return, we'll reset the WLAN connection.
    If the resetting of the WLAN does not work, we need to reset the Pi.

    '''

    ping_ret = subprocess.call(['ping -c 2 -w 1 -q 192.168.1.1 |grep "1 received" > /dev/null 2> /dev/null'], shell=True)
    if ping_ret:
        # we lost the WLAN connection.
        # did we try a recovery already?
        if WLAN_check_flg:
            # we have a serious problem and need to reboot the Pi to recover the WLAN connection
            subprocess.call(['logger "WLAN Down, Pi is forcing a reboot"'], shell=True)
            WLAN_check_flg = False
            subprocess.call(['sudo reboot'], shell=True)
        else:
            # try to recover the connection by resetting the LAN
            subprocess.call(['logger "WLAN is down, Pi is resetting WLAN connection"'], shell=True)
            WLAN_check_flg = True # try to recover
            subprocess.call(['sudo /sbin/ifdown wlan0 && sleep 10 && sudo /sbin/ifup --force wlan0'], shell=True)
    else:
        WLAN_check_flg = False
My code runs that every 10 minutes, but you can also let cron do that for you.
Alternatively, you can convert this code into a shell script.

Have fun!
Last edited by paulv on Fri Aug 30, 2013 7:14 am, edited 1 time in total.

pjc123
Posts: 913
Joined: Thu Mar 29, 2012 3:37 pm
Contact: Website

Re: Persistent/reconnecting wifi

Thu Aug 29, 2013 1:15 pm

Here is how I fixed the problem (or more accurately, circumvented the problem):

I was having an issue when I upgraded from a Model B Rev 1 board to a Model B Rev 2 board with my TP-Link TL-WN722N, where it would only intermittently get an ip address at boot on my headless pi. I suspect that the problem was related to the fact that the wifi dongle setup program did not have enough time to finish setting up the network during the boot process, probably related to the faster speed of the newer board at boot or the switch from the Soft float version of Wheezy to the hard float version of Raspbian. Moot point anyway, as I could not get it to work consistently, and the only way to resolve it without hooking up a monitor and keyboard, was by reseating the wifi dongle. However, that is neither convenient when you are hundreds of feet or miles away from the pi, nor a recommend practice with the pi. Since I was running headless, I needed a way to reconnect in software. The following is how I automated that process. This should also work if you are having issues reconnecting when turning the router off, then turning it back on, or similarly moving out of range of the router, then moving back into range.

I found the following program written by Kevin Reed. You can give it a try, and if it works for you, you are golden, but it did not work for me for a couple of reasons. I have listed the changes that I made to the program, and now it works flawlessly on two headless pis:

http://rpi.tnet.com/project/scripts/wifi_check

1) The first problem was that some of the commands were not working. The thing I had to do was to enter the full path to all the commands. There are other ways around this but this does the trick:

BEFORE:
ifdown
ifup

AFTER:
/sbin/ifdown
/sbin/ifup

2) The second problem was that it was not detecting that my ip address was absent, so it never reset the interface, and therefore it did nothing. I changed the method to check for no network connection by doing a "ping" instead of an "ifconfig".

BEFORE:

Code: Select all

# We can perform check
echo "Performing Network check for $wlan"
if ifconfig $wlan | grep -q "inet addr:" ; then
    echo "Network is Okay"
else
    echo "Network connection down! Attempting reconnection."
    ifdown $wlan
    sleep 5
    ifup --force $wlan
    ifconfig $wlan | grep "inet addr"
fi
AFTER:

Code: Select all

# We can perform check
echo "Performing Network check for $wlan"
/bin/ping -c 2 -I $wlan $pingip > /dev/null 2> /dev/null
if [ $? -ge 1 ] ; then
    echo "Network connection down! Attempting reconnection."
    /sbin/ifdown $wlan
    sleep 5
    /sbin/ifup --force $wlan
else
    echo "Network is Okay"	
fi
3) The third thing I did was to make the ip address to check for a variable. You can use whatever you want as an ip address, but I use my router's address.

BEFORE:
Not Applicable.

AFTER:
# Which address do you want to ping to see if you can connect
pingip='192.168.1.1'

4) If you are not running as root, you might have to add some "sudos" in the script, the cron, etc.

HERE IS THE COMPLETE MODIFIED VERSION:
DON'T FORGET TO CHANGE THE "pingip" VALUE TO WHAT WORKS FOR YOU (router address, internal/external address, etc.).
DON'T FORGET TO CHANGE THE "wlan" VALUE TO WHAT WORKS FOR YOU (wlan0, wlan1, eth0, etc.).

Code: Select all

#!/bin/bash
##################################################################
# NOTE! THIS IS A MODIFIED VERSION OF THE ORIGINAL PROGRAM
# WRITTEN BY KEVIN REED.  TO GET THE ORIGINAL PROGRAM SEE
# THE URL BELOW:
#
# A Project of TNET Services, Inc
#
# Title:     WiFi_Check
# Author:    Kevin Reed (Dweeber)
#            [email protected]
# Project:   Raspberry Pi Stuff
#
# Copyright: Copyright (c) 2012 Kevin Reed <[email protected]>
#            https://github.com/dweeber/WiFi_Check
#
# Purpose:
#
# Script checks to see if WiFi has a network IP and if not
# restart WiFi
#
# Uses a lock file which prevents the script from running more
# than one at a time.  If lockfile is old, it removes it
#
# Instructions:
#
# o Install where you want to run it from like /usr/local/bin
# o chmod 0755 /usr/local/bin/WiFi_Check
# o Add to crontab
#
# Run Every 5 mins - Seems like ever min is over kill unless
# this is a very common problem.  If once a min change */5 to *
# once every 2 mins */5 to */2 ... 
#
# */5 * * * * /usr/local/bin/WiFi_Check 
#
##################################################################
# Settings
# Where and what you want to call the Lockfile
lockfile='/var/run/WiFi_Check.pid'
# Which Interface do you want to check/fix
wlan='wlan0'
# Which address do you want to ping to see if you can connect
pingip='192.168.1.1'
##################################################################
echo
echo "Starting WiFi check for $wlan"
date
echo 

# Check to see if there is a lock file
if [ -e $lockfile ]; then
    # A lockfile exists... Lets check to see if it is still valid
    pid=`cat $lockfile`
    if kill -0 &>1 > /dev/null $pid; then
        # Still Valid... lets let it be...
        #echo "Process still running, Lockfile valid"
        exit 1
    else
        # Old Lockfile, Remove it
        #echo "Old lockfile, Removing Lockfile"
        rm $lockfile
    fi
fi
# If we get here, set a lock file using our current PID#
#echo "Setting Lockfile"
echo $$ > $lockfile

# We can perform check
echo "Performing Network check for $wlan"
/bin/ping -c 2 -I $wlan $pingip > /dev/null 2> /dev/null
if [ $? -ge 1 ] ; then
    echo "Network connection down! Attempting reconnection."
    /sbin/ifdown $wlan
    sleep 5
    /sbin/ifup --force $wlan
else
    echo "Network is Okay"	
fi


# Check is complete, Remove Lock file and exit
#echo "process is complete, removing lockfile"
rm $lockfile
exit 0

##################################################################
# End of Script
My Raspberry Pi Project Page:
https://www.flaminghellmet.com/launch/

G0Ku5
Posts: 47
Joined: Sun Sep 01, 2013 12:38 pm

Re: Persistent/reconnecting wifi

Wed Jan 29, 2014 6:00 pm

the script, really puts the wifi on again, but the problem is that then I can not connect to the access point

Anyone know what will be necessary to change the script?

will be necessary to restart the hostpad? :)

User avatar
DougieLawson
Posts: 37069
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Persistent/reconnecting wifi

Wed Jan 29, 2014 7:47 pm

Can you post the output from the following (when your network is running normally)

ifconfig -a
route -n
sudo cat /etc/network/interfaces
sudo cat /etc/wpa_supplicant/wpa_supplicant.conf

Have you added a file to /etc/modprobe.d to disable power saving?
sudo -i
echo "options 8192cu rtw_power_mgnt=0 rtw_enusbss=0" > /etc/modprobe.d/8192cu.conf
exit
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

G0Ku5
Posts: 47
Joined: Sun Sep 01, 2013 12:38 pm

Re: Persistent/reconnecting wifi

Wed Jan 29, 2014 8:23 pm

Thanks for the help provided Friend

I'll add the file

Code: Select all

sudo -i
echo "options 8192cu rtw_power_mgnt=0 rtw_enusbss=0" > /etc/modprobe.d/8192cu.conf
exit
and see if it works, then say here feedback ;)

G0Ku5
Posts: 47
Joined: Sun Sep 01, 2013 12:38 pm

Re: Persistent/reconnecting wifi

Thu Jan 30, 2014 9:17 pm

found a solution, add this command in script

Code: Select all

/etc/init.d/hostapd restart
:)

Kyblik
Posts: 6
Joined: Wed Jan 14, 2015 6:54 pm

Re: Persistent/reconnecting wifi

Wed Jan 14, 2015 7:03 pm

Well scripts posted here seem to be very complex, but for me works just fine this simple one:

Code: Select all

#!/bin/bash
if ! [ "$(ping -c 1 192.168.65.254)" ]; then
    sudo ifdown wlan0
    sudo ifup wlan0
fi
I use my router IP address as sometimes the internet connection is broken on provider side, so it makes no sense to ping e.g. google.com for me.
Executed via crontab every 5 minutes and it makes the job done.

nthnm
Posts: 15
Joined: Wed Apr 01, 2015 9:35 pm

Re: Persistent/reconnecting wifi

Wed Apr 29, 2015 9:10 am

Kyblik wrote:Well scripts posted here seem to be very complex, but for me works just fine this simple one:

Code: Select all

#!/bin/bash
if ! [ "$(ping -c 1 192.168.65.254)" ]; then
    sudo ifdown wlan0
    sudo ifup wlan0
fi
I use my router IP address as sometimes the internet connection is broken on provider side, so it makes no sense to ping e.g. google.com for me.
Executed via crontab every 5 minutes and it makes the job done.
Pinging the router makes the most sense to me... if you lose a connection to google.com but not to the router, then restarting wifi isn't going to help.

If you do need to ping an external site, my preference is Google's DNS server, IP 8.8.8.8.

Massi
Posts: 1691
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Persistent/reconnecting wifi

Wed Apr 29, 2015 9:48 am

i fixed with ifupdown.sh from wpasupplicant

viewtopic.php?f=63&t=101578&p=703876&hi ... sh#p703876

Return to “Troubleshooting”