出于某种原因,我无法让 net.socket:send() 可靠地工作。下面的代码应该执行以下操作:
它 100% 的时间都在工作,直到检查是否已获得 IP 的重复计时器为止。发送该数据只有 5-10% 的时间有效,我不明白为什么。(“数据”+ JSON 数据打印,“SENT”没有)
我已经在切换到站模式之前添加了 5 秒的延迟,以防止我获得的连接出现错误,并注释掉了计时器的取消注册,这最初似乎有所帮助,但仍然没有运气。
有谁知道什么可能阻止我的套接字发送?
附言。socket:send() 的其他实例工作得很好,尽管它们没有使用那么多的回调。
代码:
全选setWiFi_sta(jsonData, true, func
tion()
print("CONNECTED1")
local hold = false
local timer = tmr.create()
timer:alarm(500, tmr.ALARM_AUTO, function()
if (wifi.sta.status() == wifi.STA_GOTIP and not hold) then
hold = true
print("ip", wifi.sta.getip())
print("ssid", wifi.sta.getconfig(true).ssid)
local data = {}
data.ip = wifi.sta.getip()
data.ssid = wifi.sta.getconfig(true).ssid
print("data", sjson.encode(data))
localSocket:send(sjson.encode(data), function()
print("SENT")
localSocket:close()
tmr.create():alarm(5000, tmr.ALARM_SINGLE, function()
print("CLOSING SOCKET AND GOING TO STATION MODE")
wifi.setmode(wifi.STATION)
-- timer:unregister()
end)
end)
end
end)
end)
function setWiFi_sta(data, doConnectedCheck, connectedCallback)
print("setWiFi_sta")
if (data.ssid == "") then
setWiFi_ap()
return
end
wifi.sta.clearconfig()
print("config", wifi.sta.config({
ssid = data.ssid,
pwd = data.pass,
auto = false,
save = false
}))
if (data.ip ~= "") then
print("setip", wifi.sta.setip({
ip = data.ip,
netmask = data.netmask,
gateway = data.gateway
}))
end
if (doConnectedCheck) then
tmr.alarm(0, 60*1000, tmr.ALARM_SINGLE, function(timer)
-- If this code runs, the module hasn't connected to the network after 60 seconds,
-- so we should probably return to AP mode to fix this
setWiFi_ap()
end)
end
wifi.sta.connect(function()
print("CONNECTED2")
tmr.unregister(0)
if (connectedCallback ~= nil) then
connectedCallback()
end
end)
end