MQTT.js - MQTT Client Library Encyclopedia

Written by Matteo Collina

Category: MQTT MQTT Client Library

Published: October 12, 2015


Short info

MQTT.js
Language Javascript
License MIT
Website https://github.com/mqttjs/MQTT.js
API Style Asynchronous, Callbacks, Streams, Offline

Description

The MQTT.js provides a full-featured Javascript library for the MQTT protocol. It is fully isomorphic, which means it can run in the browser and in node.js (>= 0.8), including Intel Edison and Raspberry PIs. In fact, it is bundled in base image of the Intel Edison.

The library was originally written by Adam Rudd in May 2011, and it has been upgraded to all versions of node.js since then. In 2014, Matteo Collina took over as a maintainer, and since version 1.0.0 it supports MQTT over Websockets, both in Node.js and in the Browser.

This library is production ready and used by some fortune 500 companies. It can support long running clients with spotty connectivity. It has an optional on-disk storage for local offline messaging. MQTT.js became Open Open Source last January, and it had 55 contributors in its history. There is a team of 4 that maintains the library.

Features

Feature
MQTT 3.1 ok
MQTT 3.1.1 ok
LWT ok
SSL/TLS ok
Automatic Reconnect ok
Feature
QoS 0 ok
QoS 1 ok
QoS 2 ok
Authentication ok
Throttling limited


Usage

Installation

You need node.js installed to use MQTT.js, then:

npm install mqtt

If you want to use the embedded CLI tools, you need to

npm install mqtt -g

Connect

mqtt.connect([url], options)

Connects to the broker specified by the given url and options and returns a Client.

The URL can be on the following protocols: ‘mqtt’, ‘mqtts’, ‘tcp’, ‘tls’, ‘ws’, ‘wss’. The URL can also be an object as returned by URL.parse(), in that case the two objects are merged, i.e. you can pass a single object with both the URL and the connect options.

You can also specify a servers options with content: [{ host: 'localhost', port: 1883 }, ... ], in that case that array is iterated at every connect.

1
2
3
var mqtt    = require('mqtt');
var client  = mqtt.connect('mqtt://broker.mqttdashboard.com');

Connect with MQTT 3.1 or MQTT 3.1.1

The library connects with MQTT 3.1.1 by default. To connect with MQTT 3.1

1
2
3
4
5
6
var mqtt    = require('mqtt');
var client  = mqtt.connect('mqtt://broker.mqttdashboard.com',{
  protocolId: 'MQIsdp',
  protocolVersion: 3
});

Connect with LWT

LWT can be set in the connect function, like the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var mqtt    = require('mqtt');
var client  = mqtt.connect('mqtt://broker.mqttdashboard.com',{
  will: {
    topic: 'dead',
    payload; 'mypayload',
    qos: 1,
    retain: true
  }
});

Connect with Username / Password

Username and password can be set in the connect function, like the following:

1
2
3
4
5
6
var mqtt    = require('mqtt');
var client  = mqtt.connect('mqtt://broker.mqttdashboard.com',{
  username: 'myuser',
  password: 'mypassword'
});

Publish

1
2
  mqtt.Client#publish(topic, message, [options], [callback])

Publish a message to a topic

  • topic is the topic to publish to, String
  • message is the message to publish, Buffer or String
  • options are the options to publish with, including:
    • qos QoS level, Number, default 0
    • retain retain flag, Boolean, default false
  • callback callback fired when the QoS handling completes, or at the next tick if QoS 0.

Subscribe

1
2
mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback])

Subscribe to a topic or topics

  • topic is a String topic to subscribe to or an Array of topics to subscribe to. It can also be an object, the object key is the topic name and the value is the QoS, like {'test1': 0, 'test2': 1}.
  • options is the options to subscribe with, including:
    • qos qos subscription level, default 0
  • callback - function(err, granted) callback fired on suback where:
    • err is a subscription error
    • granted is an array of {topic, qos} where:
    • topic is a subscribed to topic
    • qos is the granted qos level on it
1
2
3
4
5
6
7
8
client.subscribe(presence');

client.on('message', function (topic, message) {
  // message is Buffer
  console.log(message.toString());
  client.end();
});

Unsubscribe

1
2
mqtt.Client#unsubscribe(topic/topic array, [options], [callback])

Unsubscribe from a topic or topics

topic is a String topic or an array of topics to unsubscribe from callback fired on unsuback

Disconnect

Using SSL / TLS

The user should call mqtt.connect(), here is a full example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var mqtt = require('mqtt');
var fs = require('fs');
var KEY = __dirname + '/tls-key.pem';
var CERT = __dirname + '/tls-cert.pem';
var TRUSTED_CA_LIST = [__dirname + '/crt.ca.cg.pem'];

var PORT = 1883;
var HOST = 'stark';

var options = {
  port: PORT,
  host: HOST,
  keyPath: KEY,
  certPath: CERT,
  rejectUnauthorized : true, 
  //The CA list will be used to determine if server is authorized
  ca: TRUSTED_CA_LIST
};

var client = mqtt.connect(options);

client.subscribe('messages');
client.publish('messages', 'Current time is: ' + new Date());
client.on('message', function(topic, message) {
  console.log(message);
});

client.on('connect', function(){
	console.log('Connected');
});

About Matteo Collina

Thanks for this guest blog post

Matteo is a code pirate and mad scientist. He spends most of his days programming in node.js, but in the past he worked with Ruby, Java and Objective-C. He recently got a Ph.D. with a thesis titled “Application Platforms for the Internet of Things”. Now he is a Software Architect at nearForm, where he consults for the top brands in world. Matteo is also the author of the Node.js MQTT Broker, Mosca and of the LevelGraph database. Matteo spoke at several international conferences: NodeSummit, Nodeconf.eu, LXJS, Distill by Engine Yard, and JsDay to name a few. He is also co-author of the book “Javascript: Best Practices” edited by FAG, Milan. In the summer he loves sailing the Sirocco.

Website

<  MQTT.DART - MQTT Client Library Encyclopedia   |   HiveMQ 3.0.1 Released   >