In previous posts the hardware to build a power switch controlled by WiFi, using the ESP8266 module, as well the microcontroller code were depicted. The switch can be controlled via accessing a web URL:

  • "http://<IP address>/gpio/1" turns the switch ON
  • "http://<IP address>/gpio/0" turns the switch OFF
  • "http://<IP address>/gpio/status" displays the status

The aim of the power switch is to control the exterior lighting, so it needs to switch on and off every day. A UNIX system using the cron scheduler seems the perfect implementation. As the system needs to be autonomous, in case the ESP8266 does not respond, the client needs to make several attempts before giving up. In the meantime, it needs to log every failed attempt (using logger) for future reference. The time between each attempt is doubled each time. The DHCP server of the router is configured to give a permanent IP address to the ESP8266 module. The above requirements are embedded in a bash script. The script is used with two arguments, the first is the ip and the second is the state (0, 1 or status).

#!/bin/bash
arguments=$#
max_attempts=10 #maximum attempts to try to connect
timeout=2       #initial timeout in seconds
attempt=0
if [ "$arguments" -ne "2" ] 
then echo "usage: setstate <ip> <state>"
exit 1
fi
dev=$1
state=$2
url="http://"$dev"/gpio/"$state
while (($attempt &amp;lt; $max_attempts)) do curl -s --max-time 1 $url > /dev/null
    exitCode=$?
    if [[ $exitCode == 0 ]]
    then
        break
    fi
     
    logger -p error "[WARNING] Wireless $ip not responding, retrying in $timeout"
    echo "Failure! Retrying in $timeout.." 1>&2
    sleep $timeout
    attempt=$(( attempt + 1 ))
    timeout=$(( timeout * 2 ))
done
if [[ $exitCode != 0 ]]
  then
    logger -p error "[ERROR] Wireless $ip not responding"
    echo "Maximum attempts reached trying to connect ($@)" 1>&2
fi
exit $exitCode

The full project for the ESP8266 power switch can be found on my Github page.