Skip to main content

mqttclient.onmessage(callback)

Register a handler for incoming messages

Availability

Agent

Parameters

Name Type Description
callback Function Function to be called upon receipt of a message

Returns

Nothing

Description

This method allows you to register a function that will be called whenever a message is received from a topic to which the mqttclient has subscribed. The mqttclient will not receive messages posted to topics to which it has not subscribed.

The provided function must have one parameter of its own: item. This will be passed a tables containing two keys:

Key Type Description
topic String The name of the topic to which the message was posted
message Blob The message body

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. A successful connection triggers a subscription attempt; if this too is successful, a message handler is registered using mqttclient.onmessage(). The message handler simply logs the incoming message body and its topic.

// 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) {
    // 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) {
                         // We are subscribed, so set the message handler
                         client.onmessage(onMessage);
                       }
                     },
                     false);
  }
}

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

// Set up the connection handler
client.onconnect(onConnect);

// Connect with credentials
local options = {};
options.username <- un;
options.password <- pw;
client.connect(url + ":" + port.tostring(), cid, options);