我对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手机和平板电脑上使用应用程序对其进行了测试 . 我在两个方向上成功地在手机和平板电脑之间发布/订阅 .
我'm a Lua novice and only understand the basics of MQTT and I'米因为 m:connect(...)
块的错误而感到茫然,如果有人可以提供帮助,我将不胜感激 .
UPDATE: PROBLEM SOLVED - 抱歉没有早点回到这个主题 . 问题只是我在我的RPi上运行的Mosquitto版本(符合MQTT v3.1) . NodeMCU MQTT库支持MQTT v3.1.1,并且不向后兼容 . 本质上我的代码没有太大的错误,虽然我做了一些改变 - 它只是归结为MQTT版本不兼容 .
2 回答
您没有告诉我们您使用的NodeMCU版本 . 警告:请勿使用https://github.com/nodemcu/nodemcu-firmware/releases中提供的任何预构建的0.9.x二进制文件 . 根据http://nodemcu.readthedocs.io/en/dev/en/build/构建您自己的固件 .
我总是帮助剥离失败的函数并利用所有可用的回调函数 . 我可以在
dev
分支向cloudmqtt.com发送数据的近两个月的固件上确认以下工作:区别:
m:connect
明确定义安全y / n和自动重新连接y / n . 如果只设置了所有可选参数的子集,它总是让我感到困惑 .m:connect
中的0
被解释为secure
还是autoreconnect
?我不太清楚Lua为什么我明确地编码它 .对连接尝试失败的函数使用额外的回调函数 . 有关失败原因代码,请参阅http://nodemcu.readthedocs.org/en/dev/en/modules/mqtt/#connection-failure-callback-reason-codes .
不要在回调函数中使用与"parent"函数中使用的变量相同的名称 . 注意你如何使用
m:connect(..., function(conn)
然后在该函数内再次使用m:publish(..., function(conn)
. 您不与代码中的conn
对象进行交互,因此不会造成任何损害 . 但是,这可能会在其他项目中咬你 .你的代码看起来很好 . 如果m:connect失败,则不会发生任何事情,因为您没有为失败的连接尝试提供回调函数 .
另外,您不检查m:connect的返回值是否成功 .
参考http://nodemcu.readthedocs.org/en/dev/en/modules/mqtt/#mqttclientconnect
并检查您的连接尝试是否失败 .