I have two WiFi networks at home where I want to use my NodeMCU ESP8266 V1 to control several relays remotely over the web from anywhere in the world.To accomplish this I was thinking to test for WiFi connectivity and if I don't get an IP within 1-minute try the other network until I get an IP. Here is the API docs for tmr which I followed in the code below.
Is there a way to switch between two or more wifi networks programatically using Lua? I am using the Lua language, however I can move to arduino IDE, if required.
wifi.setmode(wifi.STATION)
myRouter = "dlink"
tmr.alarm(1, 60000, tmr.ALARM_SINGLE, function()
if myRouter=="dlink" then
print("Dlink selected")
wifi.sta.config("dlink","password1")
wifi.sta.connect()
if wifi.sta.getip() == nil then
print("NO IP yet! ,Connecting...")
else
tmr.stop(1)
print("Connected, IP is "..wifi.sta.getip())
end
elseif myRouter=="cisco" then
print("Cisco selected")
wifi.sta.config("cisco","passoword2")
wifi.sta.connect()
if wifi.sta.getip() == nil then
print("NO IP yet! ,Connecting...")
else
tmr.stop(1)
print("Connected, IP is "..wifi.sta.getip())
end
else
print("No network is giving an ip")
end
end)
What I am looking for is a callback which fires whenever the timer "tmr" expires. This way I can change the variable to myRouter="cisco". Notice in the code above i was unable to change the "myRouter" variable.
I considered using a software watchdog to monitor the conectivity all the time so if or when the WiFi drops on one network, it will trigger a reconnect by running the code above. I am not sure how to do this or how its usually done, since I am very new to lua. Please advise or point me to a resource which can help in this regard. Thanks guys.
This is an untested piece of code quickly put together.
It'll first try to connect to 'dlink' for 60s, then to 'cisco' for another 60s, and will eventually give up after that if neither attempts was successful. It uses a semi-automatic timer which is only restarted if there's no IP yet.