Skip to main content

mqttclient.subscribe(topic, qos, callback)

Subscribe to a specific MQTT topic

Availability

Agent

Parameters

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

Returns

Integer — 0, or an error code

Description

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 takes two parameters the second of which, qos, is an integer set to the actual delivery mode — or 128 (0x80) if the subscription request was rejected by the broker.

The callback’s first parameter, resultCode, is also an integer:

Result Code Value Description
SUCCESS 0 OK
FAILURE -1 Socket error
ERROR_DISCONNECTED -3 Disconnected
ERROR_NO_MORE_MSGIDS -10 Exhausted MQTT message IDs, ie. 65535
ERROR_OPERATION_INCOMPLETE -11 Operation incomplete (a partial operation was discarded)

Example

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.

// CONSTANTS
const URL = "tcp://test.mosquitto.org";
const PORT = 1883
const UN = "generalgrugger";
const PW = "gaztakh1ghc0mmand";

// GLOBALS
local client = null;
local cid = "imp.mqtt.test." + imp.configparams.deviceid;
local errors = ["", "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"];

// FUNCTIONS
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
        client.subscribe("imp.mqtt.test.pings", 
                         mqtt.AT_MOST_ONCE, 
                         function(resultCode, mode) {
                             // This is the subscription acknowledgement callback
                             if (resultCode == 0 && mode < 0x80) {
                                 // We are subscribed, so inform the user...
                                 server.log("Subscribed to \'imp.mqtt.test.pings\' with delivery mode: " + mode);

                                 // ...and set the message handler
                                 client.onmessage(onMessage);
                             } else {
                                 // We couldn't subscribe for some reason so inform the user
                                 server.log("Not subscribed to \'imp.mqtt.test.pings\'.");
                                 if (mode == 0x80) server.log("Request rejected by the broker");
                             }
                         });

    } else {
        server.error("Failed to connect to " + s + " Error: " + errors[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");
}

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

// Set up the initial handlers
client.onconnect(onConnect);
client.onconnectionlost(onLost);

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