且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在wifi网络之间动态切换

更新时间:2023-10-04 21:34:04

这是未经测试的快速代码段.

This is an untested piece of code quickly put together.

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'60s,然后再连接到'cisco'60s,如果这两次尝试均未成功,则最终将放弃.它使用半自动计时器,只有在以下情况下才会重新启动还没有IP.

It'll first try to connect to 'dlink' for 60s, then to 'cisco' for another 60s, and will eventually give up after that if neither attempts was successful. It uses a semi-automatic timer which is only restarted if there's no IP yet.