Lua闹钟不执行代码。

我在使用LuaLoader编程NodeMCU。我尝试读取节点的ADC并将其发送到我的公共域中的PHP文件中。

使用下面的代码,可以获取ADC和Node的IP并通过GET发送它。

x = adc.read(0);
ip = wifi.sta.getip();

conn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload) print(payload) end)
conn:connect(80,'example.com')
conn:send("GET /data.php?mdata="..x.."&ip="..ip.." HTTP/1.1\r\n")
conn:send("Host: example.com\r\n")
conn:send("Connection: keep-alive\r\nAccept: */*\r\n")
conn:send("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n")
conn:send("\r\n")
print ("Done")

代码可以正常运行。如果我将其粘贴到我的LuaLoader中,它将返回:

 HTTP/1.1 200 OK
 Date: Wed, 30 Sep 2015 02:47:51 GMT
 Server: Apache
 X-Powered-By: PHP/5.5.26
 Content-Length: 0
 Keep-Alive: timeout=2, max=100
 Connection: Keep-Alive
 Content-Type: text/html

 Done

但是,我希望在警报内重复代码,并每分钟发送一次数据,但它不起作用。

tmr.alarm(0, 60000, 1, function()
    x = adc.read(0);
    ip = wifi.sta.getip();

    conn=net.createConnection(net.TCP, 0)
    conn:on("receive", function(conn, payload) print(payload) end)
    conn:connect(80,'example.com')
    conn:send("GET /data.php?mdata="..x.."&ip="..ip.." HTTP/1.1\r\n")
    conn:send("Host: example.com\r\n")
    conn:send("Connection: keep-alive\r\nAccept: */*\r\n")
    conn:send("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n")
    conn:send("\r\n")
    print ("Done")
 end )

输出仅为...

 Done

...而没有有效载荷。它没有发送数据。

我尝试将代码放入函数中,在另一个文件中,并使用** dotfile **调用警报,但它不起作用。我尝试将警报延长2分钟以便发送数据,但什么也没有。

点赞
用户1190388
用户1190388

tmr.alarm的文档中,第三个参数可以是01

重复:`0` - 一次性闹钟,`1` - 重复

由于您传递的是0,它只会执行一次功能。改为传递1

tmr.alarm(0, 60000, 1, function()
    x = adc.read(0);
    ip = wifi.sta.getip();

    conn=net.createConnection(net.TCP, 0)
    conn:on("receive", function(conn, payload) print(payload) end)
    conn:connect(80,'robcc.esy.es')
    conn:send("GET /data.php?mdata="..x.."&ip="..ip.." HTTP/1.1\r\n")
    conn:send("Host: robcc.esy.es\r\n")
    conn:send("Connection: keep-alive\r\nAccept: */*\r\n")
    conn:send("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n")
    conn:send("\r\n")
    print ("Done")
end )
2015-09-30 07:10:53
用户3330190
用户3330190

我找到了答案。我在连接建立时添加了一个回调。闹钟可能会在发送数据包之前重置连接。

x = adc.read(0);
ip = wifi.sta.getip();

conn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload)
    print ("\nDone---------------")
    print(payload)
end)

conn:on("connection", function(conn, payload)
   print('\nConnected...')
   conn:send("GET /data.php?mdata="..x.."&ip="..ip.." HTTP/1.1\r\n"
        .."Host: example.com\r\n"
        .."Connection: keep-alive\r\nAccept: */*\r\n"
        .."User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n"
        .."\r\n")
end)

conn:connect(80,'example.com')
2015-10-06 05:15:59