MQTTClient.publish()

Overview

Publishes a message to a connected MQTT broker.

Added in version 2.1.13

Format

var mqttClient = new MQTTClient(options);

//...

mqttClient.publish(message, onComplete, onError);

Value Description Type Required Notes
message The message object to publish. Object Required See Message object properties below.
onComplete A callback function that is called asynchronously if the publish completes. Function Optional When called, the first parameter is a Complete object as described below.
onError A callback function that is called asynchronously if the publish errors. Function Optional When called, the first parameter is an Error object as described below.

Message object properties

Value Description Type Required Notes
topic The topic for the message. String Required  
payload A string or ArrayBuffer containing the payload for the message. String or ArrayBuffer Required  
qos The quality of service for the message. Integer Optional

Possible values:

0 – at most once, where messages are delivered according to the best efforts of the operating environment. Message loss can occur.

1 – at least once, where messages are assured to arrive but duplicates can occur.

2 – exactly once, where messages are assured to arrive exactly once.

retain A flag indicating if this message is a retained message Boolean    

Complete object properties

Value Description Type

Notes

result A result code. Integer

Possible values:

•0 – Success

•16 – No matching subscribers

•128 – Unspecified error

•131 – Implementation specific error

•135 – Not authorized

•144 – Topic name invalid

•145 – Packet identifier in use

•151 – Quota exceeded

•153 – Payload format invalid

Error object properties

Value Description Type

Notes

message A message that describes the failure. String May be undefined.
type A category for the type of failure. String  

Example

Copy
/* Connect, send a message with QoS 1 (at least once), and disconnect
 */

mqttClient = new MQTTClient({
    broker: "mqtt://mymqtt.example.com"
});

mqttClient.connect(function() {
    if(mqttClient.connected) {
        mqttClient.publish({
            topic: "this/is/a/test",
            payload: "tada: " + Date(),
            qos: 1
        }, function(complete) {
            Logger.info("publish complete with code: " + complete.result);
            mqttClient.disconnect();
        }, function(error) {
            Logger.info("error on publish: " + (error.reason || "unknown"));
            mqttClient.disconnect();
        });
    }
});