Check and reestablish WLAN connection

Auto-reconnect WiFi on Raspberry PI using Node-Red

Updated 2017-02-06: I have had trouble getting reliable operation from the method previously described in this article – the WiFi wouldn’t always reconnect when the connection was lost. In this update I have improved the method and I have had no problems with WiFi-connectivity since implementing it.

For my IoT base station run by a Raspberry PI I am using the WiPi dongle to connect to my wireless network. This setup generally works fine, but once in a while it looses connection to the network (and the blue supernova dies out).

The easiest option for resolution has been to simply pull the plug and reboot the entire RPI. Naturally, this is not an acceptable solution and a way of auto-reconnecting should be possible without having to interact with the device.

This is another situation in which Node-Red can be helpful due to its exec node, which can execute any given shell script when triggered.

I have created a simple flow that triggers an exec node every 30 minutes. The exec node executes a shell script that simply checks whether WLAN is connected and either does nothing or tries to re-establish the connection and writes a message to stdout, which continues the flow in Node-Red executing a logging event and sending a notification to me via Twitter.

The script basically performs the following steps in order to either reconnect the WiFi or, if more drastic means are required, reboot the system:

  1. Determine whether the system is fully booted. This is done simply by reading the system uptime – if it is less than 30 seconds, the system is considered to be in its booting stage and the script exits, otherwise it is considered to be fully booted. Naturally, this interval depends on the individual system running the script.
  2. The connection status of the WiFi is checked. If the WiFi is connected to the specified SSID, then the script exits.
  3. If the WiFi is not connected, then three attempts to reconnect are made, with ten seconds interval using the ifdown and ifup commands. If it is possible to reconnect to the SSID, then the script exits.
  4. If, however, it is not possible to reconnect to the SSID, then the system is rebooted by calling reboot as sudo. One condition where this situation is possible, besides when the SSID is unavailable, is when there is no more storage left for logging (i.e. /var/log is full). A reboot frees up space by clearing the log files – with the loss of their content as consequence, mind you.

This script is shown below:

#!/bin/bash

#DEBUG=1

SSID_CHECK="YourSSIDHere"

#0=WLAN present, 1=WLAN not present
SSID=

check_wlan(){
    SSID=$(iwconfig 2>&1 | grep ESSID | sed -e 's/"//g')
    $(echo "$SSID" | grep -q $SSID_CHECK)

    echo $?
}

if [ $DEBUG ]; then
    echo "check_wlan(): $(check_wlan)"
fi

uptime=$(cat /proc/uptime | awk '{print $1}')

if [ $DEBUG ]; then
    echo "Uptime: $uptime"
fi

running=$(echo "$uptime < 30" | bc)

if [ $DEBUG ]; then
    echo "Running: $running"
fi

if [ $running -eq 1 ]; then
    if [ $DEBUG ]; then
        echo "Uptime is less than threshold"
    fi

    exit 0;
fi

if [ $(check_wlan) -eq 0 ]; then
    exit 0;
fi

cnt=3

while [ $(check_wlan) -eq 1 ] && [ $cnt -gt 0 ]; do
    if [ $DEBUG ]; then
        echo "Restarting WLAN .."
    fi

    sudo ifdown wlan0 && sudo ifup wlan0

    sleep 10

    cnt=$(echo "$cnt - 1" | bc) 
done

if [ $(check_wlan) -eq 1 ]; then
    if [ $DEBUG ]; then
        echo "Unable to reconnect WLAN. Rebooting .."
    fi

    logger -t Node-RED-WLAN "Unable to reconnect WLAN. Rebooting .."

    unset check_wlan

    echo "WLAN reconnect failed, rebooting!"
    sudo reboot
else
    echo "WLAN reconnected!"
fi 

unset check_wlan

exit 0

I have saved the script to ~/.node-red/scripts/wlan.sh and set the permissions to 700: chmod 700 ~/.node-red/scripts/wlan.sh. This makes the file accessible and executable only to the pi user.

The exec node configuration is pretty straight forward, but I include it here for completeness (You will have to re-configure the input and output connections):

[{"id":"63d652df.9c29ac", "type":"exec", "z":"22915660.dd6eaa", "command":"~/.node-red/scripts/wlan.sh", "addpay":false, "append":"", "useSpawn":"", "name":"Check WLAN", "x":340, "y":120, "wires":[[], [], []]}]

I only use the stdout output of the exec node, so I basically will not know if anything severe goes wrong running the script, but so far I have not experienced any misbehaviour from the flow. There have been no issues with network connectivity since I created the flow and I occasionally get a message saying that network connection has been restored.

2 comments on “Auto-reconnect WiFi on Raspberry PI using Node-RedAdd yours →

    1. Hi Li,

      Thanks for your comment and for visiting!

      No sudo works for me, but of course others might need sudo.
      It is my experience that sudo is rarely added to commands published in blogs in order to maintain as secure an environment as possible. It is then implicitly left to the reader to add sudo if necessary.

      Cheers – Anders

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: