我正在尝试构建一个基于ESP8266的Geekcreit开发板上的小MQTT客户端。
当我使用PuTTY在串行连接上运行命令时,所有命令都可以正常工作,并成功地发布消息,这是由运行在Raspberry Pi上的代理获取的。
我试图将其添加到Lua脚本中,通过init.lua运行,虽然连接回调触发了任何发布。
--test.lua
print("Setting up WIFI...")
wifi.setmode(wifi.STATION)
--modify according your wireless router settings
wifi.sta.config("ap","pass")
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())
-- initiate the mqtt client and set keepalive timer to 120sec
m = mqtt.Client("myNodeName", 120, "", "") -- blank user and password
m:on("connect", function() print("connected") end )
m:connect("*.*.*.*") -- my local broker's IP
m:publish("topic/test", "7.2", 0, 0) -- no QoS, not retained
end
end)我正在使用Esplorer上传和运行该脚本,正如我所说,我成功地看到了“连接”消息,但没有消息到达代理。
如果我拿了
m:publish("topic/test", "7.2", 0, 0) -- no QoS, not retained然后从Esplorer的"Send“命令栏启动它,代理接收消息。
我有点不知所措。任何帮助都很感激。
发布于 2016-12-13 08:30:48
与NodeMCU API中的许多其他函数一样,mqtt.client:connect()是异步的,也就是说它不阻塞。只有在成功建立连接之后才能发布。在mqtt.client:connect()中有一个回调函数。
您可以使用本地mqtt_connected标志,将其设置在回调(或m:on("connect"))中,然后在计时器中等待,直到连接或直接从回调发布。
m:connect("192.168.11.118", 1883, 0, function(client)
// now publish through client
end)https://stackoverflow.com/questions/41109001
复制相似问题