Class Client
This class contains the MQTT client implementation.
client:on (events) |
Add functions as handlers of given events. |
client:off (event, func) |
Remove given function handler for specified event. |
client:subscribe (opts) |
Subscribe to specified topic. |
client:unsubscribe (opts) |
Unsubscribe from specified topic, and calls optional callback when subscription will be removed on broker |
client:publish (opts) |
Publish message to broker |
client:acknowledge (msg[, rc=0[, properties[, user_properties]]]) |
Acknowledge given received message |
client:disconnect ([rc=0[, properties[, user_properties]]]) |
Send DISCONNECT packet to the broker and close the connection. |
client:shutdown (...) |
Shuts the client down. |
client:auth ([rc=0[, properties[, user_properties]]]) |
Send AUTH packet to authenticate client on broker, in MQTT v5.0 protocol |
client:close_connection ([reason]) |
Immediately close established network connection, without graceful session finishing with DISCONNECT packet |
client:start_connecting () |
Start connecting to broker |
-
client:__init (opts)
-
Create and initialize MQTT client instance. Typically this is not called directly,
but through Client.create.
Parameters:
- opts MQTT client creation options table
- uri
string
MQTT broker uri to connect. Expected format:
[mqtt[s]://][username[:password]@]hostname[:port]
Any option specifically added to the options
table will take precedence over the option specified in this uri.
- clean
boolean or string
clean session start flag, use "first" to start clean only on first connect
- protocol
string
either
"mqtt"
or "mqtts"
(optional)
- username
string
username for authorization on MQTT broker
(optional)
- password
string
password for authorization on MQTT broker; not acceptable in absence of username
(optional)
- host
string
hostname of the MQTT broker to connect to
(optional)
- port
int
port number to connect to on the MQTT broker, defaults to
1883
port for plain or 8883
for secure network connections
(optional)
- version
number
MQTT protocol version to use, either
4
(for MQTT v3.1.1) or 5
(for MQTT v5.0).
Also you may use special values mqtt.v311
or mqtt.v50
for this field.
(default 4)
- id
string
MQTT client ID, will be generated by luamqtt library if absent
(optional)
- secure
boolean or table
use secure network connection, provided by the lua module set in
opts.ssl_module
.
Set to true to select default parameters, check individual mqtt.connectors
for supported options.
(default false)
- will
table
will message table with required fields
{ topic="...", payload="..." }
and optional fields { qos=0...2, retain=true/false }
(optional)
- keep_alive
number
time interval (in seconds) for client to send PINGREQ packets to the server when network connection is inactive
(default 60)
- reconnect
boolean
force created MQTT client to reconnect on connection close.
Set to number value to provide reconnect timeout in seconds.
It's not recommended to use values
< 3
. See also Client:shutdown.
(default false)
- connector
table
connector table to open and send/receive packets over network connection.
default is
require("mqtt.connector")
which tries to auto-detect. See mqtt.connector.
(optional)
- ssl_module
string
module name for the luasec-compatible ssl module, default is
"ssl"
may be used in some non-standard lua environments with own luasec-compatible ssl module
(default "ssl")
- on
table
List of event-handlers. See Client:on for the format.
(optional)
Returns:
Client
MQTT client instance table
Usage:
local Client = require "mqtt.client"
local my_client = Client.create {
uri = "mqtts://broker.host.com",
clean = "first",
version = mqtt.v50,
}
-
client:on (events)
-
Add functions as handlers of given events.
Parameters:
- events MQTT client creation options table
- connect
function
function(connack_packet, client_obj)
After a connect attempt, after receiving the CONNACK packet from the broker.
check connack_packet.rc == 0
for a succesful connect.
- error
function
function(errmsg, client_obj [, packet])
on errors, optional packet
is only provided if the
received CONNACK.rc ~= 0
when connecting.
- close
function
function(connection_obj, client_obj)
upon closing the connection. connection_obj.close_reason
(string) will hold the close reason.
- shutdown
function
function(client_obj)
upon shutting down the client (diconnecting an no more reconnects).
- subscribe
function
function(suback_packet, client_obj)
upon a succesful subscription, after receiving the SUBACK packet from the broker
- unsubscribe
function
function(unsuback_packet, client_obj)
upon a succesful unsubscription, after receiving the UNSUBACK packet from the broker
- message
function
function(publish_packet, client_obj)
upon receiving a PUBLISH packet from the broker
- acknowledge
function
function(ack_packet, client_obj)
upon receiving a PUBACK or PUBREC packet from the broker
- auth
function
function(auth_packet, client_obj)
upon receiving an AUTH packet
Usage:
client:on {
connect = function(pck, self)
if pck.rc ~= 0 then
return end
end,
message = function(pck, self)
end,
}
client:on("message", function(pck, self)
end)
-
client:off (event, func)
-
Remove given function handler for specified event.
Parameters:
- event
string
event name to remove handler
- func
function
handler function to remove
Usage:
local handler = function(pck, self)
end
client:on {
message = handler
}
client:off("message", handler)
-
client:subscribe (opts)
-
Subscribe to specified topic. Returns the SUBSCRIBE packet id and calls optional callback when subscription will be created on broker
Parameters:
- opts subscription options
- topic
string
topic to subscribe
- qos
number
QoS level for subscription
(default 0)
- no_local
boolean
for MQTT v5.0 only: no_local flag for subscription
- retain_as_published
boolean
for MQTT v5.0 only: retain_as_published flag for subscription
- retain_handling
boolean
for MQTT v5.0 only: retain_handling flag for subscription
- properties
table
for MQTT v5.0 only: properties for subscribe operation
(optional)
- user_properties
table
for MQTT v5.0 only: user properties for subscribe operation
(optional)
- callback
function
callback function to be called when subscription is acknowledged by broker
(optional)
Returns:
packet id on success or false and error message on failure
-
client:unsubscribe (opts)
-
Unsubscribe from specified topic, and calls optional callback when subscription will be removed on broker
Parameters:
- opts subscription options
- topic
string
topic to unsubscribe
- properties
table
properties for unsubscribe operation
(optional)
- user_properties
table
user properties for unsubscribe operation
(optional)
- callback
function
callback function to be called when the unsubscribe is acknowledged by the broker
(optional)
Returns:
packet id on success or false and error message on failure
-
client:publish (opts)
-
Publish message to broker
Parameters:
- opts publish operation options table
- topic
string
topic to publish message
- payload
string
publish message payload
(optional)
- qos
number
QoS level for message publication
(default 0)
- retain
boolean
retain message publication flag
(default false)
- dup
boolean
dup message publication flag
(default false)
- properties
table
properties for publishing message
(optional)
- user_properties
table
user properties for publishing message
(optional)
- callback
function
callback to call when published message has been acknowledged by the broker
(optional)
Returns:
true or packet id on success or false and error message on failure
-
client:acknowledge (msg[, rc=0[, properties[, user_properties]]])
-
Acknowledge given received message
Parameters:
- msg
packet_mt
PUBLISH message to acknowledge
- rc
number
The reason code field of PUBACK packet in MQTT v5.0 protocol
(default 0)
- properties
table
properties for PUBACK/PUBREC packets
(optional)
- user_properties
table
user properties for PUBACK/PUBREC packets
(optional)
Returns:
true on success or false and error message on failure
-
client:disconnect ([rc=0[, properties[, user_properties]]])
-
Send DISCONNECT packet to the broker and close the connection.
Note: if the client is set to automatically reconnect, it will do so. If you
want to disconnect and NOT reconnect, use Client:shutdown.
Parameters:
- rc
number
The Disconnect Reason Code value from MQTT v5.0 protocol
(default 0)
- properties
table
properties for PUBACK/PUBREC packets
(optional)
- user_properties
table
user properties for PUBACK/PUBREC packets
(optional)
Returns:
true on success or false and error message on failure
-
client:shutdown (...)
-
Shuts the client down.
Disconnects if still connected, and disables reconnecting. If the client is
added to an ioloop, this will prevent an automatic reconnect.
Raises the "shutdown" event.
Parameters:
Returns:
true
-
client:auth ([rc=0[, properties[, user_properties]]])
-
Send AUTH packet to authenticate client on broker, in MQTT v5.0 protocol
Parameters:
- rc
number
Authenticate Reason Code
(default 0)
- properties
table
properties for PUBACK/PUBREC packets
(optional)
- user_properties
table
user properties for PUBACK/PUBREC packets
(optional)
Returns:
true on success or false and error message on failure
-
client:close_connection ([reason])
-
Immediately close established network connection, without graceful session finishing with DISCONNECT packet
Parameters:
- reason
string
the reasong string of connection close
(optional)
-
client:start_connecting ()
-
Start connecting to broker
Returns:
true on success or false and error message on failure
-
client:send_pingreq ()
-
Send PINGREQ packet
Returns:
true on success or false and error message on failure
-
client:open_connection ()
-
Open network connection to the broker
Returns:
true on success or false and error message on failure
-
client:send_connect ()
-
Send CONNECT packet into opened network connection
Returns:
true on success or false and error message on failure
-
client:check_keep_alive ()
-
Checks last message send, and sends a PINGREQ if necessary.
Use this function to check and send keep-alives when using an external event loop. When using the
included modules to add clients (see mqtt.loop), this will be taken care of automatically.
Returns:
number
time till next keep_alive (in seconds)
Or
-
number
time till next keep_alive (in seconds)
-
string
in case of errors (eg. not connected) the second return value is an error string
Usage:
copas.addthread(function()
while true do
if not my_client then
return end
copas.pause(my_client:check_keep_alive())
end
end)
-
client:step ()
-
Performs a single IO loop step.
It will connect if not connected, will re-connect if set to.
This should be called repeatedly in a loop. When using the included modules to
add clients (see mqtt.loop), this will be taken care of automatically.
The return value is the time after which this method must be called again.
It can be called sooner, but shouldn't be called later.
Returns:
-1
: the socket read timed out, so it is idle. This return code is only
returned with buffered connectors (luasocket), never for yielding sockets
(Copas or OpenResty)
Or
0
: a packet was succesfully handled, so retry immediately, no delays,
in case additional data is waiting to be read on the socket.
Or
>0
: The reconnect timer needs a delay before it can retry (calling
sooner is not a problem, it will only reconnect when the delay
has actually passed)
Or
-
nil
-
error message
-
client.create (...)
-
Create, initialize and return new MQTT client instance
Parameters:
Returns:
Client
MQTT client instance
See also: