UNPKG

18.7 kBMarkdownView Raw
1mqtt-connection   [![Build Status](https://travis-ci.org/mqttjs/mqtt-connection.png)](https://travis-ci.org/mqttjs/mqtt-connection)
2===============
3
4Barebone Connection object for MQTT.
5Works over any kind of binary Streams, TCP, TLS, WebSocket, ...
6
7[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
8
9It uses [mqtt-packet](http://npm.im/mqtt-packet) for generating and
10parsing MQTT packets. See it for the full documentations on the
11packet types.
12
13 * <a href="#installation">Installation</a>
14 * <a href="#usage">Usage</a>
15 * <a href="#api">API</a>
16 * <a href="#contributing">Contributing</a>
17 * <a href="#license">License &amp; copyright</a>
18
19This library is tested with node v4, v6 and v7. The last version to support
20older versions of node was mqtt-connection@2.1.1.
21
22Installation
23-------
24
25```sh
26npm install mqtt-connection --save
27```
28
29Usage
30-----
31
32As a client:
33
34```js
35var net = require('net')
36var mqttCon = require('mqtt-connection')
37var stream = net.createConnection(1883, 'localhost')
38var conn = mqttCon(stream)
39
40// conn is your MQTT connection!
41```
42
43As a server:
44```js
45var net = require('net')
46var mqttCon = require('mqtt-connection')
47var server = new net.Server()
48
49server.on('connection', function (stream) {
50 var client = mqttCon(stream)
51
52 // client connected
53 client.on('connect', function (packet) {
54 // acknowledge the connect packet
55 client.connack({ returnCode: 0 });
56 })
57
58 // client published
59 client.on('publish', function (packet) {
60 // send a puback with messageId (for QoS > 0)
61 client.puback({ messageId: packet.messageId })
62 })
63
64 // client pinged
65 client.on('pingreq', function () {
66 // send a pingresp
67 client.pingresp()
68 });
69
70 // client subscribed
71 client.on('subscribe', function (packet) {
72 // send a suback with messageId and granted QoS level
73 client.suback({ granted: [packet.qos], messageId: packet.messageId })
74 })
75
76 // timeout idle streams after 5 minutes
77 stream.setTimeout(1000 * 60 * 5)
78
79 // connection error handling
80 client.on('close', function () { client.destroy() })
81 client.on('error', function () { client.destroy() })
82 client.on('disconnect', function () { client.destroy() })
83
84 // stream timeout
85 stream.on('timeout', function () { client.destroy(); })
86})
87
88// listen on port 1883
89server.listen(1883)
90```
91
92As a websocket server:
93
94```js
95var websocket = require('websocket-stream')
96var WebSocketServer = require('ws').Server
97var Connection = require('mqtt-connection')
98var server = http.createServer()
99
100var wss = new WebSocketServer({server: server})
101
102if (handler) {
103 server.on('client', handler)
104}
105
106wss.on('connection', function (ws) {
107 var stream = websocket(ws)
108 var connection = new Connection(stream)
109
110 handle(connection)
111})
112
113function handle (conn) {
114 // handle the MQTT connection like
115 // the net example
116}
117```
118
119API
120---
121
122 * <a href="#connection"><code>mqtt.<b>Connection()</b></code></a>
123 * <a href="#parseStream"><code>mqtt.<b>parseStream()</b></code></a>
124 * <a href="#generateStream"><code>mqtt.<b>generateStream()</b></code></a>
125
126---------------------------------
127
128<a name="connection"></a>
129### new mqtt.Connection([options])
130
131Creates a new MQTT `Connection`.
132
133Options:
134
135 * `notData`: do not listen to the `'data'` event, so that it can
136 respect backpressure. Pipe the `Connection` to another stream to
137 consume the packets. If this option is passed `true` the object will
138 emit no packet-related events.
139
140#### Connection#connect(options, [callback])
141
142Send a MQTT connect packet.
143
144`options` supports the following properties:
145
146* `protocolId`: Protocol ID, usually `MQIsdp`. `string`
147* `protocolVersion`: Protocol version, usually 3. `number`
148* `keepalive`: keepalive period in seconds. `number`
149* `clientId`: client ID. `string`
150* `will`: the client's will message options.
151`object` that supports the following properties:
152 * `topic`: the will topic. `string`
153 * `payload`: the will payload. `string`
154 * `qos`: will qos level. `number`
155 * `retain`: will retain flag. `boolean`
156 * `properties`: properties of will by MQTT 5.0:
157 * `willDelayInterval`: representing the Will Delay Interval in seconds `number`,
158 * `payloadFormatIndicator`: Will Message is UTF-8 Encoded Character Data or not `boolean`,
159 * `messageExpiryInterval`: value is the lifetime of the Will Message in seconds and is sent as the Publication Expiry Interval when the Server publishes the Will Message `number`,
160 * `contentType`: describing the content of the Will Message `string`,
161 * `responseTopic`: String which is used as the Topic Name for a response message `string`,
162 * `correlationData`: The Correlation Data is used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`,
163 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
164* `properties`: properties MQTT 5.0.
165`object` that supports the following properties:
166 * `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
167 * `receiveMaximum`: representing the Receive Maximum value `number`,
168 * `maximumPacketSize`: representing the Maximum Packet Size the Client is willing to accept `number`,
169 * `topicAliasMaximum`: representing the Topic Alias Maximum value indicates the highest value that the Client will accept as a Topic Alias sent by the Server `number`,
170 * `requestResponseInformation`: The Client uses this value to request the Server to return Response Information in the CONNACK `boolean`,
171 * `requestProblemInformation`: The Client uses this value to indicate whether the Reason String or User Properties are sent in the case of failures `boolean`,
172 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
173 * `authenticationMethod`: the name of the authentication method used for extended authentication `string`,
174 * `authenticationData`: Binary Data containing authentication data `binary`
175* `clean`: the 'clean start' flag. `boolean`
176* `username`: username for protocol v3.1. `string`
177* `password`: password for protocol v3.1. `string`
178
179#### Connection#connack(options, [callback])
180Send a MQTT connack packet.
181
182`options` supports the following properties:
183
184* `returnCode`: the return code of the connack, success is for MQTT < 5.0
185* `reasonCode`: suback Reason Code `number` MQTT 5.0
186* `properties`: properties MQTT 5.0.
187`object` that supports the following properties:
188 * `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
189 * `receiveMaximum`: representing the Receive Maximum value `number`,
190 * `maximumQoS`: maximum qos supported by server `number`,
191 * `retainAvailable`: declares whether the Server supports retained messages `boolean`,
192 * `maximumPacketSize`: Maximum Packet Size the Server is willing to accept `number`,
193 * `assignedClientIdentifier`: Assigned Client Identifier `string`,
194 * `topicAliasMaximum`: representing the Topic Alias Maximum value indicates the highest value that the Client will accept as a Topic Alias sent by the Server `number`,
195 * `reasonString`: representing the reason associated with this response `string`,
196 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
197 * `wildcardSubscriptionAvailable`: this byte declares whether the Server supports Wildcard Subscriptions `boolean`
198 * `subscriptionIdentifiersAvailable`: declares whether the Server supports Subscription Identifiers `boolean`,
199 * `sharedSubscriptionAvailable`: declares whether the Server supports Shared Subscriptions `boolean`,
200 * `serverKeepAlive`: Keep Alive time assigned by the Server `number`,
201 * `responseInformation`: String which is used as the basis for creating a Response Topic `string`,
202 * `serverReference`: String which can be used by the Client to identify another Server to use `string`,
203 * `authenticationMethod`: the name of the authentication method used for extended authentication `string`,
204 * `authenticationData`: Binary Data containing authentication data `binary`
205
206#### Connection#publish(options, [callback])
207Send a MQTT publish packet.
208
209`options` supports the following properties:
210
211* `topic`: the topic to publish to. `string`
212* `payload`: the payload to publish, defaults to an empty buffer.
213`string` or `buffer`
214* `qos`: the quality of service level to publish on. `number`
215* `messageId`: the message ID of the packet,
216required if qos > 0. `number`
217* `retain`: retain flag. `boolean`
218* `properties`: `object`
219 * `payloadFormatIndicator`: Payload is UTF-8 Encoded Character Data or not `boolean`,
220 * `messageExpiryInterval`: the lifetime of the Application Message in seconds `number`,
221 * `topicAlias`: value that is used to identify the Topic instead of using the Topic Name `number`,
222 * `responseTopic`: String which is used as the Topic Name for a response message `string`,
223 * `correlationData`: used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`,
224 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
225 * `subscriptionIdentifier`: representing the identifier of the subscription `number`,
226 * `contentType`: String describing the content of the Application Message `string`
227
228#### Connection#puback #pubrec #pubcomp #unsuback(options, [callback])
229Send a MQTT `[puback, pubrec, pubcomp, unsuback]` packet.
230
231`options` supports the following properties:
232
233* `messageId`: the ID of the packet
234* `reasonCode`: Reason Code by packet `number`
235* `properties`: `object`
236 * `reasonString`: representing the reason associated with this response `string`,
237 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
238
239#### Connection#pubrel(options, [callback])
240Send a MQTT pubrel packet.
241
242`options` supports the following properties:
243
244* `dup`: duplicate message flag
245* `reasonCode`: pubrel Reason Code `number`
246* `messageId`: the ID of the packet
247* `properties`: `object`
248 * `reasonString`: representing the reason associated with this response `string`,
249 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
250
251#### Connection#subscribe(options, [callback])
252Send a MQTT subscribe packet.
253
254`options` supports the following properties:
255
256* `dup`: duplicate message flag
257* `messageId`: the ID of the packet
258* `properties`: `object`
259 * `subscriptionIdentifier`: representing the identifier of the subscription `number`,
260 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
261* `subscriptions`: a list of subscriptions of the form
262`[{topic: a, qos: 0}, {topic: b, qos: 1}]`
263`[{topic: a, qos: 0, nl: false, rap: true, rh: 15 }, {topic: b, qos: 1, nl: false, rap: false, rh: 100 }]` MQTT 5.0 Example
264
265#### Connection#suback(options, [callback])
266Send a MQTT suback packet.
267
268`options` supports the following properties:
269
270* `granted`: a vector of granted QoS levels,
271of the form `[0, 1, 2]`
272* `messageId`: the ID of the packet
273* `reasonCode`: suback Reason Code `number`
274* `properties`: `object`
275 * `reasonString`: representing the reason associated with this response `string`,
276 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
277
278#### Connection#unsubscribe(options, [callback])
279Send a MQTT unsubscribe packet.
280
281`options` supports the following properties:
282
283* `messageId`: the ID of the packet
284* `reasonCode`: unsubscribe Reason Code MQTT 5.0 `number`
285* `dup`: duplicate message flag
286* `properties`: `object`
287 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
288* `unsubscriptions`: a list of topics to unsubscribe from,
289of the form `["topic1", "topic2"]`
290
291#### Connection#pingreq #pingresp #disconnect(options, [callback])
292Send a MQTT `[pingreq, pingresp]` packet.
293
294#### Connection#disconnect(options, [callback])
295Send a MQTT `disconnect` packet.
296
297`options` supports the following properties only MQTT 5.0:
298
299* `reasonCode`: Disconnect Reason Code `number`
300* `properties`: `object`
301 * `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
302 * `reasonString`: representing the reason for the disconnect `string`,
303 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
304 * `serverReference`: String which can be used by the Client to identify another Server to use `string`
305
306#### Connection#auth(options, [callback])
307Send a MQTT `auth` packet. Only MQTT 5.0
308
309`options` supports the following properties only MQTT 5.0:
310
311* `reasonCode`: Auth Reason Code `number`
312* `properties`: `object`
313 * `authenticationMethod`: the name of the authentication method used for extended authentication `string`,
314 * `authenticationData`: Binary Data containing authentication data `binary`,
315 * `reasonString`: representing the reason for the disconnect `string`,
316 * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
317
318#### Event: 'connect'
319`function(packet) {}`
320
321Emitted when a MQTT connect packet is received by the client.
322
323`packet` is an object that may have the following properties:
324
325* `version`: the protocol version string
326* `versionNum`: the protocol version number
327* `keepalive`: the client's keepalive period
328* `clientId`: the client's ID
329* `will`: an object with the following keys:
330 * `topic`: the client's will topic
331 * `payload`: the will message
332 * `retain`: will retain flag
333 * `qos`: will qos level
334 * `properties`: properties of will
335* `properties`: properties of packet
336* `clean`: clean start flag
337* `username`: v3.1 username
338* `password`: v3.1 password
339
340#### Event: 'connack'
341`function(packet) {}`
342
343Emitted when a MQTT connack packet is received by the client.
344
345`packet` is an object that may have the following properties:
346
347* `returnCode`: the return code of the connack packet
348* `properties`: properties of packet
349
350#### Event: 'publish'
351`function(packet) {}`
352
353Emitted when a MQTT publish packet is received by the client.
354
355`packet` is an object that may have the following properties:
356
357* `topic`: the topic the message is published on
358* `payload`: the payload of the message
359* `messageId`: the ID of the packet
360* `properties`: properties of packet
361* `qos`: the QoS level to publish at
362
363#### Events: \<'puback', 'pubrec', 'pubrel', 'pubcomp', 'unsuback'\>
364`function(packet) {}`
365
366Emitted when a MQTT `[puback, pubrec, pubrel, pubcomp, unsuback]`
367packet is received by the client.
368
369`packet` is an object that may contain the property:
370
371* `messageId`: the ID of the packet
372* `properties`: properties of packet
373
374#### Event: 'subscribe'
375`function(packet) {}`
376
377Emitted when a MQTT subscribe packet is received.
378
379`packet` is an object that may contain the properties:
380
381* `messageId`: the ID of the packet
382* `properties`: properties of packet
383* `subscriptions`: an array of objects
384representing the subscribed topics, containing the following keys
385 * `topic`: the topic subscribed to
386 * `qos`: the qos level of the subscription
387
388
389#### Event: 'suback'
390`function(packet) {}`
391
392Emitted when a MQTT suback packet is received.
393
394`packet` is an object that may contain the properties:
395
396* `messageId`: the ID of the packet
397* `properties`: properties of packet
398* `granted`: a vector of granted QoS levels
399
400#### Event: 'unsubscribe'
401`function(packet) {}`
402
403Emitted when a MQTT unsubscribe packet is received.
404
405`packet` is an object that may contain the properties:
406
407* `messageId`: the ID of the packet
408* `properties`: properties of packet
409* `unsubscriptions`: a list of topics the client is
410unsubscribing from, of the form `[topic1, topic2, ...]`
411
412#### Events: \<'pingreq', 'pingresp'\>
413`function(packet){}`
414
415Emitted when a MQTT `[pingreq, pingresp, disconnect]` packet is received.
416
417`packet` only includes static header information and can be ignored.
418
419#### Event: 'disconnect'
420`function(packet) {}`
421
422Emitted when a MQTT disconnect packet is received.
423
424`packet` only includes static header information and can be ignored for MQTT < 5.0.
425
426`packet` is an object that may contain the properties for MQTT 5.0:
427
428* `reasonCode`: disconnect Reason Code
429* `properties`: properties of packet
430
431#### Event: 'auth'
432`function(packet) {}`
433
434Emitted when a MQTT auth packet is received.
435
436`packet` is an object that may contain the properties:
437
438* `reasonCode`: Auth Reason Code
439* `properties`: properties of packet
440-------------------------------------
441
442<a name="generateStream">
443
444### mqtt.generateStream()
445
446Returns a `Transform` stream that calls [`generate()`](https://github.com/mqttjs/mqtt-packet#generate).
447The stream is configured into object mode.
448
449<a name="parseStream">
450
451### mqtt.parseStream(opts)
452
453Returns a `Transform` stream that embeds a [`Parser`](https://github.com/mqttjs/mqtt-packet#mqttparser) and calls [`Parser.parse()`](https://github.com/mqttjs/mqtt-packet#parserparsebuffer) for each new `Buffer`. The stream is configured into object mode. It accepts the same options of [`parser(opts)`](#parser).
454
455<a name="contributing"></a>
456Contributing
457------------
458
459mqtt-connection is an **OPEN Open Source Project**. This means that:
460
461> Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
462
463See the [CONTRIBUTING.md](https://github.com/mqttjs/mqtt-connection/blob/master/CONTRIBUTING.md) file for more details.
464
465### Contributors
466
467mqtt-connection is only possible due to the excellent work of the following contributors:
468
469<table><tbody>
470<tr><th align="left">Matteo Collina</th><td><a href="https://github.com/mcollina">GitHub/mcollina</a></td><td><a href="http://twitter.com/matteocollina">Twitter/@matteocollina</a></td></tr>
471<tr><th align="left">Adam Rudd</th><td><a href="https://github.com/adamvr">GitHub/adamvr</a></td><td><a href="http://twitter.com/adam_vr">Twitter/@adam_vr</a></td></tr>
472<tr><th align="left">Siarhei Buntsevich</th><td><a href="https://github.com/scarry1992">GitHub/scarry1992</a></td></tr>
473</tbody></table>
474
475License
476-------
477
478MIT