### Simple MQTT Client Example in Lua Source: https://xhaskx.github.io/luamqtt/examples/simple.lua.html This snippet demonstrates how to create an MQTT client, connect to a broker, subscribe to a topic, publish a message, and handle incoming messages. It uses the `mqtt.client` constructor and event handlers for connection, message reception, and errors. The `mqtt.run_ioloop` function is used to process network events. ```lua -- load mqtt module local mqtt = require("mqtt") -- create mqtt client local client = mqtt.client{ -- NOTE: this broker is not working sometimes; comment username = "..." below if you still want to use it -- uri = "test.mosquitto.org", uri = "mqtt.flespi.io", -- NOTE: more about flespi tokens: https://flespi.com/kb/tokens-access-keys-to-flespi-platform username = "stPwSVV73Eqw5LSv0iMXbc4EguS7JyuZR9lxU5uLxI5tiNM8ToTVqNpu85pFtJv9", clean = true, } print("created MQTT client", client) client:on{ connect = function(connack) if connack.rc ~= 0 then print("connection to broker failed:", connack:reason_string(), connack) return end print("connected:", connack) -- successful connection -- subscribe to test topic and publish message after it assert(client:subscribe{ topic="luamqtt/#", qos=1, callback=function(suback) print("subscribed:", suback) -- publish test message print('publishing test message "hello" to "luamqtt/simpletest" topic...') assert(client:publish{ topic = "luamqtt/simpletest", payload = "hello", qos = 1 }) end}) end, message = function(msg) assert(client:acknowledge(msg)) print("received:", msg) print("disconnecting...") assert(client:disconnect()) end, error = function(err) print("MQTT client error:", err) end, } print("running ioloop for it") mqtt.run_ioloop(client) print("done, ioloop is stopped") ``` -------------------------------- ### Synchronous MQTT Client Example Source: https://xhaskx.github.io/luamqtt/examples/sync.lua.html This snippet demonstrates how to create and use a synchronous MQTT client. It connects to a broker, subscribes to a topic, publishes a message, and handles incoming messages. Note that in synchronous mode, background PINGREQ and automatic reconnects are not available. ```lua -- load mqtt module local mqtt = require("mqtt") -- create mqtt client local client = mqtt.client{ -- NOTE: this broker is not working sometimes; comment username = "..." below if you still want to use it -- uri = "test.mosquitto.org", uri = "mqtt.flespi.io", -- NOTE: more about flespi tokens: https://flespi.com/kb/tokens-access-keys-to-flespi-platform username = "stPwSVV73Eqw5LSv0iMXbc4EguS7JyuZR9lxU5uLxI5tiNM8ToTVqNpu85pFtJv9", clean = true, } print("created MQTT client", client) client:on{ connect = function(connack) if connack.rc ~= 0 then print("connection to broker failed:", connack:reason_string(), connack) return end print("connected:", connack) -- successful connection -- subscribe to test topic and publish message after it assert(client:subscribe{ topic="luamqtt/#", qos=1, callback=function(suback) print("subscribed:", suback) -- publish test message print('publishing test message "hello" to "luamqtt/simpletest" topic...') assert(client:publish{ topic = "luamqtt/simpletest", payload = "hello", qos = 1 }) end}) end, message = function(msg) assert(client:acknowledge(msg)) print("received:", msg) print("disconnecting...") assert(client:disconnect()) end, error = function(err) print("MQTT client error:", err) end, close = function() print("MQTT conn closed") end } -- run io loop for client until connection close -- please note that in sync mode background PINGREQ's are not available, and automatic reconnects too print("running client in synchronous input/output loop") mqtt.run_sync(client) print("done, synchronous input/output loop is stopped") ``` -------------------------------- ### ioloop_mt:get Source: https://xhaskx.github.io/luamqtt/modules/mqtt.ioloop.html Retrieves the default ioloop instance, optionally creating it if it doesn't exist. ```APIDOC ## ioloop_mt:get ### Description Returns default ioloop instance ### Parameters: * autocreate (boolean) - Automatically create ioloop instance (default: true) * args (table) - Arguments for creating ioloop instance (optional) ### Returns: * ioloop_mt - ioloop instance ``` -------------------------------- ### MQTT v5.0 Client Connection and Messaging Source: https://xhaskx.github.io/luamqtt/examples/mqtt5-simple.lua.html This snippet demonstrates how to create an MQTT v5.0 client, connect to a broker, subscribe to a topic, publish a message, and handle incoming messages. It includes setting up connection and message callbacks, and managing client lifecycle. ```lua local mqtt = require("mqtt") -- create mqtt client local client = mqtt.client{ uri = "mqtt.flespi.io", -- NOTE: more about flespi tokens: https://flespi.com/kb/tokens-access-keys-to-flespi-platform username = "stPwSVV73Eqw5LSv0iMXbc4EguS7JyuZR9lxU5uLxI5tiNM8ToTVqNpu85pFtJv9", clean = true, version = mqtt.v50, } print("created MQTT v5.0 client:", client) client:on{ connect = function(connack) if connack.rc ~= 0 then print("connection to broker failed:", connack:reason_string(), connack) return end print("connected:", connack) -- successful connection -- subscribe to test topic and publish message after it assert(client:subscribe{ topic = "luamqtt/#", qos = 1, callback = function(suback) print("subscribed:", suback) -- publish test message print('publishing test message "hello" to "luamqtt/simpletest" topic...') assert(client:publish{ topic = "luamqtt/simpletest", payload = "hello", qos = 1, properties = { payload_format_indicator = 1, content_type = "text/plain", }, user_properties = { hello = "world", }, }) end }) end, message = function(msg) assert(client:acknowledge(msg)) print("received:", msg) print("disconnecting...") assert(client:disconnect()) end, error = function(err) print("MQTT client error:", err) end, } print("running ioloop for it") mqtt.run_ioloop(client) print("done, ioloop is stopped") ``` -------------------------------- ### create Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Creates and initializes a new MQTT client instance. Accepts arguments similar to the client_mt:__init method. ```APIDOC ## create (...) ### Description Create, initialize and return new MQTT client instance. ### Parameters * **...** - See arguments of client_mt:__init(args) ### Returns client_mt - MQTT client instance ### See also: client_mt:__init ``` -------------------------------- ### client_mt:start_connecting Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Initiates the connection process to the MQTT broker. ```APIDOC ## client_mt:start_connecting () ### Description Start connecting to broker. ### Returns true on success or false and error message on failure ``` -------------------------------- ### client_mt:start_connecting Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Initiates the process of connecting to the MQTT broker. This method should be called after client initialization to establish the network connection. ```APIDOC ## client_mt:start_connecting () ### Description Start connecting to broker. ``` -------------------------------- ### create Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Creates, initializes, and returns a new MQTT client instance. This is the primary function for obtaining a client object. ```APIDOC ## create (...) ### Description Create, initialize and return new MQTT client instance. ### Parameters: * ... - Arguments for client creation, passed to `client_mt:__init`. ``` -------------------------------- ### mqtt.client Source: https://xhaskx.github.io/luamqtt/modules/mqtt.html Creates a new MQTT client instance. The parameters are the same as for `mqtt.client.create`. ```APIDOC ## mqtt.client ### Description Create new MQTT client instance. ### Parameters: * ... Same as for mqtt.client.create(...) ### See also: __init ``` -------------------------------- ### client_mt:__init Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Creates and initializes a new MQTT client instance. It allows configuration of connection details, authentication, and session parameters. ```APIDOC ## client_mt:__init (args) ### Description Create and initialize MQTT client instance. ### Parameters: * args (table) - MQTT client creation arguments table * uri (string) - MQTT broker uri to connect. Expecting "host:port" or "host" format, in second case the port will be selected automatically: 1883 port for plain or 8883 for secure network connections * clean (boolean) - clean session start flag * 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. * id (string) - MQTT client ID, will be generated by luamqtt library if absent (_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_) * secure (boolean|table) - use secure network connection, provided by luasec lua module; set to true to select default params: { mode="client", protocol="tlsv1_2", verify="none", options="all" } or set to luasec-compatible table, for example with cafile="...", certificate="...", key="..." (_default_ false) * will (table) - will message table with required fields { topic="...", payload="..." } and optional fields { qos=1...3, retain=true/false } (_optional_) * keep_alive (number) - time interval for client to send PINGREQ packets to the server when network connection is inactive (_default_ 60) * reconnect (boolean|number) - 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 (_default_ false) * connector (table) - connector table to open and send/receive packets over network connection. default is require("mqtt.luasocket"), or require("mqtt.luasocket_ssl") if secure argument is set (_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") ### Returns: * client_mt (table) - MQTT client instance table ``` -------------------------------- ### ioloop_mt:__init Source: https://xhaskx.github.io/luamqtt/modules/mqtt.ioloop.html Initializes a new ioloop instance with optional arguments for network operation timeouts and sleep intervals. ```APIDOC ## ioloop_mt:__init ### Description Initialize ioloop instance ### Parameters: * args (table) - ioloop creation arguments table * timeout (number) - network operations timeout in seconds (default: 0.005) * sleep (number) - sleep interval after each iteration (default: 0) * sleep_function (function) - custom sleep function to call after each iteration (optional) ### Returns: * ioloop_mt - ioloop instance ``` -------------------------------- ### mqtt.get_ioloop Source: https://xhaskx.github.io/luamqtt/modules/mqtt.html Returns the default ioloop instance. ```APIDOC ## mqtt.get_ioloop ### Description Returns default ioloop instance. ### Parameters: None ``` -------------------------------- ### mqtt.run_sync Source: https://xhaskx.github.io/luamqtt/modules/mqtt.html Runs a synchronous input/output loop for a single MQTT client. This function opens the client's connection, but the client reconnect feature and keep-alive will not work. ```APIDOC ## mqtt.run_sync ### Description Run synchronous input/output loop for only one given MQTT client. Provided client's connection will be opened. Client reconnect feature will not work, and keep_alive too. ### Parameters: * cl MQTT client instance to run ``` -------------------------------- ### mqtt.run_ioloop Source: https://xhaskx.github.io/luamqtt/modules/mqtt.html Runs the default ioloop for the given MQTT clients or functions. ```APIDOC ## mqtt.run_ioloop ### Description Run default ioloop for given MQTT clients or functions. ### Parameters: * ... MQTT clients or lopp functions to add to ioloop ### See also: * mqtt.ioloop.get * mqtt.ioloop.run_until_clients ``` -------------------------------- ### Asynchronous MQTT Ping-Pong with Copas Source: https://xhaskx.github.io/luamqtt/examples/copas-example.lua.html This snippet demonstrates a ping-pong communication pattern using two LuaMQTT clients within the Copas ioloop. It requires the 'mqtt', 'copas', and 'mqtt.ioloop' modules. The 'ping' client sends a sequence of messages, and the 'pong' client receives and acknowledges them. Ensure a valid Flespi token is provided for authentication. ```lua -- example of using luamqtt inside copas ioloop: http://keplerproject.github.io/copas/index.html local mqtt = require("mqtt") local copas = require("copas") local mqtt_ioloop = require("mqtt.ioloop") local num_pings = 10 -- total number of ping-pongs local timeout = 1 -- timeout between ping-pongs local suffix = tostring(math.random(1000000)) -- mqtt topic suffix to distinct simultaneous running of this script -- NOTE: more about flespi tokens: https://flespi.com/kb/tokens-access-keys-to-flespi-platform local token = "stPwSVV73Eqw5LSv0iMXbc4EguS7JyuZR9lxU5uLxI5tiNM8ToTVqNpu85pFtJv9" local ping = mqtt.client{ uri = "mqtt.flespi.io", username = token, clean = true, version = mqtt.v50, } local pong = mqtt.client{ uri = "mqtt.flespi.io", username = token, clean = true, version = mqtt.v50, } ping:on{ connect = function(connack) assert(connack.rc == 0) print("ping connected") for i = 1, num_pings do copas.sleep(timeout) print("ping", i) assert(ping:publish{ topic = "luamqtt/copas-ping/"..suffix, payload = "ping"..i, qos = 1 }) end copas.sleep(timeout) print("ping done") assert(ping:publish{ topic = "luamqtt/copas-ping/"..suffix, payload = "done", qos = 1 }) ping:disconnect() end, error = function(err) print("ping MQTT client error:", err) end, } pong:on{ connect = function(connack) assert(connack.rc == 0) print("pong connected") assert(pong:subscribe{ topic="luamqtt/copas-ping/"..suffix, qos=1, callback=function(suback) assert(suback.rc[1] > 0) print("pong subscribed") end }) end, message = function(msg) print("pong: received", msg.payload) assert(pong:acknowledge(msg)) if msg.payload == "done" then print("pong done") pong:disconnect() end end, error = function(err) print("pong MQTT client error:", err) end, } print("running copas loop...") copas.addthread(function() local ioloop = mqtt_ioloop.create{ sleep = 0.01, sleep_function = copas.sleep } ioloop:add(ping) ioloop:run_until_clients() end) copas.addthread(function() local ioloop = mqtt_ioloop.create{ sleep = 0.01, sleep_function = copas.sleep } ioloop:add(pong) ioloop:run_until_clients() end) copas.loop() print("done, copas loop is stopped") ``` -------------------------------- ### client_mt:open_connection Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Opens the network connection to the MQTT broker. This is a low-level method, typically managed internally by `start_connecting`. ```APIDOC ## client_mt:open_connection () ### Description Open network connection to the broker. ``` -------------------------------- ### client_mt:open_connection Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Opens the network connection to the MQTT broker. ```APIDOC ## client_mt:open_connection () ### Description Open network connection to the broker. ### Returns true on success or false and error message on failure ``` -------------------------------- ### Packet Creation and Utility Functions Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Functions for creating MQTT packet headers, checking QoS and Packet IDs, generating the next Packet ID, and combining packet data. ```APIDOC ## make_header (ptype, flags, len) ### Description Creates the bytes of the MQTT fixed packet header. For MQTT v3.1.1: **2.2 Fixed header**, For MQTT v5.0: **2.1.1 Fixed Header**. ### Parameters * `ptype` number - MQTT packet type. * `flags` number - MQTT packet flags. * `len` number - MQTT packet length. ### Returns string - Bytes of the fixed packet header. ``` ```APIDOC ## check_qos (val) ### Description Checks if the given value is a valid PUBLISH message QoS value. ### Parameters * `val` number - QoS value. ### Returns boolean - True for a valid QoS value, otherwise false. ``` ```APIDOC ## check_packet_id (val) ### Description Checks if the given value is a valid Packet Identifier. For MQTT v3.1.1: **2.3.1 Packet Identifier**, For MQTT v5.0: **2.2.1 Packet Identifier**. ### Parameters * `val` number - Packet ID value. ### Returns boolean - True for a valid Packet ID value, otherwise false. ``` ```APIDOC ## next_packet_id ([curr]) ### Description Returns the next Packet Identifier value relative to the given current value. If current is nil, returns 1 as the first possible Packet ID. For MQTT v3.1.1: **2.3.1 Packet Identifier**, For MQTT v5.0: **2.2.1 Packet Identifier**. ### Parameters * `curr` number - current Packet ID value (optional). ### Returns number - Next Packet ID value. ``` ```APIDOC ## packet_id_required (args) ### Description Checks if the Packet Identifier field is required for the given packet. ### Parameters * `args` table - Arguments for creating the packet. ### Returns boolean - True if Packet Identifier is required for the packet. ``` ```APIDOC ## combine (...) ### Description Combines several data parts into one. ### Parameters * `...` combined_packet_mt/string - Any amount of strings of combined_packet_mt tables to combine into one packet. ### Returns table - Combined_packet_mt table suitable to append packet parts or to stringify it into raw packet bytes. ``` ```APIDOC ## packet_tostring (packet) ### Description Renders a packet to its string representation. ### Parameters * `packet` packet_mt table - The packet table to convert to a string. ### Returns string - Human-readable string representation of the packet. ``` -------------------------------- ### client_mt:send_connect Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Sends the CONNECT packet over the opened network connection to establish the MQTT session. ```APIDOC ## client_mt:send_connect () ### Description Send CONNECT packet into opened network connection. ### Returns true on success or false and error message on failure ``` -------------------------------- ### client_mt:subscribe Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Subscribes to one or more topics with specified Quality of Service (QoS) levels. Supports MQTT v5.0 specific flags and properties for advanced configurations. An optional callback can be provided to be notified when the subscription is created. ```APIDOC ## client_mt:subscribe (args) ### Description Subscribes to topics with specified QoS levels. Supports MQTT v5.0 flags and properties. An optional callback can be provided. ### Parameters #### Path Parameters * **args** (table) - Subscription arguments * **topic** (string) - Topic to subscribe * **qos** (number) - QoS level for subscription (default: 0) * **no_local** (boolean) - MQTT v5.0 only: no_local flag * **retain_as_published** (boolean) - MQTT v5.0 only: retain_as_published flag * **retain_handling** (boolean) - MQTT v5.0 only: retain_handling flag * **properties** (table) - MQTT v5.0 only: properties for subscribe operation (optional) * **user_properties** (table) - MQTT v5.0 only: user properties for subscribe operation (optional) * **callback** (function) - Callback function when subscription is created (optional) ### Returns packet id on success or false and error message on failure ``` -------------------------------- ### mqtt table Source: https://xhaskx.github.io/luamqtt/modules/mqtt.html The module table containing protocol version constants and the library version. ```APIDOC ## mqtt ### Description Module table. ### Fields: * v311 number MQTT v3.1.1 protocol version constant * v50 number MQTT v5.0 protocol version constant * _VERSION string luamqtt library version string ### See also: mqtt.const ``` -------------------------------- ### client_mt:on Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Adds functions as handlers for specified MQTT events. This allows the client to react to various occurrences like connection, message reception, etc. ```APIDOC ## client_mt:on (...) ### Description Add functions as handlers of given events. ### Parameters: * ... - (event_name, function) or { event1 = func1, event2 = func2 } table ``` -------------------------------- ### make_string Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Encodes a UTF-8 string into bytes, prefixed with its length as a uint16, adhering to MQTT specifications. ```APIDOC ## make_string (str) ### Description Create bytes of the UTF-8 string value according to the MQTT spec. Basically it's the same string with its length prefixed as uint16 value. For MQTT v3.1.1: **1.5.3 UTF-8 encoded strings** , For MQTT v5.0: **1.5.4 UTF-8 Encoded String**. ### Parameters * **str** (string) - string value to convert to bytes ### Returns string bytes of the value ``` -------------------------------- ### client_mt:publish Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Publishes a message to a specified topic. Supports QoS levels, retain and duplicate flags, and optional payload. MQTT v5.0 properties and an acknowledgment callback are also supported. ```APIDOC ## client_mt:publish (args) ### Description Publishes a message to a broker. ### Parameters #### Path Parameters * **args** (table) - Publish operation arguments * **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 is acknowledged (optional) ### Returns true or packet id on success or false and error message on failure ``` -------------------------------- ### make_uint16_nonzero Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Creates bytes for a 2-byte value, enforcing that the value must be non-zero. ```APIDOC ## make_uint16_nonzero (value) ### Description Make bytes for 2-byte value with nonzero check. ### Parameters * **value** (number) - integer value to convert to bytes ### Returns string bytes of the value ``` -------------------------------- ### make_uint32 Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Creates bytes for a uint32 value, used for larger integer fields within MQTT packets. ```APIDOC ## make_uint32 (val) ### Description Create bytes of the uint32 value. ### Parameters * **val** (number) - integer value to convert to bytes ### Returns string bytes of the value ``` -------------------------------- ### ioloop_mt:run_until_clients Source: https://xhaskx.github.io/luamqtt/modules/mqtt.ioloop.html Continuously runs the ioloop until at least one client is active or has pending operations. ```APIDOC ## ioloop_mt:run_until_clients ### Description Run ioloop until at least one client are in ioloop ``` -------------------------------- ### client_mt:publish Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Publishes a message to a specified MQTT topic on the broker. This is a core function for sending data through MQTT. ```APIDOC ## client_mt:publish (args) ### Description Publish message to broker. ### Parameters: * args (table) - Arguments for publishing. Expected to contain topic and payload information. ``` -------------------------------- ### ioloop_mt:add Source: https://xhaskx.github.io/luamqtt/modules/mqtt.ioloop.html Adds an MQTT client or a loop function to the ioloop instance for event processing. ```APIDOC ## ioloop_mt:add ### Description Add MQTT client or a loop function to the ioloop instance ### Parameters: * client (client_mt or function) - MQTT client or a loop function to add to ioloop ### Returns: * boolean - true on success or false and error message on failure ``` -------------------------------- ### make_uint8_0_or_1 Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Creates bytes for a 1-byte value that must be either 0 or 1, used for specific boolean-like flags in MQTT. ```APIDOC ## make_uint8_0_or_1 (value) ### Description Make bytes for 1-byte value with only 0 or 1 value allowed. ### Parameters * **value** (number) - integer value to convert to bytes ### Returns string bytes of the value ``` -------------------------------- ### make_uint8 Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Creates bytes for a uint8 value. This is a fundamental operation for encoding MQTT messages. ```APIDOC ## make_uint8 (val) ### Description Create bytes of the uint8 value. ### Parameters * **val** (number) - integer value to convert to bytes ### Returns string bytes of the value ``` -------------------------------- ### client_mt:auth Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Sends an AUTH packet to authenticate the client on the broker, specifically for MQTT v5.0. Supports setting a reason code and MQTT v5.0 properties. ```APIDOC ## client_mt:auth ([rc=0[, properties[, user_properties]]]) ### Description Send AUTH packet to authenticate client on broker, in MQTT v5.0 protocol. ### Parameters #### Path 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 ``` -------------------------------- ### make_var_length Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Encodes an integer into a variable-length byte sequence, crucial for fields like Remaining Length in MQTT packets. ```APIDOC ## make_var_length (len) ### Description Create bytes of the integer value encoded as variable length field For MQTT v3.1.1: **2.2.3 Remaining Length** , For MQTT v5.0: **2.1.4 Remaining Length**. ### Parameters * **len** (number) - integer value to be encoded ### Returns string bytes of the value ``` -------------------------------- ### client_mt:auth Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Sends an AUTH packet to authenticate the client on the broker, specifically for MQTT v5.0 protocol. Used for authentication flows that occur after the initial connection. ```APIDOC ## client_mt:auth ([rc=0[, properties[, user_properties]]]) ### Description Send AUTH packet to authenticate client on broker, in MQTT v5.0 protocol. ### Parameters: * rc (number) - Reason code for authentication, defaults to 0. * properties (table) - Optional properties for the AUTH packet. * user_properties (table) - Optional user properties for the AUTH packet. ``` -------------------------------- ### client_mt:unsubscribe Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Unsubscribes from specified topics. An optional callback can be provided to be notified when the subscription is removed from the broker. Supports MQTT v5.0 properties. ```APIDOC ## client_mt:unsubscribe (args) ### Description Unsubscribes from specified topics. An optional callback can be provided to be notified when the subscription is removed. ### Parameters #### Path Parameters * **args** (table) - Unsubscription arguments * **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 when subscription is removed (optional) ### Returns packet id on success or false and error message on failure ``` -------------------------------- ### client_mt:unsubscribe Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Unsubscribes the client from a specified MQTT topic. An optional callback can be provided to be executed once the unsubscription is confirmed by the broker. ```APIDOC ## client_mt:unsubscribe (args) ### Description Unsubscribe from specified topic, and calls optional callback when subscription will be removed on broker. ### Parameters: * args (table) - Arguments for unsubscription. Expected to contain topic information. ``` -------------------------------- ### client_mt:send_connect Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Sends the CONNECT packet into the opened network connection. This is a low-level method, usually called after the network connection is established. ```APIDOC ## client_mt:send_connect () ### Description Send CONNECT packet into opened network connection. ``` -------------------------------- ### make_var_length_nonzero Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Creates bytes for a variable-length encoded value, ensuring the value is non-zero. ```APIDOC ## make_var_length_nonzero (value) ### Description Make bytes for variable length value with nonzero value check. ### Parameters * **value** (number) - integer value to convert to bytes ### Returns string bytes of the value ``` -------------------------------- ### make_uint16 Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Creates bytes for a uint16 value, commonly used for fields like packet identifiers or string lengths. ```APIDOC ## make_uint16 (val) ### Description Create bytes of the uint16 value. ### Parameters * **val** (number) - integer value to convert to bytes ### Returns string bytes of the value ``` -------------------------------- ### client_mt:subscribe Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Subscribes the client to a specified MQTT topic. It returns the SUBSCRIBE packet ID and can optionally call a callback function once the subscription is confirmed by the broker. ```APIDOC ## client_mt:subscribe (args) ### Description Subscribe to specified topic. Returns the SUBSCRIBE packet id and calls optional callback when subscription will be created on broker. ### Parameters: * args (table) - Arguments for subscription. Expected to contain topic information. ``` -------------------------------- ### Packet Parsing Functions Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Functions for initiating packet parsing and parsing specific packet types. ```APIDOC ## start_parse_packet (read_func) ### Description Starts parsing a new packet. ### Parameters * `read_func` function - Function to read data from the network connection. ### Returns 1. number - Packet type. 2. number - Flags. 3. table - Input, a table with fields "read_func" and "available" representing a stream-like object to read already received packet data in chunks. 4. OR false and error_message on failure. ``` ```APIDOC ## parse_packet_connect (read_func[, version]) ### Description Parses a CONNECT packet using the provided read_func. ### Parameters * `read_func` function - Function to read data from the network connection. * `version` number - The MQTT protocol version (optional). ``` -------------------------------- ### ioloop_mt:iteration Source: https://xhaskx.github.io/luamqtt/modules/mqtt.ioloop.html Performs a single iteration of the ioloop, processing network events for connected clients. ```APIDOC ## ioloop_mt:iteration ### Description Perform one ioloop iteration ``` -------------------------------- ### parse_packet_connect_input Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Parses a CONNECT packet from a stream-like input table. It can optionally validate against a specific protocol version. ```APIDOC ## parse_packet_connect_input (input[, version]) ### Description Parse CONNECT packet from already received stream-like packet input table. ### Parameters #### Path Parameters * **input** (table) - a table with fields "read_func" and "available" representing a stream-like object * **version** (number) - expected protocol version constant or nil to accept both versions (_optional_) ### Returns packet on success or false and error message on failure ``` -------------------------------- ### client_mt:send_pingreq Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Sends a PINGREQ packet to the broker to maintain the connection. ```APIDOC ## client_mt:send_pingreq () ### Description Send PINGREQ packet. ### Returns true on success or false and error message on failure ``` -------------------------------- ### client_mt:send_pingreq Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Sends a PINGREQ (ping request) packet to the broker. This is used to keep the connection alive and check if the broker is still responsive. ```APIDOC ## client_mt:send_pingreq () ### Description Send PINGREQ packet. ``` -------------------------------- ### client_mt:close_connection Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Immediately closes the established network connection without sending a graceful DISCONNECT packet. Use this for abrupt connection termination. ```APIDOC ## client_mt:close_connection ([reason]) ### Description Immediately close established network connection, without graceful session finishing with DISCONNECT packet. ### Parameters: * reason (any) - Optional reason for closing the connection. ``` -------------------------------- ### ioloop_mt:remove Source: https://xhaskx.github.io/luamqtt/modules/mqtt.ioloop.html Removes an MQTT client or a loop function from the ioloop instance. ```APIDOC ## ioloop_mt:remove ### Description Remove MQTT client or a loop function from the ioloop instance ### Parameters: * client (client_mt or function) - MQTT client or a loop function to remove from ioloop ### Returns: * boolean - true on success or false and error message on failure ``` -------------------------------- ### client_mt:close_connection Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Immediately closes the established network connection without a graceful session finishing with a DISCONNECT packet. An optional reason string can be provided. ```APIDOC ## client_mt:close_connection ([reason]) ### Description Immediately close established network connection, without graceful session finishing with DISCONNECT packet. ### Parameters #### Path Parameters * **reason** (string) - The reason string of connection close (optional) ### Returns N/A (This method performs an action, return value not specified) ``` -------------------------------- ### client_mt:acknowledge Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Acknowledges a received message, typically a PUBLISH message. Supports setting a reason code and MQTT v5.0 properties for PUBACK/PUBREC packets. ```APIDOC ## client_mt:acknowledge (msg[, rc=0[, properties[, user_properties]]]) ### Description Acknowledge given received message. ### Parameters #### Path Parameters * **msg** (packet_mt) - PUBLISH message to acknowledge * **rc** (number) - Reason code for PUBACK/PUBREC in MQTT v5.0 (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_mt:disconnect Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Sends a DISCONNECT packet to the broker and gracefully closes the network connection. This is the standard way to terminate an MQTT session. ```APIDOC ## client_mt:disconnect ([rc=0[, properties[, user_properties]]]) ### Description Send DISCONNECT packet to the broker and close the connection. ### Parameters: * rc (number) - Reason code for disconnection, defaults to 0. * properties (table) - Optional properties for the disconnect packet. * user_properties (table) - Optional user properties for the disconnect packet. ``` -------------------------------- ### client_mt:disconnect Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Sends a DISCONNECT packet to the broker and gracefully closes the connection. Supports setting a reason code and MQTT v5.0 properties. ```APIDOC ## client_mt:disconnect ([rc=0[, properties[, user_properties]]]) ### Description Send DISCONNECT packet to the broker and close the connection. ### Parameters #### Path Parameters * **rc** (number) - Disconnect Reason Code in MQTT v5.0 (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 ``` -------------------------------- ### Parsing Functions Source: https://xhaskx.github.io/luamqtt/modules/mqtt.protocol.html Functions for parsing various data types from a read function, including strings, integers of different sizes, and variable-length fields. ```APIDOC ## parse_string (read_func) ### Description Reads string (or bytes) using the provided read_func function. ### Parameters * `read_func` function - Function to read some bytes from the network layer. ### Returns 1. string - Parsed string (or bytes) on success. 2. OR false and error message on failure. ``` ```APIDOC ## parse_uint8 (read_func) ### Description Parses a uint8 value using the provided read_func. ### Parameters * `read_func` function - Function to read some bytes from the network layer. ### Returns 1. number - Parsed value. 2. OR false and error message on failure. ``` ```APIDOC ## parse_uint8_0_or_1 (read_func) ### Description Parses a uint8 value using the provided read_func, allowing only 0 or 1. ### Parameters * `read_func` function - Function to read some bytes from the network layer. ### Returns 1. number - Parsed value. 2. OR false and error message on failure. ``` ```APIDOC ## parse_uint16 (read_func) ### Description Parses a uint16 value using the provided read_func. ### Parameters * `read_func` function - Function to read some bytes from the network layer. ### Returns 1. number - Parsed value. 2. OR false and error message on failure. ``` ```APIDOC ## parse_uint16_nonzero (read_func) ### Description Parses a non-zero uint16 value using the provided read_func. ### Parameters * `read_func` function - Function to read some bytes from the network layer. ### Returns 1. number - Parsed value. 2. OR false and error message on failure. ``` ```APIDOC ## parse_uint32 (read_func) ### Description Parses a uint32 value using the provided read_func. ### Parameters * `read_func` function - Function to read some bytes from the network layer. ### Returns 1. number - Parsed value. 2. OR false and error message on failure. ``` ```APIDOC ## parse_var_length (read_func) ### Description Parses a variable-length field value using the provided read_func. For MQTT v3.1.1: **2.2.3 Remaining Length**, For MQTT v5.0: **2.1.4 Remaining Length**. ### Parameters * `read_func` function - Function to read some bytes from the network layer. ### Returns 1. number - Parsed value. 2. OR false and error message on failure. ``` ```APIDOC ## parse_var_length_nonzero (read_func) ### Description Parses a non-zero variable-length field value using the provided read_func. For MQTT v3.1.1: **2.2.3 Remaining Length**, For MQTT v5.0: **2.1.4 Remaining Length**. ### Parameters * `read_func` function - Function to read some bytes from the network layer. ### Returns 1. number - Parsed value. 2. OR false and error message on failure. ``` -------------------------------- ### client_mt:acknowledge Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Acknowledges a received message. This is typically used in scenarios requiring message confirmation, especially with QoS levels higher than 0. ```APIDOC ## client_mt:acknowledge (msg[, rc=0[, properties[, user_properties]]]) ### Description Acknowledge given received message. ### Parameters: * msg (table) - The received message to acknowledge. * rc (number) - Return code, defaults to 0. * properties (table) - Optional properties for the acknowledgment. * user_properties (table) - Optional user properties for the acknowledgment. ``` -------------------------------- ### client_mt:off Source: https://xhaskx.github.io/luamqtt/modules/mqtt.client.html Removes a previously added function handler for a specified event. This is used to stop the client from reacting to certain events. ```APIDOC ## client_mt:off (event, func) ### Description Remove given function handler for specified event. ### Parameters: * event (string) - event name to remove handler * func (function) - handler function to remove ``` -------------------------------- ### ioloop_mt:can_sleep Source: https://xhaskx.github.io/luamqtt/modules/mqtt.ioloop.html Determines if the ioloop can sleep, based on whether any network operations timed out in the current iteration. ```APIDOC ## ioloop_mt:can_sleep ### Description Perform sleep if no one of the network operation in current iteration was not timeouted ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.