在wifi网络之间动态切换

时间:2016-09-25 13:45:02

标签: lua wifi nodemcu

我家里有两个WiFi网络,我想用 NodeMCU ESP8266 V1 从世界上任何地方通过网络远程控制多个中继。为了实现这一点,我想考验WiFi连接,如果我在1分钟内没有获得IP,请尝试其他网络,直到我获得IP。以下是我在下面的代码中遵循的API docs for tmr

有没有办法使用Lua以编程方式在两个或更多个wifi网络之间切换?我使用的是Lua语言,但如果需要,我可以转到arduino IDE。

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)

我正在寻找的是当计时器“tmr”到期时会触发的回调。这样我可以将变量更改为 myRouter =“cisco”。请注意,在上面的代码中,我无法更改“ myRouter ”变量。

我考虑过使用software watchdog来监控连续性,因此,如果WiFi在一个网络上掉线,它将通过运行上面的代码触发重新连接。我不知道该怎么做或者通常如何做,因为我对lua很新。请告知或指出一个可以在这方面提供帮助的资源。谢谢你们。

1 个答案:

答案 0 :(得分:3)

这是一段未经测试的快速拼凑的代码。

effectiveRouter = nil
counter = 0
wifi.sta.config("dlink", "password1")
tmr.alarm(1, 1000, tmr.ALARM_SEMI, function()
  counter = counter + 1
  if counter < 60 then
    if wifi.sta.getip() == nil then
      print("NO IP yet! Keep trying to connect to dlink")
      tmr.start(1) -- restart
    else
      print("Connected to dlink, IP is "..wifi.sta.getip())
      effectiveRouter = "dlink"
      startProgram()
    end
  elseif counter < 120 then
    wifi.sta.config("cisco", "password2")
    if wifi.sta.getip() == nil then
      print("NO IP yet! Keep trying to connect to cisco")
      tmr.start(1) -- restart
    else
      print("Connected to cisco, IP is "..wifi.sta.getip())
      effectiveRouter = "cisco"
      startProgram()
    end
  else
    print("Out of options, giving up.")
  end
end)

首先尝试连接到'dlink'60秒,然后再'cisco'连续60秒,如果两次尝试都没有成功,最终会放弃。它使用semi-automatic timer,只有在没有IP的情况下才会重新启动。