NodeMCU WiFi自动连接

我正在尝试使用Lua语言解决WiFi连接问题。我一直在查阅 API(https://nodemcu.readthedocs.io/en/master/en/modules/wifi/) 来找到解决方案,但还没有确定的解决方案。我之前问过一个问题,动态切换WiFi网络,答案确实回答了我所提出的问题,但并没有达到我预期的效果。

基本上,我有来自两个不同提供商的两个不同网络。我想让ESP8266 12e检测当前网络是否有互联网访问权限,并自动切换到下一个网络。它必须连续尝试连接,例如每隔3分钟,直到成功,并且不仅仅是放弃。

为了测试目的,我尝试了下面的代码。计划使用变量“effectiveRouter”并编写一些逻辑来基于当前路由器进行切换。

effectiveRouter = nil
function wifiConnect(id,pw)
    counter = 0
    wifi.sta.config(id,pw)
    tmr.alarm(1, 1000, tmr.ALARM_SEMI, function()
    counter = counter + 1
        if counter < 10 then
            if wifi.sta.getip() == nil then
              print("NO IP yet! Trying on "..id)
              tmr.start(1)
            else
                print("Connected, IP is "..wifi.sta.getip())

            end
        end
    end)
end
wifiConnect("myNetwork","myPassword")
print(effectiveRouter)

当我运行该代码时,控制台上的effectiveRouternil。这告诉我,在方法调用完成之前,print(effectiveRouter) 语句已经执行,我对Lua非常陌生,这是我第一次使用这种语言。我确定这个样板代码以前肯定做过。请问有谁能指点我方向吗?如果我已经设置好了NodeMCU ESP8266的arduino IDE,我可以转向那里并跟随逻辑。因为我来自Java-OOP背景。

点赞
用户3082873
用户3082873

你最好迁移使用回调函数的架构,以确保已成功连接。这里有相应文档:

https://nodemcu.readthedocs.io/en/master/en/modules/wifi/#wifistaeventmonreg

你可以监听:

wifi.STA_GOTIP

在其中进行自定义操作。不要忘记启动eventmon。

P.S.我在相关函数中无法看到你的变量effectiveRouter。

2016-10-06 16:19:19
用户131929
用户131929

最终,我坐下来测试了我之前回答中的草图。只需要加上两行代码,就可以开始...

我错过的是,wifi.sta.config()auto connect == true(默认情况下)时重置连接尝试。因此,如果你在连接到X的过程中调用它,以连接到AP X,它将从头开始-因此通常无法在再次调用之前获取IP。

effectiveRouter = nil
counter = 0
wifi.sta.config("dlink", "password1")
tmr.alarm(1, 1000, tmr.ALARM_SEMI, function()
  counter = counter + 1
  if counter < 30 then
    if wifi.sta.getip() == nil then
      print("NO IP yet! Keep trying to connect to dlink")
      tmr.start(1) -- 重新启动
    else
      print("Connected to dlink, IP is "..wifi.sta.getip())
      effectiveRouter = "dlink"
      --startProgram()
    end
  elseif counter == 30 then
    wifi.sta.config("cisco", "password2")
    -- 还应该在这里加入tmr.start(1)来建议
  elseif counter < 60 then
    if wifi.sta.getip() == nil then
      print("NO IP yet! Keep trying to connect to cisco")
      tmr.start(1) -- 重新启动
    else
      print("Connected to cisco, IP is "..wifi.sta.getip())
      effectiveRouter = "cisco"
      --startProgram()
    end
  else
    print("Out of options, giving up.")
  end
end)
2016-10-08 08:59:38