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 a runtime error 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;
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);