### Install luamqtt from development branch Source: https://github.com/xhaskx/luamqtt/blob/master/README.md Install the luamqtt library from the development branch for the latest features and fixes. ```sh luarocks install luamqtt --dev ``` -------------------------------- ### Install luamqtt from cloned repository Source: https://github.com/xhaskx/luamqtt/blob/master/README.md Install the luamqtt library locally after cloning the repository using 'luarocks make'. ```sh luarocks make ``` -------------------------------- ### Basic MQTT Client Example Source: https://github.com/xhaskx/luamqtt/blob/master/README.md Connect to an MQTT broker, subscribe to a topic, publish a message, and disconnect upon receiving a message. Ensure FLESPI_TOKEN environment variable is set for authentication. ```lua -- load mqtt library local mqtt = require("mqtt") -- create MQTT client, flespi tokens info: https://flespi.com/kb/tokens-access-keys-to-flespi-platform local client = mqtt.client{ uri = "mqtt.flespi.io", username = os.getenv("FLESPI_TOKEN"), clean = true } -- assign MQTT client event handlers client:on{ connect = function(connack) if connack.rc ~= 0 then print("connection to broker failed:", connack:reason_string(), connack) return end -- connection established, now subscribe to test topic and publish a message after assert(client:subscribe{ topic="luamqtt/#", qos=1, callback=function() assert(client:publish{ topic = "luamqtt/simpletest", payload = "hello" }) end}) end, message = function(msg) assert(client:acknowledge(msg)) -- receive one message and disconnect print("received message", msg) client:disconnect() end, } -- run ioloop for client mqtt.run_ioloop(client) ``` -------------------------------- ### Install LuaBitOp for Lua 5.1 Source: https://github.com/xhaskx/luamqtt/blob/master/README.md Install the LuaBitOp library if you are using Lua 5.1, as it's required for bitwise operations. ```sh luarocks install luabitop ``` -------------------------------- ### MQTT v5.0 Client Setup and Interaction Source: https://github.com/xhaskx/luamqtt/blob/master/docs/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 callbacks, subscription callbacks, and message handling. ```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") ``` -------------------------------- ### Install luamqtt Source: https://github.com/xhaskx/luamqtt/blob/master/README.md Install the luamqtt library using LuaRocks. This command installs the latest stable version. ```sh luarocks install luamqtt ``` -------------------------------- ### Install luasocket Source: https://github.com/xhaskx/luamqtt/blob/master/README.md Install the luasocket library, which is a primary dependency for establishing TCP connections. ```sh luarocks install luasocket ``` -------------------------------- ### Example Output: Client 1 Console Log Source: https://github.com/xhaskx/luamqtt/blob/master/examples/last-will/README.md This console output shows the sequence of events for client-1, including connection, subscription, receiving the close command, and initiating the simulated disconnection. ```console $ lua examples/last-will/client-1.lua connected: CONNACK{rc=0, type=2, sp=false} subscribed to luamqtt/close, waiting for connection close command from client-2 received: PUBLISH{qos=1, retain=false, topic="luamqtt/close", payload="Dear client-1, please close your connection", packet_id=1, type=3, dup=false} closing connection without DISCONNECT and stopping client-1 ``` -------------------------------- ### Install luasec for SSL/TLS Source: https://github.com/xhaskx/luamqtt/blob/master/README.md Install the luasec module to enable secure network connections (SSL/TLS) to an MQTT broker. This is optional. ```sh luarocks install luasec ``` -------------------------------- ### Synchronous MQTT Client Example Source: https://github.com/xhaskx/luamqtt/blob/master/docs/examples/sync.lua.html This snippet demonstrates a full synchronous MQTT client workflow. It connects to a broker, subscribes to a topic, publishes a message, and disconnects upon receiving a message. Note that in sync mode, background PINGREQ and automatic reconnects are not available. ```lua local mqtt = require("mqtt") local client = mqtt.client{ uri = "mqtt.flespi.io", 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) assert(client:subscribe{ topic="luamqtt/#", qos=1, callback=function(suback) print("subscribed:", suback) 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 } print("running client in synchronous input/output loop") mqtt.run_sync(client) print("done, synchronous input/output loop is stopped") ``` -------------------------------- ### Example Output: Client 2 Console Log Source: https://github.com/xhaskx/luamqtt/blob/master/examples/last-will/README.md This console output details the execution flow for client-2, demonstrating its connection, subscription to the will topic, publishing the close command, and receiving the Last Will message. ```console $ lua examples/last-will/client-2.lua connected: CONNACK{rc=0, sp=false, type=2} subscribed to luamqtt/lost published close command received: PUBLISH{topic="luamqtt/lost", qos=1, payload="client-1 connection lost last will message", dup=false, packet_id=1, retain=false, type=3} disconnecting and stopping client-2 ``` -------------------------------- ### start_parse_packet Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Starts the process of parsing a new MQTT packet from a network connection. ```APIDOC ## start_parse_packet ### Description Starts the process of parsing a new MQTT packet from a network connection. ### Parameters: #### Path Parameters * read_func (function) - A function to read data from the network connection ### Returns: * number - The packet type * number - The flags * table - An input table with 'read_func' and 'available' fields, representing a stream-like object to read packet data in chunks * OR false and error_message on failure ``` -------------------------------- ### LuaMQTT Copas Example with Ping-Pong Source: https://github.com/xhaskx/luamqtt/blob/master/docs/examples/copas-example.lua.html This snippet demonstrates setting up two LuaMQTT clients, 'ping' and 'pong', to communicate using a Copas I/O loop. The 'ping' client publishes messages, and the 'pong' client subscribes and responds. It requires the 'mqtt' and 'copas' libraries. ```lua 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") ``` -------------------------------- ### start_parse_packet Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Starts the process of parsing a new MQTT packet using a provided read function. ```APIDOC ## start_parse_packet (read_func) ### Description Start parsing a new packet. ### Parameters: * read_func (function) - A function that reads data for parsing. ### Returns: (any) - The result of starting the packet parsing process. ``` -------------------------------- ### Client 1: Last Will and Testament Setup and Disconnection Source: https://github.com/xhaskx/luamqtt/blob/master/examples/last-will/README.md This script connects to an MQTT broker, sets a Last Will message, subscribes to a close command topic, and then simulates an unexpected disconnection. It's designed to trigger the will message upon losing connection without sending a DISCONNECT packet. ```lua local mqtt = require "luamqtt" local client_id = "client-1-" .. os.time() local will_topic = "luamqtt/lost" local will_payload = "client-1 connection lost last will message" local close_topic = "luamqtt/close" local client = mqtt.client(client_id) client:on("connect", function(session) print(string.format("connected: %s", tostring(session))) session:subscribe(close_topic, 1) print(string.format("subscribed to %s, waiting for connection close command from client-2", close_topic)) end) client:on("message", function(session, msg) print(string.format("received: %s", tostring(msg))) if msg.topic == close_topic then print(string.format("closing connection without DISCONNECT and stopping client-1")) session:close() end end) client:connect("localhost", 1883, false, nil, nil, nil, { will_topic = will_topic, will_payload = will_payload, will_qos = 1, will_retain = false }) -- Keep the client running until closed while client:loop() do -- wait for close command end ``` -------------------------------- ### ioloop_mt:get Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.ioloop.html Retrieves the default ioloop instance, with an option to automatically create 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 ``` -------------------------------- ### Collect Code Coverage Stats Source: https://github.com/xhaskx/luamqtt/blob/master/README.md Install luacov and use it with Busted to collect code coverage statistics during test execution. The '-v' flag provides verbose output. ```sh # collect stats during tests busted -v -e 'package.path="./?/init.lua;./?.lua;"..package.path;require("luacov.runner")(".luacov")' tests/spec/*.lua ``` -------------------------------- ### create Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Creates and initializes a new MQTT client instance. ```APIDOC ## create ### Description Creates and initializes a new MQTT client instance. ### Parameters * ... see arguments of client_mt:__init(args) ### Returns: [client_mt] MQTT client instance ### See also: [client_mt:__init] ``` -------------------------------- ### Basic MQTT Client Operations Source: https://github.com/xhaskx/luamqtt/blob/master/docs/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. Ensure you have a working MQTT broker URI and credentials if required. ```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") ``` -------------------------------- ### client_mt:start_connecting Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Initiates the connection process to the MQTT broker. ```APIDOC ## client_mt:start_connecting ### Description Initiates the connection process to the MQTT broker. ### Returns: true on success or false and error message on failure ``` -------------------------------- ### client_mt:start_connecting Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Initiates the connection process to the MQTT broker. This method should be called after the client instance is created and configured. ```APIDOC ## client_mt:start_connecting () ### Description Start connecting to broker ``` -------------------------------- ### create Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Creates, initializes, and returns a new MQTT client instance. This is a factory function for creating clients. ```APIDOC ## create (...) ### Description Create, initialize and return new MQTT client instance ### Parameters #### Path Parameters - **...** (variadic) - Required - Arguments for creating the client instance. ``` -------------------------------- ### client_mt:__init Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Creates and initializes a new MQTT client instance. This is the constructor for the client object. ```APIDOC ## client_mt:__init (args) ### Description Create and initialize MQTT client instance ### Parameters #### Path Parameters - **args** (table) - Required - Arguments for initializing the client. ``` -------------------------------- ### mqtt.client Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.html Creates a new MQTT client instance. The parameters are the same as for mqtt.client.create. ```APIDOC ## mqtt.client ### Description Creates a new MQTT client instance. ### Parameters * ... Same as for mqtt.client.create(...) ### See also: * [mqtt.client.create](../modules/mqtt.client.html#client_mt:__init) ``` -------------------------------- ### MQTT Client Creation Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Creates a new MQTT client instance with specified connection arguments. ```APIDOC ## MQTT Client Creation ### Description Creates a new MQTT client instance with specified connection arguments. ### 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. (_default_ 4) * 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](../modules/mqtt.html#client) MQTT client instance table ``` -------------------------------- ### ioloop_mt:__init Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.ioloop.html Initializes a new ioloop instance with optional arguments for timeout, sleep interval, and a custom sleep function. ```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.run_sync Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.html Runs a synchronous input/output loop for a single MQTT client. The client's connection will be opened, but reconnect and keep_alive features will not work. ```APIDOC ## mqtt.run_sync ### Description Runs a synchronous input/output loop for only one given MQTT client. The client's connection will be opened. Client reconnect feature will not work, and keep_alive too. ### Parameters * cl (mqtt client instance) - The MQTT client instance to run. ### See also: * [mqtt.client.create](../modules/mqtt.client.html#client_mt:__init) ``` -------------------------------- ### mqtt.get_ioloop Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.html Returns the default ioloop instance. ```APIDOC ## mqtt.get_ioloop ### Description Returns the default ioloop instance. ### Method GET ### Endpoint N/A (Function call) ### Returns * Default ioloop instance ``` -------------------------------- ### Run All Tests for All Lua Versions Source: https://github.com/xhaskx/luamqtt/blob/master/README.md Use the provided script to run all tests across different Lua versions, leveraging the hererocks tool. ```sh ./tests/run-for-all-lua-versions.sh ``` -------------------------------- ### make_header Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates bytes for the MQTT fixed packet header. ```APIDOC ## make_header (ptype, flags, len) ### Description Create 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) - The packet type. * flags (number) - The packet flags. * len (number) - The packet length. ### Returns: string - Bytes representing the fixed packet header. ``` -------------------------------- ### mqtt.run_ioloop Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.html Runs the default ioloop for the given MQTT clients or functions. ```APIDOC ## mqtt.run_ioloop ### Description Runs the default ioloop for the given MQTT clients or functions. ### Parameters * ... MQTT clients or loop functions to add to ioloop ### See also: * [mqtt.ioloop.get](../modules/mqtt.ioloop.html#ioloop_mt:get) * [mqtt.ioloop.run_until_clients](../modules/mqtt.ioloop.html#ioloop_mt:run_until_clients) ``` -------------------------------- ### make_header Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Constructs the MQTT fixed header bytes, including packet type, flags, and length. ```APIDOC ## make_header (ptype, flags, len) ### Description Creates the bytes for the MQTT fixed packet header. This includes the packet type, flags, and length, as defined in MQTT v3.1.1 (2.2 Fixed header) and MQTT v5.0 (2.1.1 Fixed Header). ### Parameters: * ptype (number) - The MQTT packet type. * flags (number) - The MQTT packet flags. * len (number) - The MQTT packet length. ### Returns: (string) Bytes of the fixed packet header. ``` -------------------------------- ### Run Tests with Busted Source: https://github.com/xhaskx/luamqtt/blob/master/README.md Execute tests using the Busted test framework. Ensure the package path is correctly set to include local Lua modules. ```sh busted -e 'package.path="./?/init.lua;./?.lua;"..package.path' tests/spec/*.lua ``` -------------------------------- ### client_mt:on Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Adds functions as handlers for specified MQTT events. ```APIDOC ## client_mt:on ### Description Add functions as handlers of given events ### Parameters * ... (event_name, function) or { event1 = func1, event2 = func2 } table ``` -------------------------------- ### client_mt:open_connection Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Opens the network connection to the MQTT broker. ```APIDOC ## client_mt:open_connection ### Description Opens the network connection to the MQTT broker. ### Returns: true on success or false and error message on failure ``` -------------------------------- ### MQTT Client Console Output Source: https://github.com/xhaskx/luamqtt/blob/master/examples/README.md This is the expected console output when running a basic luamqtt script. It shows the sequence of events from client creation to disconnection. ```console created MQTT client mqtt.client{id="luamqtt-v2-0-0-5807dc7"} running ioloop for it connected: CONNACK{rc=0, sp=false, type=2} subscribed: SUBACK{rc={1}, packet_id=1, type=9} publishing test message "hello" to "luamqtt/simpletest" topic... received: PUBLISH{payload="hello", topic="luamqtt/simpletest", dup=false, retain=false, qos=1, packet_id=1, type=3} disconnecting... done, ioloop is stopped ``` -------------------------------- ### Client 2: Triggering Disconnection and Receiving Last Will Source: https://github.com/xhaskx/luamqtt/blob/master/examples/last-will/README.md This script connects to the same MQTT broker, subscribes to a topic to receive confirmation of the client-1 disconnection, and then sends a close command to client-1. It also subscribes to the will topic to receive the Last Will message published by the broker. ```lua local mqtt = require "luamqtt" local client_id = "client-2-" .. os.time() local will_topic = "luamqtt/lost" local close_topic = "luamqtt/close" local client = mqtt.client(client_id) client:on("connect", function(session) print(string.format("connected: %s", tostring(session))) session:subscribe(will_topic, 1) print(string.format("subscribed to %s", will_topic)) print("published close command") session:publish(close_topic, "Dear client-1, please close your connection", 1, false) end) client:on("message", function(session, msg) print(string.format("received: %s", tostring(msg))) if msg.topic == will_topic then print("disconnecting and stopping client-2") session:close() end end) client:connect("localhost", 1883) -- Keep the client running until closed while client:loop() do -- wait for will message end ``` -------------------------------- ### client_mt:send_connect Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Sends the CONNECT packet over the opened network connection to establish the MQTT session. ```APIDOC ## client_mt:send_connect ### Description Sends the CONNECT packet over the opened network connection to establish the MQTT session. ### Returns: true on success or false and error message on failure ``` -------------------------------- ### make_string Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates bytes for a UTF-8 string value according to the MQTT specification. ```APIDOC ## make_string (str) ### Description Create bytes of the UTF-8 string value according to the MQTT spec. ### Parameters: * str (string) - The string to convert to bytes. ### Returns: string - Bytes representing the UTF-8 string. ``` -------------------------------- ### mqtt table Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.html The main MQTT module table, containing protocol versions and the library version. ```APIDOC ## mqtt table ### Description Module table for MQTT constants and version information. ### 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](../modules/mqtt.const.html#) ``` -------------------------------- ### client_mt:send_connect Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Sends the CONNECT packet over the opened network connection to establish the MQTT session with the broker. ```APIDOC ## client_mt:send_connect () ### Description Send CONNECT packet into opened network connection ``` -------------------------------- ### ioloop_mt:run_until_clients Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.ioloop.html Runs the ioloop until at least one client is active within the ioloop. ```APIDOC ## ioloop_mt:run_until_clients ### Description Run ioloop until at least one client are in ioloop ``` -------------------------------- ### client_mt:on Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Adds functions as handlers for specified events. This allows for asynchronous event-driven programming. ```APIDOC ## client_mt:on (...) ### Description Add functions as handlers of given events ### Parameters #### Path Parameters - **...** (variadic) - Required - Event names and corresponding handler functions. ``` -------------------------------- ### ioloop_mt:add Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.ioloop.html Adds an MQTT client or a loop function to the ioloop instance. ```APIDOC ## ioloop_mt:add ### Description Add MQTT client or a loop function to the ioloop instance ### Parameters: * client ([client_mt](../modules/mqtt.html#client) or function) - MQTT client or a loop function to add to ioloop ### Returns: * boolean - true on success or false and error message on failure ``` -------------------------------- ### combine Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Combines several data parts into one packet structure. ```APIDOC ## combine ### Description Combines several data parts into one packet structure. ### Parameters: #### Path Parameters * ... - Any amount of strings or combined_packet_mt tables to combine into one packet ### Returns: * table - A combined_packet_mt table suitable for appending packet parts or stringifying into raw packet bytes ``` -------------------------------- ### client_mt:open_connection Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Opens the underlying network connection to the MQTT broker. This is a lower-level operation. ```APIDOC ## client_mt:open_connection () ### Description Open network connection to the broker ``` -------------------------------- ### make_string Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates MQTT-compatible UTF-8 encoded string bytes, prefixed with a uint16 length. This is used for string fields in MQTT packets as per the protocol specifications. ```APIDOC ## make_string (str) ### Description Creates bytes of the UTF-8 string value according to the MQTT spec. It prefixes the string with its length as a uint16 value. This function is relevant for MQTT v3.1.1 (1.5.3 UTF-8 encoded strings) and MQTT v5.0 (1.5.4 UTF-8 Encoded String). ### Parameters: * str (string) - The string value to convert to bytes. ### Returns: (string) Bytes of the value. ``` -------------------------------- ### combine Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Combines several data parts into one. ```APIDOC ## combine (...) ### Description Combine several data parts into one. ### Parameters: * ... - Variable number of data parts to combine. ### Returns: string - The combined data. ``` -------------------------------- ### Generate Code Coverage Report Source: https://github.com/xhaskx/luamqtt/blob/master/README.md After collecting coverage stats, use the 'luacov' command to generate a report. The report will be output to 'luacov.report.out'. ```sh luacov ``` -------------------------------- ### make_uint16_nonzero Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates bytes for a 2-byte value, ensuring the value is non-zero. ```APIDOC ## make_uint16_nonzero (value) ### Description Make bytes for 2-byte value with nonzero check. ### Parameters: * value (number) - The non-zero 2-byte integer value. ### Returns: string - Bytes representing the non-zero 2-byte value. ``` -------------------------------- ### client_mt:publish Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Publishes a message to the MQTT broker. ```APIDOC ## client_mt:publish ### Description Publish message to broker ### Parameters * args (table) publish arguments ``` -------------------------------- ### make_uint32 Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates bytes representing a 32-bit unsigned integer value. ```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 ``` -------------------------------- ### client_mt:publish Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Publishes a message to a specified topic with optional QoS, retain flag, and properties. A callback can be provided to be notified upon acknowledgment. ```APIDOC ## client_mt:publish ### Description Publishes a message to a specified topic with optional QoS, retain flag, and properties. A callback can be provided to be notified upon acknowledgment. ### Parameters * args (table) - publish operation arguments 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 will be acknowledged (optional) ### Returns: true or packet id on success or false and error message on failure ``` -------------------------------- ### client_mt:subscribe Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Subscribes to a specified topic and optionally calls a callback upon successful subscription. ```APIDOC ## client_mt:subscribe ### Description Subscribe to specified topic. Returns the SUBSCRIBE packet id and calls optional callback when subscription will be created on broker ### Parameters * args (table) subscription arguments * 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 will be created (_optional_) ### Returns: packet id on success or false and error message on failure ``` -------------------------------- ### client_mt:publish Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Publishes a message to a specified topic on the MQTT broker. This method allows sending data to other connected clients. ```APIDOC ## client_mt:publish (args) ### Description Publish message to broker ### Parameters #### Path Parameters - **args** (table) - Required - Arguments for the publish operation, including topic, message, QoS, and retain flag. ``` -------------------------------- ### client_mt:subscribe Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Subscribes the client to one or more MQTT topics. This allows the client to receive messages published to these topics. ```APIDOC ## client_mt:subscribe (args) ### Description Subscribe to specified topic. ### Parameters #### Path Parameters - **args** (table) - Required - Arguments for the subscription, typically including topic and QoS. ``` -------------------------------- ### packet_tostring Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Renders a packet to its string representation. ```APIDOC ## packet_tostring (packet) ### Description Render packet to string representation. ### Parameters: * packet (table) - The packet table to render. ### Returns: string - The string representation of the packet. ``` -------------------------------- ### packet_tostring Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Renders a packet to its string representation. ```APIDOC ## packet_tostring ### Description Renders a packet to its string representation. ### Parameters: #### Path Parameters * packet (packet_mt table) - The packet metatable to convert to a string ### Returns: * string - A human-readable string representation of the packet ``` -------------------------------- ### client_mt:auth Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Sends an AUTH packet to authenticate the client with the broker, specifically for MQTT v5.0 protocol. ```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) - Optional - The return code, defaults to 0. - **properties** (table) - Optional - MQTT v5.0 properties. - **user_properties** (table) - Optional - User-defined properties. ``` -------------------------------- ### make_uint16_nonzero Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates a 2-byte representation for an integer value, ensuring the value is non-zero. ```APIDOC ## make_uint16_nonzero (value) ### Description Makes bytes for a 2-byte value with a non-zero check. ### Parameters: * value (number) - The integer value to convert to bytes. ### Returns: (string) Bytes of the value. ``` -------------------------------- ### client_mt:auth Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Sends an AUTH packet to authenticate the client with the broker, used in MQTT v5.0 protocol. ```APIDOC ## client_mt:auth ### Description Sends an AUTH packet to authenticate the client with the broker, used 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 ``` -------------------------------- ### check_qos Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Validates if a given value is a permissible QoS level for an MQTT PUBLISH message. ```APIDOC ## check_qos (val) ### Description Checks if the given value is a valid PUBLISH message QoS value. ### Parameters: * val (number) - The QoS value to check. ### Returns: (boolean) True if the QoS value is valid, otherwise false. ``` -------------------------------- ### parse_packet_connect_input Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Parses an MQTT CONNECT packet from an already received stream-like input table. ```APIDOC ## parse_packet_connect_input ### Description Parses an MQTT CONNECT packet from an already received stream-like input table. ### Parameters: #### Path Parameters * input (table) - A table with 'read_func' and 'available' fields, representing a stream-like object * version (number) - Optional - Expected protocol version constant or nil to accept both versions ### Returns: * packet - The parsed CONNECT packet on success * OR false and error message on failure ``` -------------------------------- ### make_uint16 Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates bytes representing a 16-bit unsigned integer value. ```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 ``` -------------------------------- ### make_uint8_0_or_1 Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates bytes for a 1-byte value that can only be 0 or 1. ```APIDOC ## make_uint8_0_or_1 (value) ### Description Make bytes for 1-byte value with only 0 or 1 value allowed. ### Parameters: * value (number) - The value (0 or 1) to convert to bytes. ### Returns: string - Bytes representing the 0 or 1 value. ``` -------------------------------- ### make_uint8 Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates bytes representing an 8-bit unsigned integer value. ```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:acknowledge Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Acknowledges a received MQTT message by sending a PUBACK or PUBREC packet to the broker. ```APIDOC ## client_mt:acknowledge ### Description Acknowledges a received MQTT message by sending a PUBACK or PUBREC packet to the broker. ### 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 ``` -------------------------------- ### ioloop_mt:iteration Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.ioloop.html Performs a single iteration of the ioloop. ```APIDOC ## ioloop_mt:iteration ### Description Perform one ioloop iteration ``` -------------------------------- ### check_qos Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Checks if a given value is a valid PUBLISH message QoS value. ```APIDOC ## check_qos (val) ### Description Check if given value is a valid PUBLISH message QoS value. ### Parameters: * val (number) - The value to check. ### Returns: boolean - True if the value is a valid QoS, false otherwise. ``` -------------------------------- ### make_var_length_nonzero Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates bytes for a variable-length 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) - The non-zero value to encode. ### Returns: string - Bytes representing the non-zero variable-length value. ``` -------------------------------- ### make_var_length Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Creates bytes for an integer value encoded as a variable-length field, as defined in MQTT specifications for Remaining Length. ```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) - The integer length to encode. ### Returns: string - Bytes representing the variable-length encoded integer. ``` -------------------------------- ### parse_uint16_nonzero Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Parses a 16-bit unsigned integer from the network layer, ensuring the value is non-zero. ```APIDOC ## parse_uint16_nonzero (read_func) ### Description Parses a non-zero uint16 value using the provided read function from the network layer. ### Parameters: * read_func (function) - A function to read some bytes from the network layer. ### Returns: 1. (number) The parsed value. 2. OR (false, error message) on failure. ``` -------------------------------- ### make_var_length Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Encodes an integer value as a variable-length field, as specified in MQTT protocol for Remaining Length. ```APIDOC ## make_var_length (len) ### Description Creates bytes of the integer value encoded as a variable-length field. This is used for fields like Remaining Length in MQTT v3.1.1 (2.2.3 Remaining Length) and MQTT v5.0 (2.1.4 Remaining Length). ### Parameters: * len (number) - The integer value to be encoded. ### Returns: (string) Bytes of the value. ``` -------------------------------- ### client_mt:unsubscribe Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Unsubscribes the client from a specified topic. An optional callback can be provided to be executed once the unsubscribe 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 #### Path Parameters - **args** (table) - Required - Arguments for the unsubscription, typically including topic and a callback function. ``` -------------------------------- ### parse_packet_connect Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Parses an MQTT CONNECT packet using a provided read function. ```APIDOC ## parse_packet_connect ### Description Parses an MQTT CONNECT packet using a provided read function. ### Parameters: #### Path Parameters * read_func (function) - Function to read data from the network connection * version (number) - Optional - Expected protocol version constant or nil to accept both versions ### Returns: * packet - The parsed CONNECT packet on success * OR false and error message on failure ``` -------------------------------- ### parse_packet_connect_input Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Parses a CONNECT packet from an already received stream-like input table, with optional version specification. ```APIDOC ## parse_packet_connect_input (input, version) ### Description Parse CONNECT packet from already received stream-like packet input table. ### Parameters: * input (table) - A table containing the received packet data. * version (string, optional) - The MQTT protocol version (e.g., '3.1.1', '5.0'). ### Returns: (any) - The parsed CONNECT packet data. ``` -------------------------------- ### client_mt:unsubscribe Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.client.html Unsubscribes from a specified topic and optionally calls a callback upon successful unsubscription. ```APIDOC ## client_mt:unsubscribe ### Description Unsubscribe from specified topic, and calls optional callback when subscription will be removed on broker ### Parameters * args (table) subscription 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 to be called when subscription will be removed on broker (_optional_) ### Returns: packet id on success or false and error message on failure ``` -------------------------------- ### make_uint8_0_or_1 Source: https://github.com/xhaskx/luamqtt/blob/master/docs/modules/mqtt.protocol.html Generates a 1-byte representation for values that are restricted to 0 or 1. ```APIDOC ## make_uint8_0_or_1 (value) ### Description Makes bytes for a 1-byte value where only 0 or 1 are allowed. ### Parameters: * value (number) - The integer value to convert to bytes. ### Returns: (string) Bytes of the value. ```