Skip to main content

mqtt.createclient()

Create a client for MQTT communication

Availability

Agent

Returns

An mqttclient instance

Description

This method creates a new mqttclient object, which it returns. You can create as many mqttclient objects as you like, memory permitting. However, you can only connect to one of these objects at a time (using mqttclient.connect()). Attempting to connect to a second mqttclient object will throw an excception when mqttclient.connect() is called on it.

If the returned mqttclient object reference goes out of scope, or is set to null, the connection will implicitly be closed.

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; 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 cid = "imp.mqtt.test." + imp.configparams.deviceid;
local client = null;

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

                                 // ...and set the message handler
                                 client.onmessage(onMessage);
                             }
                        });
    } else {
        server.error("Failed to connect to " + s + " Error: " + error(resultCode));
    }
}

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

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