Auto-reconnection to a router
Posted: Tue Oct 25, 2016 4:08 am
So I have two ESP8266 based nodes in a house thousands of miles away monitoring and reporting the status of 14 different sensors. Works pretty well except that both are in a deep, dark basement and while the 12-F stays connected, it appears that the 12-E sees a weaker signal and will, on occasion, disconnect. Once disconnected, the node is isolated yet still running.
So I've conjured up a little code to solve that problem and have it working locally. While there are various ways one might check for connection to a router, I'm going simple. I just look to see if the WGET() that I use to report to my web server is returning a response. If it fails three times in an many minutes, I assume that I've lost connection with the router. While it could be other problems, those cannot be solved by the node and a re-connection is harmless.
So this works by reading the router SSID and password and any IP setup from flash (same variables used in the Settings page). Then it uses the right version of the WIFI.CONNECT() function to re-connect. Notice how I use an array so I can DIM and UNDIM it to save on variables? Yeah, that means I read the flash variables every time, but speed is not an issue here.
Now all I have to do is get my cousin (who is barely computer literate) over to the house and talk him through updating the Basic program.
So I've conjured up a little code to solve that problem and have it working locally. While there are various ways one might check for connection to a router, I'm going simple. I just look to see if the WGET() that I use to report to my web server is returning a response. If it fails three times in an many minutes, I assume that I've lost connection with the router. While it could be other problems, those cannot be solved by the node and a re-connection is harmless.
Code: Select all
' Initialize this once
fail = 0
' Timer triggered reporting code goes here to create a url with command line variable passage.
' (Once per minute in my case)
rv = wget(url)
if rv == "" then
fail = fail + 1
if fail>2 then gosub [reconnect]
endif
wait
[reconnect]
dim c_inf(6) as string
c_inf(1) = read("WIFIname")
c_inf(2) = read("WIFIpass")
c_inf(3) = read("ipaddress")
c_inf(4) = read("gateway")
c_inf(5) = read("subnetmask")
if c_inf(3) == "" then wifi.connect(c_inf(1),c_inf(2)) else wifi.connect(c_inf(1),c_inf(2),c_inf(3),c_inf(4),c_inf(5))
undim c_inf
fail = 0
return
So this works by reading the router SSID and password and any IP setup from flash (same variables used in the Settings page). Then it uses the right version of the WIFI.CONNECT() function to re-connect. Notice how I use an array so I can DIM and UNDIM it to save on variables? Yeah, that means I read the flash variables every time, but speed is not an issue here.
Now all I have to do is get my cousin (who is barely computer literate) over to the house and talk him through updating the Basic program.