NodeMCU文档中文翻译 6 MQTT模块

本文详细介绍了一个遵循MQTT 3.1.1协议的客户端库,包括客户端的创建、连接、发布消息、订阅主题等核心功能及其使用方法。

一、译文 

MQTT客户端支持Mqtt3.1.1协议,要确保你的MQTT服务器配置正确并支持3.1.1版本。此Mqtt模块并不兼容3.1版本之前的MQTT服务器。

mqtt.Client() 创建一个MQTT客户端.
mqtt.client:close() 关闭与服务器之间的连接.
mqtt.client:connect() 根据主机名、端口号和安全配置连接服务器.
mqtt.client:lwt() 创建遗嘱 (可选).
mqtt.client:on() 为事件创建回调函数.
mqtt.client:publish() 发送一条消息.
mqtt.client:subscribe() 订阅一个或多个主题.
mqtt.client:unsubscribe() 取消订阅一个或多个主题.

1、mqtt.Client()

创建一个MQTT客户端。

语法(PS:中括号内为可选参数)

mqtt.Client(clientid, keepalive[, username, password, cleansession])

参数

  • clientid 客户端id
  • keepalive 心跳秒数
  • username 用户名
  • password 密码
  • cleansession 清除session  0/1 表示 /

返回

Mqtt客户端

示例代码

[javascript]  view plain  copy
  1. -- 初始化无需登陆的客户端, 心跳时间 120秒  
  2. m = mqtt.Client("clientid", 120)  
  3.   
  4. -- 初始化需要登陆的客户端, 心跳时间 120秒  
  5. m = mqtt.Client("clientid", 120, "user""password")  
  6.   
  7. -- 创建遗嘱(可选)  
  8. -- 服务器将会发送一条 qos = 0, retain = 0, 内容为"offline"的消息到"/lwt"主题,如果没收到客户端发送的心跳数据包(掉线)   
  9. m:lwt("/lwt""offline", 0, 0)  
  10.   
  11. m:on("connect"function(client) print ("connected") end) --连接到服务器触发事件  
  12. m:on("offline"function(client) print ("offline") end) --掉线触发事件  
  13.   
  14. -- 收到消息时触发事件  
  15. m:on("message"function(client, topic, data)   
  16.   print(topic .. ":" )   
  17.   if data ~= nil then  
  18.     print(data)  
  19.   end  
  20. end)  
  21.   
  22. -- 对于 TLS: m:connect("192.168.11.118", secure-port, 1)  
  23. m:connect("192.168.11.118", 1883, 0, function(client) print("connected") end,   
  24.                                      function(client, reason) print("failed reason: "..reason) end)  
  25.   
  26. -- 确保subscribe/publish方法在连接上服务器后再调用,在实际应用中是把他们放在connect回调函数里或者确定连接成功  
  27.   
  28. -- 订阅/topic主题、服务质量为0  
  29. m:subscribe("/topic",0, function(client) print("subscribe success") end)  
  30. -- 发送一条信息 data = hello, QoS = 0, retain = 0  
  31. m:publish("/topic","hello",0,0, function(client) print("sent") end)  
  32.   
  33. m:close();  
  34. -- 你可以再次调用 m:connect 连接函数  

2、mqtt.client:close()

关闭与服务器的连接

语法   mqtt:close()
参数 

返回 成功true,失败false

3、mqtt.client:connect()

根据主机名、端口号和安全配置连接服务器。
语法
  mqtt:connect(host[, port[, secure[, autoreconnect]]][, function(client)[, function(client, reason)]])
参数
  • host 主机名, 域名或 IP (字符串)
  • port 服务器端口(数字), 默认1883
  • secure 0/1 表示 false/true, 默认 0. 详情查看文档 net module.
  • autoreconnect 0/1表示 false/true,默认 0 (断线是否重连)
  • function(client) 连接服务器成功时的回调函数
  • function(client, reason) 连接服务器失败时的回调函数
返回 
成功 true,失败 false
连接失败时的错误代码
常量 描述
mqtt.CONN_FAIL_SERVER_NOT_FOUND -5 未找到服务器(或没开端口)
mqtt.CONN_FAIL_NOT_A_CONNACK_MSG -4 返回消息回应不是Mqtt协议
mqtt.CONN_FAIL_DNS -3 DNS错误
mqtt.CONN_FAIL_TIMEOUT_RECEIVING -2 等待响应超时
mqtt.CONN_FAIL_TIMEOUT_SENDING -1 尝试发送连接消息超时
mqtt.CONNACK_ACCEPTED 0 没有错误. 注意: 这不会触发错误回调函数.
mqtt.CONNACK_REFUSED_PROTOCOL_VER 1 服务器MQTT版本不是3.1.1.
mqtt.CONNACK_REFUSED_ID_REJECTED 2 ClientID被服务器拒绝. (查看mqtt.Client())
mqtt.CONNACK_REFUSED_SERVER_UNAVAILABLE 3 服务不可用.
mqtt.CONNACK_REFUSED_BAD_USER_OR_PASS 4 用户名或密码错误.
mqtt.CONNACK_REFUSED_NOT_AUTHORIZED 5 用户名没经过认证.

4、mqtt.client:lwt()

创建遗嘱(可选),服务器将会发送一条 qos = 0, retain = 0, 内容为"offline"的消息到"/lwt"主题,如果没收到客户端发送的心跳数据包(掉线)。
语法
mqtt:lwt(topic, message[, qos[, retain]])
参数
  • topic 将要发送遗嘱消息的主题 (字符串)
  • message 遗嘱消息, (缓存 或 字符串)
  • qos 消息质量, 默认 0
  • retain 保留标志, 默认 0
返回 

5、mqtt.client:on()

为事件创建回调函数.
语法
mqtt:on(event, function(client[, topic[, message]]))
参数
  • event 可以是 "connect", "message" 或者 "offline"
  • function(client[, topic[, message]]) 回调函数。第一个参数为client、如果事件为 "message",那么第二个、第三个参数分别是主题和接收到的消息
返回 

6、mqtt.client:publish()

发送一条消息.
语法
mqtt:publish(topic, payload, qos, retain[, function(client)])
参数
  • topic 要发送消息的主题 (字符串)
  • message 消息, (缓存 或 字符串)
  • qos 消息质量
  • retain 消息保留标志
  • function(client) 可选的回调函数。当消息发送成功(服务器传来PUBACK响应)则触发该事件。注意:当多次调用publish() 函数,所有的发送指令将会调用最后定义的回调函数。
返回 
成功 true失败 false

7、mqtt.client:subscribe()

订阅一个或多个主题.
语法
mqtt:subscribe(topic, qos[, function(client)])   mqtt:subscribe(table[, function(client)])
参数
  • topic 主题 (字符串)
  • qos 订阅的消息质量, 默认 0
  • table 要订阅的'topic, qos'数组对
  • function(client) 订阅成功时的可选回调函数.注意:当多次调用subscribe() 函数,所有的订阅指令将会调用最后定义的回调函数。
返回 
成功 true失败 false
示例代码
[javascript]  view plain  copy
  1. -- 订阅/topic主题、服务质量为0  
  2. m:subscribe("/topic",0, function(conn) print("subscribe success") end)  
  3.   
  4. -- 或者订阅多个主题 (topic/0, qos = 0; topic/1, qos = 1; topic2 , qos = 2)  
  5. m:subscribe({["topic/0"]=0,["topic/1"]=1,topic2=2}, function(conn) print("subscribe success") end)  

8、mqtt.client:unsubscribe()

取消订阅一个或多个主题.
语法
mqtt:unsubscribe(topic[, function(client)]) 或   mqtt:unsubscribe(table[, function(client)])
参数
  • topic 主题 (字符串)
  • table 要取消订阅的'topic, qos'数组对
  • function(client) 取消订阅成功时的可选回调函数.注意:当多次调用unsubscribe() 函数,所有的取消订阅指令将会调用最后定义的回调函数。
返回 
成功 true失败 false
示例代码
[javascript]  view plain  copy
  1. -- 取消订阅主题  
  2. m:unsubscribe("/topic"function(conn) print("unsubscribe success") end)  
  3.   
  4. -- 或者取消订阅多个主题 (topic/0; topic/1; topic2)  
  5. m:unsubscribe({["topic/0"]=0,["topic/1"]=0,topic2="anything"}, function(conn) print("unsubscribe success") end)  


MQTT Module

Since Origin / Contributor Maintainer Source
2015-01-23 Stephen RobinsonTuan PM Vowstar mqtt.c

The client adheres to version 3.1.1 of the MQTT protocol. Make sure that your broker supports and is correctly configured for version 3.1.1. The client is backwards incompatible with brokers running MQTT 3.1.

mqtt.Client() Creates a MQTT client.
mqtt.client:close() Closes connection to the broker.
mqtt.client:connect() Connects to the broker specified by the given host, port, and secure options.
mqtt.client:lwt() Setup Last Will and Testament (optional).
mqtt.client:on() Registers a callback function for an event.
mqtt.client:publish() Publishes a message.
mqtt.client:subscribe() Subscribes to one or several topics.
mqtt.client:unsubscribe() Unsubscribes from one or several topics.

mqtt.Client()

Creates a MQTT client.

Syntax

mqtt.Client(clientid, keepalive[, username, password, cleansession])

Parameters
  • clientid client ID
  • keepalive keepalive seconds
  • username user name
  • password user password
  • cleansession 0/1 for false/true
Returns

MQTT client

Example
-- init mqtt client without logins, keepalive timer 120s
m = mqtt.Client("clientid", 120)

-- init mqtt client with logins, keepalive timer 120sec
m = mqtt.Client("clientid", 120, "user", "password")

-- setup Last Will and Testament (optional)
-- Broker will publish a message with qos = 0, retain = 0, data = "offline" 
-- to topic "/lwt" if client don't send keepalive packet
m:lwt("/lwt", "offline", 0, 0)

m:on("connect", function(client) print ("connected") end)
m:on("offline", function(client) print ("offline") end)

-- on publish message receive event
m:on("message", function(client, topic, data) 
  print(topic .. ":" ) 
  if data ~= nil then
    print(data)
  end
end)

-- for TLS: m:connect("192.168.11.118", secure-port, 1)
m:connect("192.168.11.118", 1883, 0, function(client) print("connected") end, 
                                     function(client, reason) print("failed reason: "..reason) end)

-- Calling subscribe/publish only makes sense once the connection
-- was successfully established. In a real-world application you want
-- move those into the 'connect' callback or make otherwise sure the 
-- connection was established.

-- subscribe topic with qos = 0
m:subscribe("/topic",0, function(client) print("subscribe success") end)
-- publish a message with data = hello, QoS = 0, retain = 0
m:publish("/topic","hello",0,0, function(client) print("sent") end)

m:close();
-- you can call m:connect again

MQTT Client

mqtt.client:close()

Closes connection to the broker.

Syntax

mqtt:close()

Parameters

none

Returns

true on success, false otherwise

mqtt.client:connect()

Connects to the broker specified by the given host, port, and secure options.

Syntax

mqtt:connect(host[, port[, secure[, autoreconnect]]][, function(client)[, function(client, reason)]])

Parameters
  • host host, domain or IP (string)
  • port broker port (number), default 1883
  • secure 0/1 for false/true, default 0. Take note of constraints documented in the net module.
  • autoreconnect 0/1 for false/true, default 0
  • function(client) callback function for when the connection was established
  • function(client, reason) callback function for when the connection could not be established
Returns

true on success, false otherwise

Connection failure callback reason codes:
Constant Value Description
mqtt.CONN_FAIL_SERVER_NOT_FOUND -5 There is no broker listening at the specified IP Address and Port
mqtt.CONN_FAIL_NOT_A_CONNACK_MSG -4 The response from the broker was not a CONNACK as required by the protocol
mqtt.CONN_FAIL_DNS -3 DNS Lookup failed
mqtt.CONN_FAIL_TIMEOUT_RECEIVING -2 Timeout waiting for a CONNACK from the broker
mqtt.CONN_FAIL_TIMEOUT_SENDING -1 Timeout trying to send the Connect message
mqtt.CONNACK_ACCEPTED 0 No errors. Note: This will not trigger a failure callback.
mqtt.CONNACK_REFUSED_PROTOCOL_VER 1 The broker is not a 3.1.1 MQTT broker.
mqtt.CONNACK_REFUSED_ID_REJECTED 2 The specified ClientID was rejected by the broker. (Seemqtt.Client())
mqtt.CONNACK_REFUSED_SERVER_UNAVAILABLE 3 The server is unavailable.
mqtt.CONNACK_REFUSED_BAD_USER_OR_PASS 4 The broker refused the specified username or password.
mqtt.CONNACK_REFUSED_NOT_AUTHORIZED 5 The username is not authorized.

mqtt.client:lwt()

Setup Last Will and Testament (optional). A broker will publish a message with qos = 0, retain = 0, data = "offline" to topic "/lwt" if client does not send keepalive packet.

Syntax

mqtt:lwt(topic, message[, qos[, retain]])

Parameters
  • topic the topic to publish to (string)
  • message the message to publish, (buffer or string)
  • qos QoS level, default 0
  • retain retain flag, default 0
Returns

nil

mqtt.client:on()

Registers a callback function for an event.

Syntax

mqtt:on(event, function(client[, topic[, message]]))

Parameters
  • event can be "connect", "message" or "offline"
  • function(client[, topic[, message]]) callback function. The first parameter is the client. If event is "message", the 2nd and 3rd param are received topic and message (strings).
Returns

nil

mqtt.client:publish()

Publishes a message.

Syntax

mqtt:publish(topic, payload, qos, retain[, function(client)])

Parameters
  • topic the topic to publish to (topic string)
  • message the message to publish, (buffer or string)
  • qos QoS level
  • retain retain flag
  • function(client) optional callback fired when PUBACK received. NOTE: When calling publish() more than once, the last callback function defined will be called for ALL publish commands.
Returns

true on success, false otherwise

mqtt.client:subscribe()

Subscribes to one or several topics.

Syntax

mqtt:subscribe(topic, qos[, function(client)]) mqtt:subscribe(table[, function(client)])

Parameters
  • topic a topic string
  • qos QoS subscription level, default 0
  • table array of 'topic, qos' pairs to subscribe to
  • function(client) optional callback fired when subscription(s) succeeded. NOTE: When calling subscribe() more than once, the last callback function defined will be called for ALL subscribe commands.
Returns

true on success, false otherwise

Example
-- subscribe topic with qos = 0
m:subscribe("/topic",0, function(conn) print("subscribe success") end)

-- or subscribe multiple topic (topic/0, qos = 0; topic/1, qos = 1; topic2 , qos = 2)
m:subscribe({["topic/0"]=0,["topic/1"]=1,topic2=2}, function(conn) print("subscribe success") end)

mqtt.client:unsubscribe()

Unsubscribes from one or several topics.

Syntax

mqtt:unsubscribe(topic[, function(client)]) mqtt:unsubscribe(table[, function(client)])

Parameters
  • topic a topic string
  • table array of 'topic, anything' pairs to unsubscribe from
  • function(client) optional callback fired when unsubscription(s) succeeded. NOTE: When calling unsubscribe() more than once, the last callback function defined will be called for ALL unsubscribe commands.
Returns

true on success, false otherwise

Example
-- unsubscribe topic
m:unsubscribe("/topic", function(conn) print("unsubscribe success") end)

-- or unsubscribe multiple topic (topic/0; topic/1; topic2)
m:unsubscribe({["topic/0"]=0,["topic/1"]=0,topic2="anything"}, function(conn) print("unsubscribe success") end)
<think>好的,用户想找关于D1迷你版NodeMCU使用Lua语言通过WiFi连接到MQTT云平台的教程或方案。我需要结合之前的引用内容来给出合适的回答。 首先,用户提到的D1 Mini NodeMCU,应该是指基于ESP8266的开发板,使用Lua语言编程。引用4中提到了NodeMCU的HTTP方法,可能相关的网络连接部分。但用户需要的是MQTT连接,所以可能需要更具体的步骤。 引用1提到WiFi模块初始化过程,如果初始化失败需要检查接线和热点。这说明在连接WiFi时,用户需要确保正确的SSID和密码,以及2.4GHz频段的热点可用。这一步在连接MQTT之前是必须的,所以教程的第一步应该是配置WiFi。 引用2提到了使用esptool刷写固件到NodeMCU,用户可能需要确认他们的NodeMCU固件是否包含MQTT和WiFi模块。如果默认固件没有,可能需要重新烧录包含这些模块的固件,比如使用自定义编译的固件,包含mqtt、wifi、net等模块。 引用3提到MQTT客户端ID必须唯一,否则会冲突。所以在编写Lua代码时,需要确保每个设备的client id不同,避免被服务器踢下线。 引用4中的HTTP方法可能和MQTT无关,但展示了NodeMCU Lua的网络请求方式,可能可以类比到MQTT的连接方法。需要查阅NodeMCU文档,找到mqtt库的使用方法。 现在,我需要将这些信息整合成一个步骤指南。首先初始化WiFi,然后连接到MQTT服务器,确保client id唯一,并处理订阅和发布。可能需要示例代码,使用Lua的mqtt函数,比如mqtt.Client()创建客户端,然后连接到服务器,设置回调函数处理消息。 此外,用户可能需要测试连接,例如使用MQTT.fx客户端验证消息收发,但要注意client id不要重复,如引用3所述。引用2中的esptool命令可能需要用户先刷写正确的固件,所以步骤中应包括固件烧录的指导,或者确认固件版本是否支持MQTT。 可能的问题包括WiFi连接失败,这时候需要检查热点设置;MQTT连接失败,检查服务器地址、端口、用户名密码;以及client id冲突的问题。需要提醒用户注意这些点。 最后,生成相关问题,帮助用户深入解决可能遇到的问题,比如固件烧录、连接参数配置、调试方法等。</think>根据引用内容和NodeMCU Lua开发要求,以下是D1 Mini连接MQTT云平台的完整实现方案: ### 一、硬件准备 1. 确认D1 Mini已正确烧录包含WIFI和MQTT模块的固件(建议使用自定义编译固件) ```bash # 参考引用[2]的烧录命令格式 python esptool.py --port COMx write_flash -fm dio 0x00000 firmware.bin ``` ### 二、Lua连接代码实现 ```lua -- 初始化WIFI模块(引用[1]的硬件初始化要求) wifi.setmode(wifi.STATION) wifi.sta.config("SSID", "PASSWORD") wifi.sta.connect() -- 等待WIFI连接 tmr.create():alarm(1000, tmr.ALARM_AUTO, function() if wifi.sta.getip() then tmr.stop() mqtt_connect() end end) -- MQTT连接函数(引用[3]的client ID要求) function mqtt_connect() local m = mqtt.Client("D1MINI_"..node.chipid(), 120, "username", "password") m:on("connect", function(client) print("MQTT Connected") client:subscribe("/nodemcu/#", 0) end) m:on("message", function(client, topic, data) print("Received:"..topic..":"..data) end) m:connect("mqtt.server.com", 1883, false, function(client) print("Connection failed!") end) end ``` ### 三、关键参数配置 1. MQTT服务器地址:根据云平台要求填写 2. 认证信息:多数云平台需要token/clientid(引用[3]) 3. 消息主题设计建议: - 发布主题:/device/{chipid}/sensor - 订阅主题:/device/{chipid}/control ### 四、调试要点 1. 使用串口监视器查看连接状态 2. 通过LED指示灯显示连接阶段(引用[1]的硬件状态反馈) 3. 测试命令示例: ```lua -- 发布测试消息 m:publish("/nodemcu/test", "hello", 0, 0) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值