NodeMCU Lua 中的套接字连接作为片段使用,而不是来自 init.lua
Socket Connection in NodeMCU Lua works as snippet, not from init.lua
我有以下代码
conn = net.createConnection(net.TCP, 0)
conn:on("sent", function(sck,c)
print("Sent")
sck:close()
end)
conn:on("connection", function(sck,c)
print("Connected..")
sck:send("test")
end)
conn:connect(9090, "192.168.1.89")
print("Send data.")
这在 运行 作为 ESPlorer、IE 运行 实时解释器中的片段时工作正常。我看到输出 "Connected.." 和 "Sent",消息出现在服务器上。当它是 init.lua 或我的 mcu-temp.lua 的一部分时,我什至看不到 "Connected.." 消息。
与 WIFI 的连接正常,在尝试 "live" 和从文件中未重置电路板。我真的很困惑为什么它以一种方式工作而不是另一种方式。
The connection to WIFI is OK
我对此深表怀疑。如果您从 ESPlorer 运行 那么是的,但是当您重新启动设备时不是。
连接到 AP 通常需要几秒钟。您需要等到它连接后才能继续启动序列。请记住:对于 NodeMCU,大多数操作都是异步和事件驱动的,wifi.sta.connect()
不会阻塞。
这是我从 https://cknodemcu.wordpress.com/ 借用并改编的启动序列。
SSID = <tbd>
PASSWORD = <tbd>
function startup()
local conn = net.createConnection(net.TCP, 0)
conn:on("sent", function(sck, c)
print("Sent")
sck:close()
end)
conn:on("connection", function(sck, c)
print("Connected..")
sck:send("test")
end)
conn:connect(9090, "192.168.1.89")
print("Sent data.")
end
print("setting up WiFi")
wifi.setmode(wifi.STATION)
wifi.sta.config(SSID,PASSWORD)
wifi.sta.connect()
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip() == nil then
print("IP unavaiable, Waiting...")
else
tmr.stop(1)
print("Config done, IP is "..wifi.sta.getip())
print("You have 5 seconds to abort startup")
print("Waiting...")
tmr.alarm(0, 5000, 0, startup)
end
end)
就在两天前,我在 SO 上回答了几乎相同的问题。有关替代解决方案,请参阅 。
我有以下代码
conn = net.createConnection(net.TCP, 0)
conn:on("sent", function(sck,c)
print("Sent")
sck:close()
end)
conn:on("connection", function(sck,c)
print("Connected..")
sck:send("test")
end)
conn:connect(9090, "192.168.1.89")
print("Send data.")
这在 运行 作为 ESPlorer、IE 运行 实时解释器中的片段时工作正常。我看到输出 "Connected.." 和 "Sent",消息出现在服务器上。当它是 init.lua 或我的 mcu-temp.lua 的一部分时,我什至看不到 "Connected.." 消息。
与 WIFI 的连接正常,在尝试 "live" 和从文件中未重置电路板。我真的很困惑为什么它以一种方式工作而不是另一种方式。
The connection to WIFI is OK
我对此深表怀疑。如果您从 ESPlorer 运行 那么是的,但是当您重新启动设备时不是。
连接到 AP 通常需要几秒钟。您需要等到它连接后才能继续启动序列。请记住:对于 NodeMCU,大多数操作都是异步和事件驱动的,wifi.sta.connect()
不会阻塞。
这是我从 https://cknodemcu.wordpress.com/ 借用并改编的启动序列。
SSID = <tbd>
PASSWORD = <tbd>
function startup()
local conn = net.createConnection(net.TCP, 0)
conn:on("sent", function(sck, c)
print("Sent")
sck:close()
end)
conn:on("connection", function(sck, c)
print("Connected..")
sck:send("test")
end)
conn:connect(9090, "192.168.1.89")
print("Sent data.")
end
print("setting up WiFi")
wifi.setmode(wifi.STATION)
wifi.sta.config(SSID,PASSWORD)
wifi.sta.connect()
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip() == nil then
print("IP unavaiable, Waiting...")
else
tmr.stop(1)
print("Config done, IP is "..wifi.sta.getip())
print("You have 5 seconds to abort startup")
print("Waiting...")
tmr.alarm(0, 5000, 0, startup)
end
end)
就在两天前,我在 SO 上回答了几乎相同的问题。有关替代解决方案,请参阅