我正在用NodeMCU构建一个基于ESP8266的电池供电物联网设备。我使用mqtt定期执行测量并发布结果。我知道,为了允许网络堆栈运行,我应该避免紧循环,并依赖于回调函数。因此,在我看来,我的测量代码的正确组织应该是:
interval=60000000
function sleep_till_next_sample()
node.dsleep(interval)
end
function close_after_sending()
m:close()
sleep_till_next_sample()
end
function publish_meas()
m:publish("/test",result,1,0,close_after_sending)
print("published:"..result)
end
function measurement()
-- The omitted part of the function accesses
-- the hardware and places results
-- in the "result" variable
m = mqtt.Client("clientid", 120, "user", "password")
m:connect("172.19.1.254",1883,0, publish_meas)
end
init.lua确保节点已连接到WiFi AP(如果未连接,则最多重试20次,如果未建立连接,则将节点置于睡眠状态,直到下一次测量时间)。WiFi连接完成后,它会调用测量功能。
有趣的是,上面的代码不起作用。控制台中没有显示任何错误,但mqtt代理不会接收已发布的消息。为了使它工作,我不得不通过在回调函数中添加计时器来添加额外的空闲时间。
最终工作的代码如下所示:
interval=60000000
function sleep_till_next_sample()
node.dsleep(interval)
end
function close_after_sending()
m:close()
tmr.alarm(1,500,0,function() sleep_till_next_sample() end)
end
function publish_meas()
m:publish("/test",result,1,0,function() tmr.alarm(1,500,0,close_after_sending) end)
print("published:"..result)
end
function measurement()
-- The omitted part of the function accesses
-- the hardware and places results
-- in the "result" variable
m = mqtt.Client("clientid", 120, "user", "password")
m:connect("172.19.1.254",1883,0, function() tmr.alarm(1,500,0, publish_meas) end)
end
上面的方法有效,但我不确定它是否是最优的。为了节省电池电量,我希望在测量完成并公布结果后,尽量缩短节点进入睡眠状态之前的时间。
有没有更好的方法将必要的调用链接到m:connect、m:publish、m:close,最后是node.dsleep,以便在最短的时间内正确发布结果?
也许最近的固件解决了这个问题。我正在处理一个问题,我认为这个问题可能会在一定程度上解释这个问题,所以我试图按照描述重现这个问题。
我的简化测试代码基本相似;它从mqtt的PUBACK回调中调用dslee()。Client.publish():
m = mqtt.Client("clientid", 120, "8266test", "password")
m:lwt("/lwt", "offline", 0, 0)
function main(client)
print("connected - at top of main")
m:publish("someval",12345,1,0, function(client)
rtctime.dsleep(SLEEP_USEC)
end)
end
m:on("connect", main)
m:on("offline", function(client) is_connected = false print ("offline") end)
m:connect(MQQT_SVR, 1883, 0, mainloop,
function(client, reason) print("failed reason: "..reason) end)
并在运行时成功发布到我的MQTT代理。
我正在使用:
NodeMCU custom build by frightanic.com
branch: master
commit: 81ec3665cb5fe68eb8596612485cc206b65659c9
SSL: false
modules: dht,file,gpio,http,mdns,mqtt,net,node,rtctime,sntp,tmr,uart,wifi
build built on: 2017-01-01 20:51
powered by Lua 5.1.4 on SDK 1.5.4.1(39cb9a32)