我正在尝试使用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 回答
我最终坐下来测试了前一个答案中的草图 . 两条额外的线路,我们很高兴...
我错过的是wifi.sta.config()重置连接尝试,如果
auto connect == true
(这是默认值) . 所以,如果你把它叫做连接到AP X,那么's in the process of connecting to X it will start from scratch - and thus usually not get an IP before it'再次调用它 .您最好迁移基于回调的体系结构,以确保已成功连接 . 这是doc的文章:
https://nodemcu.readthedocs.io/en/master/en/modules/wifi/#wifistaeventmonreg
你可以听
并在其中进行自定义操作 . 别忘了开始eventmon .
附:我无法在相关函数中看到您的变量effectiveRouter .