天天看點

NodeMCU文檔中文翻譯 6 MQTT子產品【本文出處:http://blog.csdn.net/leytton/article/details/72454287】一、譯文 【轉載請注明出處:http://blog.csdn.net/leytton/article/details/72454287】二、原文 MQTT Module MQTT Client

【本文出處:http://blog.csdn.net/leytton/article/details/72454287】

一、譯文 

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用戶端

示例代碼

-- 初始化無需登陸的用戶端, 心跳時間 120秒
m = mqtt.Client("clientid", 120)

-- 初始化需要登陸的用戶端, 心跳時間 120秒
m = mqtt.Client("clientid", 120, "user", "password")

-- 建立遺囑(可選)
-- 伺服器将會發送一條 qos = 0, retain = 0, 内容為"offline"的消息到"/lwt"主題,如果沒收到用戶端發送的心跳資料包(掉線) 
m:lwt("/lwt", "offline", 0, 0)

m:on("connect", function(client) print ("connected") end) --連接配接到伺服器觸發事件
m:on("offline", function(client) print ("offline") end) --掉線觸發事件

-- 收到消息時觸發事件
m:on("message", function(client, topic, data) 
  print(topic .. ":" ) 
  if data ~= nil then
    print(data)
  end
end)

-- 對于 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)

-- 確定subscribe/publish方法在連接配接上伺服器後再調用,在實際應用中是把他們放在connect回調函數裡或者确定連接配接成功

-- 訂閱/topic主題、服務品質為0
m:subscribe("/topic",0, function(client) print("subscribe success") end)
-- 發送一條資訊 data = hello, QoS = 0, retain = 0
m:publish("/topic","hello",0,0, function(client) print("sent") end)

m:close();
-- 你可以再次調用 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

沒有錯誤. 注意: 這不會觸發錯誤回調函數.

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

示例代碼

-- 訂閱/topic主題、服務品質為0
m:subscribe("/topic",0, function(conn) print("subscribe success") end)

-- 或者訂閱多個主題 (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)
           

8、mqtt.client:unsubscribe()

取消訂閱一個或多個主題. 文法

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

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

參數

  • topic

     主題 (字元串)
  • table

     要取消訂閱的'topic, qos'數組對
  • function(client)

     取消訂閱成功時的可選回調函數.注意:當多次調用unsubscribe() 函數,所有的取消訂閱指令将會調用最後定義的回調函數。

傳回  成功 true,失敗 false

示例代碼

-- 取消訂閱主題
m:unsubscribe("/topic", function(conn) print("unsubscribe success") end)

-- 或者取消訂閱多個主題 (topic/0; topic/1; topic2)
m:unsubscribe({["topic/0"]=0,["topic/1"]=0,topic2="anything"}, function(conn) print("unsubscribe success") end)
           

【轉載請注明出處:http://blog.csdn.net/leytton/article/details/72454287】

二、原文

摘自 https://nodemcu.readthedocs.io/en/master/en/modules/mqtt/

MQTT Module

Since Origin / Contributor Maintainer Source
2015-01-23 Stephen Robinson, Tuan 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", )

-- init mqtt client with logins, keepalive timer 120sec
m = mqtt.Client("clientid", , "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", , )

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", , , 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",, function(client) print("subscribe success") end)
-- publish a message with data = hello, QoS = 0, retain = 0
m:publish("/topic","hello",,, 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

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. (See

mqtt.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",, 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"]=,["topic/1"]=,topic2=}, 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"]=,["topic/1"]=,topic2="anything"}, function(conn) print("unsubscribe success") end)
           

轉載于:https://www.cnblogs.com/leytton/p/8253271.html