我对 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 版本不兼容。