NodeMCU WiFi自动连接

时间:2016-10-06 13:37:37

标签: lua wifi nodemcu

我正在尝试使用Lua语言解决wifi连接问题。我一直在梳理the api找到解决方案,但还没什么可靠的。我问过上一个问题 dynamically switch between wifi networks,答案确实以我提出的方式解决了这个问题,但它没有达到我的预期。

基本上,我有来自两个不同提供商的两个不同的网络。我希望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)

当我运行该代码时,我在控制台上将 effectiveRouter 作为 nil 。这告诉我print语句在方法调用完成之前运行print(effectiveRouter)。我对lua非常新,因为这是我第一次使用这种语言。我确信这个锅炉板代码必须在之前完成。有人可以指点我正确的方向吗?我愿意转移到arduino IDE,因为我已经为NodeMCU ESP8266设置了它。可能是因为我来自java-OOP背景,我可以更好地遵循逻辑。

2 个答案:

答案 0 :(得分:3)

我最终坐下来测试了上一个答案中的草图。另外两行,我们很高兴......

我错过的是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) -- restart
    else
      print("Connected to dlink, IP is "..wifi.sta.getip())
      effectiveRouter = "dlink"
      --startProgram()
    end
  elseif counter == 30 then
    wifi.sta.config("cisco", "password2")
    -- there should also be tmr.start(1) in here as suggested in the comment
  elseif counter < 60 then
    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)

答案 1 :(得分:2)

您最好迁移基于回调的体系结构,以确保已成功连接。这是它的文档:

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

你可以听

  

wifi.STA_GOTIP

并在其中进行自定义操作。不要忘记开始eventmon。

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

相关问题