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.

We recommend that you wrap all mqttmessage.sendasync() calls in a try... catch statement. Even if the client is connected at the time of the call, the socket could nonetheless fail as a result of the send process itself.

Note Inbound and Outbound MQTT requests and messages are subject to rate limits.

Example Code

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

// 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});

// 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("Error code " + result);