mqtt - mqtt Client#
Adapted Air780E Air780EP
Note
This page document is automatically generated by this file. If there is any error, please submit issue or help modify pr, thank you!
Tip
This library has its own demo,click this link to view the demo example of mqtt
Example
-- Please see the specific usage demo
-- this library only supports mqtt 3.1.1, other versions such as 3.1 or 5 are not supported!!!
-- Only pure MQTT/MQTTS communication is supported. mqtt over websocket
-- several major premises:
-- This library is based on TCP links and supports encrypted TCP and non-encrypted TCP
-- Any communication failure will disconnect. If automatic reconnect is turned on, automatic reconnect will start after an interval of N seconds.
-- Uplink data are all one-time, there is no cache mechanism, and there is no uplink retry/retransmission mechanism.
-- How to know that the sending was successful: trigger the event = = "sent" event in mqttc:on
-- Regarding the explanation of QOS value at publish, the behavior of the special module ascending to the cloud/server side:
-- QOS0, Push the underlying TCP send stack as a success
-- QOS1, Receive server response PUBACK, considered successful
-- QOS2, After receiving the server response PUBREC, the uplink PUBCOMP is immediately pushed into the TCP send queue and regarded as successful.
-- The important thing is said three times: no retransmission mechanism, no retransmission mechanism, no retransmission mechanism
-- 1. MQTT A retransmission mechanism is specified in the protocol, but that is a mechanism that will only be implemented on the cloud/server side, not on the module side.
-- 2. The only possibility of uplink failure is that there is a problem with the TCP link, and the solution to the problem with the TCP link is reconnection.
-- 3. The module side will not save any uplink data, and retransmission cannot be realized after reconnection.
-- The business needs to determine whether the uplink is successful and how to solve it.:
-- First recommend use QOS1, then monitor/judge sent events, and select a timeout period to meet 99.9 percent of the demand.
-- With QOS2, there is a theoretical possibility that the server side does not broadcast data due to PUBCOMP uplink failure.
-- demo There is a code that demonstrates waiting for the sent event, similar to sys.waitUntil("mqtt_sent", 3000) to search for mqtt_sent keywords.
Constant#
constant |
type |
explanation |
---|---|---|
mqtt.STATE_DISCONNECT |
number |
mqtt Disconnect |
mqtt.STATE_SCONNECT |
number |
mqtt socket In connection |
mqtt.STATE_MQTT |
number |
mqtt socket Connected mqtt connection in process |
mqtt.STATE_READY |
number |
mqtt mqtt Connected |
mqttc:subscribe(topic, qos)#
Subscribe to Topic
Parameters
Incoming Value Type |
Explanation |
---|---|
string/table |
Theme |
int |
topic 0/1/2 Default 0 |
Return Value
return value type |
explanation |
---|---|
int |
Message id, valid when qos is 1/2, if the bottom layer fails to return, it will return nil |
Examples
-- Subscribe to a single topic, and qos=0
mqttc:subscribe("/luatos/123456", 0)
-- Subscribe to a single topic, and qos=1
mqttc:subscribe("/luatos/12345678", 1)
-- subscribe to multiple topics and use different qos
mqttc:subscribe({["/luatos/1234567"]=1,["/luatos/12345678"]=2})
mqttc:unsubscribe(topic)#
Unsubscribe from a topic
Parameters
Incoming Value Type |
Explanation |
---|---|
string/table |
Theme |
Return Value
None
Examples
mqttc:unsubscribe("/luatos/123456")
mqttc:unsubscribe({"/luatos/1234567","/luatos/12345678"})
mqttc:debug(onoff)#
Configure whether to open debug information
Parameters
Incoming Value Type |
Explanation |
---|---|
boolean |
Whether to turn on debug switch |
Return Value
return value type |
explanation |
---|---|
nil |
No return value |
Examples
None
mqtt.create(adapter,host,port,ssl,isipv6)#
mqtt Client Creation
Parameters
Incoming Value Type |
Explanation |
---|---|
int |
The adapter serial number can only be socket.ETH0, socket.STA, socket.AP. If it is not filled in, the platform’s own method will be selected, and then the last registered adapter will be selected. |
string |
Server address, which can be a domain name or ip |
int |
Port number |
bool/table |
Whether it is an ssl encrypted connection or not, default is no encryption, true is the simplest encryption without certificate, table is encryption with certificate |
bool/table |
bool Whether ipv6 is ipv6, the default value is not the table mqtt extension parameter, whether ipv6 is ipv6, rxSize receive buffer size |
Return Value
return value type |
explanation |
---|---|
userdata |
if successful, the mqtt client instance is returned. otherwise, the mqtt client instance is returned.nil |
Examples
-- Common TCP Link
mqttc = mqtt.create(nil,"120.55.137.106", 1884)
-- Normal TCP link, mqtt receive buffer 4096
mqttc = mqtt.create(nil,"120.55.137.106", 1884, nil, {rxSize = 4096})
-- Encrypt TCP link without validating server certificate
mqttc = mqtt.create(nil,"120.55.137.106", 8883, true)
-- Encrypted TCPTCP link, single server certificate validation
mqttc = mqtt.create(nil,"120.55.137.106", 8883, {server_cert=io.readFile("/luadb/ca.crt")})
-- Encrypted TCPTCP link, single server certificate validation, but optional authentication
mqttc = mqtt.create(nil,"120.55.137.106", 8883, {server_cert=io.readFile("/luadb/ca.crt"), verify=1})
-- Encrypted TCPTCP link, two-way certificate verification
mqttc = mqtt.create(nil,"120.55.137.106", 8883, {
server_cert=io.readFile("/luadb/ca.crt"),
client_cert=io.readFile("/luadb/client.pem"),
client_key="123456",
client_password="123456",
})
mqttc:auth(client_id,username,password,cleanSession)#
mqtt Triple configuration and cleanSession
Parameters
Incoming Value Type |
Explanation |
---|---|
string |
the device id must be unique for the same mqtt server. the same client_id will be kicked off each other. |
string |
Account Number Optional |
string |
Password optional |
bool |
Clear session, default true, optional |
Return Value
return value type |
explanation |
---|---|
nil |
No return value |
Examples
-- Login without account password, only clientId
mqttc:auth("123456789")
-- Login with account password
mqttc:auth("123456789","username","password")
-- Additional configuration cleanSession, do not clear
mqttc:auth("123456789","username","password", false)
-- no clientId mode, the server randomly generates an id, the cleanSession is not configurable
mqttc:auth()
mqttc:keepalive(time)#
mqtt Heartbeat Settings
Parameters
Incoming Value Type |
Explanation |
---|---|
int |
Optional unit s defaults to 240s. first 15, highest 600 |
Return Value
return value type |
explanation |
---|---|
nil |
No return value |
Examples
mqttc:keepalive(30)
mqttc:on(cb)#
register mqtt callback
Parameters
Incoming Value Type |
Explanation |
---|---|
function |
cb mqtt callback, parameters include mqtt_client, event, data, payload |
Return Value
return value type |
explanation |
---|---|
nil |
No return value |
Examples
mqttc:on(function(mqtt_client, event, data, payload, metas)
-- User-defined code
log.info("mqtt", "event", event, mqtt_client, data, payload)
end)
--[[
event The possible values are
conack -- the server authentication is completed, the mqtt connection has been established, and data can be subscribed and published without additional data.
recv -- The received data is delivered by the server, data is the topic value (string), payload is the business data (string), metas is metadata (table), generally not processed. .
-- metas Contains the following
-- qos Value range 0,1,2
-- retain Value range 0,1
-- dup Value range 0,1
sent -- After the sending is completed, qos0 will notify immediately, qos1/qos2 will call back in the server response, and data is a message.id
disconnect -- The server is disconnected, network problems or the server kicks the client, such as duplicate clientId, timeout not reporting business data
pong -- Received server heartbeat reply, no additional data
]]
mqttc:connect()#
Connection Server
Parameters
None
Return Value
return value type |
explanation |
---|---|
boolean |
Returns true if the launch is successful, otherwise false |
Examples
-- Start establishing a connection
mqttc:connect()
-- this function only indicates that the mqtt is successfully initiated. you need to determine whether the mqtt connection is normal according to the ready function.
mqttc:disconnect()#
Disconnect the server (resources are not released)
Parameters
None
Return Value
return value type |
explanation |
---|---|
boolean |
Returns true if the launch is successful, otherwise false |
Examples
-- Disconnect
mqttc:disconnect()
mqttc:autoreconn(reconnect, reconnect_time)#
Automatic reconnect
Parameters
Incoming Value Type |
Explanation |
---|---|
bool |
Auto reconnect |
int |
Auto reconnect cycle unit ms default 3000ms |
Return Value
None
Examples
mqttc:autoreconn(true)
mqttc:publish(topic, data, qos, retain)#
Publish message
Parameters
Incoming Value Type |
Explanation |
---|---|
string |
Subject, required |
string |
Message, required, but length can be 0 |
int |
Message Level 0/1 Default 0 |
int |
Archive, 0/1, default 0 |
Return Value
return value type |
explanation |
---|---|
int |
the id of the message, which is valid when qos is 1 or 2. if no is returned from the bottom layer, the value is returned.nil |
Examples
mqttc:publish("/luatos/123456", "123")
mqttc:close()#
mqtt Client shutdown (resources released after shutdown can no longer be used)
Parameters
None
Return Value
None
Examples
mqttc:close()
mqttc:ready()#
mqtt Whether the client is ready
Parameters
None
Return Value
return value type |
explanation |
---|---|
bool |
Whether the client is ready |
Examples
local error = mqttc:ready()
mqttc:state()#
mqtt Client Status
Parameters
None
Return Value
return value type |
explanation |
---|---|
number |
Client Status |
Examples
local state = mqttc:state()
-- Known Status:
-- 0: MQTT_STATE_DISCONNECT
-- 1: MQTT_STATE_CONNECTING
-- 2: MQTT_STATE_CONNECTED
-- 3: MQTT_STATE_READY
-- 4: MQTT_STATE_ERROR
mqttc:will(topic, payload, qos, retain)#
Set Will Message
Parameters
Incoming Value Type |
Explanation |
---|---|
string |
The message of the will topic |
string |
The message of the will payload |
string |
Qos of will message, default 0, can not fill in |
string |
Retain of will message, default 0, can not fill in |
Return Value
return value type |
explanation |
---|---|
bool |
Returns true on success, otherwise false |
Examples
-- To call before connect
mqttc:will("/xxx/xxx", "xxxxxx")