Skip to main content

mqttclient.onconnect(callback)

Register a handler for completed connections

Availability

Agent

Parameters

Name Type Description
callback Function Optional function to be called upon completion of a connection attempt

Returns

Nothing

Description

This method allows you to register a function that will be called whenever an attempt to connect to an MQTT broker (see mqttclient.connect()) completes, whether successfully or not.

The provided function must have one parameter of its own: resultCode. This will be passed an integer indicating the state of the connection:

Result Value Description
SUCCESS 0 Connected
FAILURE -1 Socket error
ERROR_DISCONNECTED -3 Disconnected
ERROR_OPERATION_INCOMPLETE -11 Operation incomplete (a partial operation was discarded)

Only one callback function may be registered at any one time. To clear a previously registered callback, either provide a new function, or pass in null.

Example

The following code sets up an MQTT client and connects to the specified MQTT broker. The outcome of the connection attempt is handled by the function registered using mqttclient.onconnect(): it checks the value passed into resultCode and reports accordingly. If the connection is made, the code attempts to subscribe to a 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 error(code) {
    local e = errors[code * -1];
    if (e.len() == 0) return "Unknown";
    return e;
}

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", 
                         AT_MOST_ONCE, 
                         function(resultCode, mode) {
                             // This is the subscription acknowledgement callback
                             if (resultCode == 0 && mode < 0x80) {
                                 client.onmessage(onMessage);
                             } else {
                                 server.log("Not subscribed to \'imp.mqtt.test.pings\'.");
                             }
                         });
    } else {
        server.error("Failed to connect to " + s + ". Error: " + errors[resultCode]);
    }
}

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

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

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