MQTT.js is a client library for the MQTT protocol, written in JavaScript. And this is a fork of original MQTT.js for Ruff that currently supports only TCP connection.
rap install mqttFor the sake of simplicity, let's put the subscriber and the publisher in the same file:
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://test.mosquitto.org');
client.on('connect', function () {
client.subscribe('presence');
client.publish('presence', 'Hello Ruff!');
});
client.on('message', function (topic, message) {
// message is Buffer
console.log('topic:', topic);
console.log('message:', message.toString());
client.end();
});topic: presense
message: Hello Ruff!
mqtt.connect()mqtt.Client()mqtt.Client#publish()mqtt.Client#subscribe()mqtt.Client#unsubscribe()mqtt.Client#end()mqtt.Client#handleMessage()mqtt.Store()mqtt.Store#put()mqtt.Store#del()mqtt.Store#createStream()mqtt.Store#close()
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.
For all MQTT-related options, see the Client constructor.
The Client class wraps a client connection to an
MQTT broker over an arbitrary transport method (TCP only in this fork).
Client automatically handles the following:
- Regular server pings
- QoS flow
- Automatic reconnections
- Start publishing before being connected
The arguments are:
streamBuilderis a function that returns a subclass of theStreamclass that supports theconnectevent. Typically anet.Socket.optionsis the client connection options (see: the connect packet). Defaults:keepalive:10seconds, set to0to disablereschedulePings: reschedule ping messages after sending packets (defaulttrue)clientId:'mqttjs_' + Math.random().toString(16).substr(2, 8)protocolId:'MQTT'protocolVersion:4clean:true, set to false to receive QoS 1 and 2 messages while offlinereconnectPeriod:1000milliseconds, interval between two reconnectionsconnectTimeout:30 * 1000milliseconds, time to wait before a CONNACK is receivedusername: the username required by your broker, if anypassword: the password required by your broker, if anyincomingStore: a Store for the incoming packetsoutgoingStore: a Store for the outgoing packetsqueueQoSZero: if connection is broken, queue outgoing QoS zero messages (defaulttrue)will: a message that will sent by the broker automatically when the client disconnect badly. The format is:topic: the topic to publishpayload: the message to publishqos: the QoSretain: the retain flag
If you are connecting to a broker that supports only MQTT 3.1 (not 3.1.1 compliant), you should pass these additional options:
{
protocolId: 'MQIsdp',
protocolVersion: 3
}This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto version 1.3 and 1.4 works fine without those.
function(connack) {}
Emitted on successful (re)connection (i.e. connack rc=0).
connackreceived connack packet. Whencleanconnection option isfalseand server has a previous session forclientIdconnection option, thenconnack.sessionPresentflag istrue. When that is the case, you may rely on stored session and prefer not to send subscribe commands for the client.
function() {}
Emitted when a reconnect starts.
function() {}
Emitted after a disconnection.
function() {}
Emitted when the client goes offline.
function(error) {}
Emitted when the client cannot connect (i.e. connack rc != 0) or when a parsing error occurs.
function(topic, message, packet) {}
Emitted when the client receives a publish packet
topictopic of the received packetmessagepayload of the received packetpacketreceived packet, as defined in mqtt-packet
Publish a message to a topic
topicis the topic to publish to,Stringmessageis the message to publish,BufferorStringoptionsis the options to publish with, including:qosQoS level,Number, default0retainretain flag,Boolean, defaultfalse
callbackcallback fired when the QoS handling completes, or at the next tick if QoS 0.
Subscribe to a topic or topics
topicis aStringtopic to subscribe to or anArrayof topics to subscribe to. It can also be an object, it has as object keys the topic name and as value the QoS, like{'test1': 0, 'test2': 1}.optionsis the options to subscribe with, including:qosqos subscription level, default 0
callback-function(err, granted)callback fired on suback where:erra subscription errorgrantedis an array of{topic, qos}where:topicis a subscribed to topicqosis the granted qos level on it
Unsubscribe from a topic or topics
topicis aStringtopic or an array of topics to unsubscribe fromcallbackfired on unsuback
Close the client, accepts the following options:
force: passing it to true will close the client right away, without waiting for the in-flight messages to be acked. This parameter is optional.cb: will be called when the client is closed. This parameter is optional.
Handle messages with backpressure support, one at a time.
Override at will, but always call callback, or the client
will hang.
In-memory implementation of the message store.
Another implementaion is mqtt-level-store which uses Level-browserify to store the inflight data, making it usable both in Node and the Browser.
Adds a packet to the store, a packet is
anything that has a messageId property.
The callback is called when the packet has been stored.
Creates a stream with all the packets in the store.
Removes a packet from the store, a packet is
anything that has a messageId property.
The callback is called when the packet has been removed.
Closes the Store.
This fork is only possible due to the excellent work of the original contributors:
| Adam Rudd | GitHub/adamvr | Twitter/@adam_vr |
|---|---|---|
| Matteo Collina | GitHub/mcollina | Twitter/@matteocollina |
| Maxime Agor | GitHub/4rzael | Twitter/@4rzael |
MIT
