我正在使用esp8266与Marcel的NodeMCU自定义版本生成的固件http://frightanic.com/nodemcu-custom-build/ 我测试了“dev”分支和“master”。
我在这里找到了一些“ Connect to MQTT Broker ”代码https://github.com/nodemcu/nodemcu-firmware
-- init mqtt client with keepalive timer 120sec
m = mqtt.Client("clientid", 120, "user", "password")
m:on("connect", function(con) print ("connected") end)
m:on("offline", function(con) print ("offline") end)
-- m:connect( host, port, secure, auto_reconnect, function(client) )
-- for secure: m:connect("192.168.11.118", 1880, 1, 0)
-- for auto-reconnect: m:connect("192.168.11.118", 1880, 0, 1)
m:connect("192.168.11.118", 1880, 0, 0, function(conn) print("connected") end)
-- publish a message with data = hello, QoS = 0, retain = 0
local i = 1
while i < 10 do
m:publish("/topic","hello",0,0, function(conn) print("sent") end)
i = i + 1
end
m:close();
我正在使用mosquitto作为mqtt经纪人,我已经在所有主题#上推出了订阅者。
结果是:消息正确到达,但它们到达订户的速度很慢(每个约1秒)...为什么?
我也试图改变mqtt架构而转向UDP .. esp8266快速发送100条消息。
更新1#:
我做了一些实验:
据我所知,阅读调试日志和源代码.. 有一种队列将消息保存在内存中,一个计时器(我不知道频率/间隔)从队列中读取消息并通过mqtt发送它。 如果您尝试发送100条消息,队列会增加,但它无法同时传递消息(可能存在竞争条件?)。
这里存在第二个问题,在它排队超过15条消息后,固件崩溃和设备重新启动:它似乎没有更多可用内存的症状。
答案 0 :(得分:4)
它可能不是您正在寻找的答案,但是,NodeMCU MQTT使用内部队列来处理消息。它是2015年3月底的added。由于NodeMCU API的异步特性,它被添加了。
如果您快速连续两次拨打m.publish
,请记住他们是异步的,没有足够的时间在第二条消息被触发之前传递第一条消息。在引入该队列之前,如果您已经在循环中发布,那么固件就会崩溃。
我更简化了你的代码并添加了一些调试语句:
m = mqtt.Client("clientid", 120, "user", "password")
m:connect("m20.cloudmqtt.com", port, 0, function(conn)
print("MQTT connected")
for i=1,10 do
print("MQTT publishing...")
m:publish("/topic", "hello", 0, 0, function(conn)
print("MQTT message sent")
print(" heap is " .. node.heap() .. " bytes")
end)
print(" heap is " .. node.heap() .. " bytes in loop " .. i)
end
end)
知道对m.publish
的调用是异步的,输出不应该太令人惊讶:
MQTT connected
MQTT publishing...
heap is 37784 bytes in loop 1
MQTT publishing...
heap is 37640 bytes in loop 2
MQTT publishing...
heap is 37520 bytes in loop 3
MQTT publishing...
heap is 37448 bytes in loop 4
MQTT publishing...
heap is 37344 bytes in loop 5
MQTT publishing...
heap is 37264 bytes in loop 6
MQTT publishing...
heap is 37192 bytes in loop 7
MQTT publishing...
heap is 37120 bytes in loop 8
MQTT publishing...
heap is 37048 bytes in loop 9
MQTT publishing...
heap is 36976 bytes in loop 10
sent
heap is 38704 bytes
sent
heap is 38792 bytes
sent
heap is 38856 bytes
sent
heap is 38928 bytes
sent
heap is 39032 bytes
sent
heap is 39112 bytes
sent
heap is 39184 bytes
sent
heap is 39256 bytes
sent
heap is 39328 bytes
sent
heap is 39400 bytes
您会看到可用堆空间在发布时正在减少,并在队列清空时再次增加。