【发布时间】:2016-04-16 16:58:51
【问题描述】:
我对 ESP8266 上的以下 Lua 代码有疑问...
function sendData(humidity,temperature)
-- Setup MQTT client and events
print("sendData() entered")
print("Setting up mqtt.Client...")
m = mqtt.Client(mqtt_client_id, 120, username, password)
print("Attempting client connect...")
m:connect(mqtt_broker_ip , mqtt_broker_port, 0, function(conn)
print("Connected to MQTT")
print(" IP: " .. mqtt_broker_ip)
print(" Port: " .. mqtt_broker_port)
print(" Client ID: " .. mqtt_client_id)
print(" Username: " .. mqtt_username)
payload = "Temp: " .. temperature .. " Hmdy: " .. humidity
m:publish("pt/env",payload, 0, 0, function(conn)
print("Going to deep sleep for " .. (DSLEEPTIME/1000) .. " seconds")
node.dsleep(DSLEEPTIME*1000,4)
end)
end)
end
代码被成功调用,如下...
-- Connect to network
wifi.setmode(wifi.STATION)
wifi.setphymode(wifi_signal_mode)
wifi.sta.config(wifi_SSID, wifi_password)
wifi.sta.connect()
print("Attempting to connect...")
ip = wifi.sta.getip()
if ip ~= nil then
print("Got IP: " .. ip)
print("About to call sendData()...")
sendData(humidity, temperature)
print("Returned from sendData()...")
end
使用 ESPlorer 我看到以下内容...
Attempting to connect...
Attempting to connect...
Attempting to connect...
Attempting to connect...
Attempting to connect...
Attempting to connect...
Got IP: 192.168.0.39
About to call sendData()...
sendData() entered
Setting up mqtt.Client...
Attempting client connect...
Returned from sendData()...
所以它基本上输入了sendData(...),我看到了该行的输出......
print("Attempting client connect...")
...但我从来没有看到 m:connect(...) 块中的日志记录,例如...
print("Connected to MQTT")
...它似乎只是立即返回。
MQTT 代理是一个运行 Mosquitto 的 Raspberry Pi,我已经在我的 Android 手机和平板电脑上使用应用程序对其进行了测试。我在手机和平板电脑之间双向成功发布/订阅。
我是 Lua 新手,只了解 MQTT 的基础知识,如果有人能提供帮助,我不知道 m:connect(...) 块有什么问题。
更新:问题已解决 - 很抱歉没有尽快回到这个帖子。问题只是因为我在我的 RPi 上运行的 Mosquitto 版本(它符合 MQTT v3.1)。 NodeMCU MQTT 库支持 MQTT v3.1.1 并且不向后兼容。本质上,我的代码并没有太大的问题,尽管我确实做了一些更改 - 只是因为 MQTT 版本不兼容。
【问题讨论】:
-
我猜你的连接尝试失败了,所以什么也没有发生。你预计会发生什么?
-
你解决了吗,结案了?
-
@MarcelStör:我在原始问题的末尾添加了更新/评论,解释了问题的原因。感谢您提供帮助 - 我确实根据您的建议修改了我的代码,但我不得不“清理”我的 RPi 以强制下载更新版本的 Mosquitto 以使工作正常。
-
啊,很高兴知道。您不想将其添加为自我接受的答案吗?恕我直言,无需将其显示在未解决的 NodeMCU 问题列表中。
-
@MarcelStör:当然。当我查看我为解决问题所做的工作时,我会添加一个答案(我现在不记得确切)我目前正在努力解决我应该尽快解决的 C++ / Arduino ESP8266 问题. :)