Skip to main content

mqttclient.subscribe(topic, qos, callback)

Subscribe to a specific MQTT topic




Name Type Description
topic String or blob Topic to be subscribed to. Must be valid UTF-8
qos Integer Optional delivery mode constant
callback Function Optional function to be called with MQTT broker’s acknowledgement


Integer — 0, or an error code


This method allows you to subscribe to the specified topic.

You can request a delivery mode by passing one of the following integer constants into the qos parameter:

Constant Value Description
mqtt.AT_MOST_ONCE 0 Only provide the message once or not at all. This is the default value
mqtt.AT_LEAST_ONCE 1 The message may be delivered more than once
mqtt.EXACTLY_ONCE 2 Provide the message once

You should note that this is simply a request made to the broker — which may apply a different delivery mode. To discover the actual delivery mode, provide a callback function: this has two parameters, the second of which, qosMode, receives an integer indicating the actual delivery mode — or 128 (0x80) if the subscription request was rejected by the broker:

Value State Actual QoS
0x00 Success mqtt.AT_MOST_ONCE
0x01 Success mqtt.AT_LEAST_ONCE
0x02 Success mqtt.EXACTLY_ONCE
0x80 Failure N/A

The callback’s first parameter, resultCode, receives 0 on a successful subscription. Any other value indicates failure.

An exception will be thrown if you call subscribe() on an mqttclient instance that is currently disconnected.


The following code sets up an MQTT client and connects to the specified MQTT broker. If the connection is made, the code attempts to subscribe to a topic using mqttclient.subscribe(). If this succeeds in turn, the code registers the handler that will log any incoming messages that have been posted to the chosen topic.

const URL  = "tcp://";
const PORT = 1883
const UN   = "generalgrugger";
const PW   = "gaztakh1ghc0mmand";

local client = null;
local cid = "imp.mqtt.test." + imp.configparams.deviceid;

function error(code) {
    switch (code) {
        case -1: return "Socket Error";
        case 1:  return "Unsupported MQTT version";
        case 2:  return "Client ID rejected";
        case 3:  return "Server unavailable";
        case 4:  return "Invalid username/password";
        case 5:  return "Not authorized";
        default: return "Unknown error";

function onMessage(message) {
    // Called on receipt of a message
    server.log("Message \'" + message.message + "\' received under topic \'" + message.topic + "\'");

function onConnect(resultCode) {
    // Called when the client connects (or fails to connect) to the MQTT broker
    local s = URL + ":" + PORT.tostring();
    if (resultCode == 0) {
        server.log("Connected to " + s);

        // We're connected to try to subscribe to a topic
                         function(result, qosMode) {
                             // This is the subscription acknowledgement callback
                             if (result == 0 && qosMode < 0x80) {
                                 // We are subscribed, so inform the user...
                                 server.log("Subscribed to \'imp.mqtt.test.pings\' with delivery mode: " + result);

                                 // ...and set the message handler
                             } else {
                                 // We couldn't subscribe for some reason so inform the user
                                 server.log("Not subscribed to \'imp.mqtt.test.pings\'.");

    } else {
        server.error("Failed to connect to " + s + " Error: " + error(resultCode));

function onLost() {
    // Called when the connection to the MQTT broker is unexpectedly lost
    local s = URL + ":" + PORT.tostring();
    server.log("Connected to " + s + " broken");

// Instance an MQTT client
client = mqtt.createclient();

// Set up the initial handlers

// Connect with credentials
local options = {};
options.username <- UN;
options.password <- PW;
client.connect(URL + ":" + PORT.tostring(), cid, options);