The wifi.sta module connects if a loop is running?

微笑、不失礼 提交于 2019-12-02 08:02:22

Using tmr.delay doesnot let run the event loop, you should use a timer callback.

Then the code could be something like :

wifi.sta.config("SSID","password")
wifi.sta.connect()

i=0
tmr.alarm(1, 1000, 1, function()
    if (wifi.sta.status() ~= 5 and i < 10) then
       print("Status:"..wifi.sta.status())
       i = i + 1
    else
       tmr.stop(1)
       if (wifi.sta.status() == 5) then
          print("IP:"..wifi.sta.getip())
       else
          print("Status:"..wifi.sta.status())
       end
    end
end)

If you use a recent dev firmware you can do something really event based :

wifi.setmode(wifi.STATION)
wifi.sta.config(SSID, PASSWORD)

function Success()
    tmr.stop(0)
    if (SERIAL_PRINT) then
        print("IP: " .. wifi.sta.getip())
    end
    wifi.sta.eventMonStop()
    wifi.sta.eventMonReg(wifi.STA_GOTIP, "unreg")
    dofile("mainProgram.lua")
end

function Failure()
    if (SERIAL_PRINT) then
        print("Unable to connect")
    end
    wifi.sta.eventMonStop()
    wifi.sta.eventMonReg(wifi.STA_GOTIP, "unreg")
    return 0
end

tmr.alarm(0,30000,0, function() Failure() end)
wifi.sta.connect()
wifi.sta.eventMonReg(wifi.STA_GOTIP, function() Success() end)
wifi.sta.eventMonStart()

EDIT: Please have a look to the documentation for a list of all events. If you wish to use this code, you'll have to handle the failure more cleanly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!