Skip to main content


Publish a message asynchronously




Name Type Description
callback Function Optional function to be called when the message has been sent




This method attempts to publish an mqttmessage previously created using mqttclient.createmessage(). It does so asynchronously, so the call will not block.

Whether the call publication attempt succeeds or fails can be determined by providing a callback function. This function has a single parameter of its own: resultCode. This takes an integer which will be zero if the message was sent successfully, otherwise an error code (see below). If such a callback is registered, it will be triggered when the message is considered to have been delivered according to the message’s delivery mode (see mqttclient.createmessage()).

Result Code Description
0 Success
-1 Socket error
-3 Client disconnected
-10 Exhausted the available MQTT message IDs (maximum is 65535)
-11 Operation did not complete (a partial operation will be discarded)
-12 The maximum number of buffered messages was exceeded

If you call mqttmessage.sendasync() on a message that was created with an mqttclient instance which is not currently connected, an exception will be thrown. Make sure you call mqttclient.connect() before sending messages.

API Change Log

  • 2018-07-27 — remove sendsync() method. Only sendasync() now supported.


The following code generates a message (using an mqttclient instance, client) and sends it to the broker referenced when client was created.

local errors = ["Success", "Socket Error", "Persistence Error", "Disconnected", 
                "Max. Messages in Flight", "Bad UTF-8 String", "Null Parameter", 
                "Topic Name Truncated", "Bad Structure", "Bad QoS", "No more message IDs", 
                "Operation incomplete", "Max buffered messages exceeded"];

// Create a message (topic, message, options) using the mqttclient instance
local message = client.createmessage("imp.mqtt.test.pings",
                                     "This is a test message",
                                     {"qos": mqtt.AT_LEAST_ONCE});
if (message != null) {
    // Send the new message
    server.log("Posting the message");
    message.sendasync(function(result) {
        // Log the result
        server.log("The message was " + (result != 0 ? "not " : "") + "published");
        if (result != 0) server.error(errors(result));
} else {
    server.error("Could not create message");