Skip to main content

mqttclient.onconnectionlost(callback)

Register a handler for broken connections

Availability

Agent

Returns

Nothing

Parameters

Name Type Description
callback Function Optional function to be called upon the loss of a connection

Description

This document describes pre-release alpha functionality which is not yet available to developers.
Both the documentation and the functionality it details are preliminary and subject to change.

This method allows you to register a function that will be called whenever an open connection fails for any reason.

The provided function must have no parameters of its own.

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. It uses mqttclient.onconnectionlost() to warn the user if the connection is unexpectedly broken.

// CONSTANTS
const url = "tcp://test.mosquitto.org";
const port = 1883
const cid = "imp.mqtt.test." + imp.configparams.deviceid;
const un = "generalgrugger";
const pw = "gaztakh1ghc0mmand";

// GLOBALS
local client = null;
local errors = [ "Connected", "Bad protocol version", "Bad client ID",
                 "Server unavailable", "Bad username/password", "Not authorised" ];

// 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", 
                     AT_MOST_ONCE, 
                     function(resultCode, mode) {
                       // This is the subscription acknowledgement callback
                       if (resultCode == 0 && mode < 0x80) {
                          client.onmessage(onMessage);
                       }
                     },
                     false);

  }
}

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