mqtt 2.18.9 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CONTRIBUTING.md +27 -27
  2. package/LICENSE.md +15 -15
  3. package/README.md +689 -612
  4. package/bin/pub.js +146 -146
  5. package/bin/sub.js +123 -123
  6. package/dist/mqtt.js +11916 -14116
  7. package/dist/mqtt.min.js +1 -1
  8. package/doc/help.txt +8 -8
  9. package/doc/publish.txt +26 -26
  10. package/doc/subscribe.txt +26 -26
  11. package/examples/client/secure-client.js +24 -24
  12. package/examples/client/simple-both.js +13 -13
  13. package/examples/client/simple-publish.js +7 -7
  14. package/examples/client/simple-subscribe.js +9 -9
  15. package/examples/tls client/crt.ca.cg.pem +34 -34
  16. package/examples/tls client/mqttclient.js +48 -48
  17. package/examples/tls client/tls-cert.pem +13 -13
  18. package/examples/tls client/tls-key.pem +15 -15
  19. package/examples/wss/client.js +49 -49
  20. package/examples/wss/client_with_proxy.js +58 -58
  21. package/lib/client.js +1460 -1129
  22. package/lib/connect/ali.js +130 -0
  23. package/lib/connect/index.js +157 -149
  24. package/lib/connect/tcp.js +19 -19
  25. package/lib/connect/tls.js +41 -41
  26. package/lib/connect/ws.js +92 -92
  27. package/lib/connect/wx.js +134 -110
  28. package/lib/store.js +140 -140
  29. package/lib/validations.js +52 -52
  30. package/mqtt.js +41 -41
  31. package/package.json +112 -107
  32. package/test/abstract_client.js +3084 -2667
  33. package/test/abstract_store.js +135 -135
  34. package/test/browser/server.js +132 -132
  35. package/test/browser/test.js +92 -92
  36. package/test/client.js +1129 -544
  37. package/test/helpers/private-csr.pem +16 -16
  38. package/test/helpers/private-key.pem +27 -27
  39. package/test/helpers/public-cert.pem +19 -19
  40. package/test/helpers/public-key.pem +9 -9
  41. package/test/helpers/server.js +52 -52
  42. package/test/helpers/server_process.js +9 -9
  43. package/test/helpers/tls-cert.pem +14 -14
  44. package/test/helpers/tls-csr.pem +11 -11
  45. package/test/helpers/tls-key.pem +15 -15
  46. package/test/helpers/wrong-cert.pem +13 -13
  47. package/test/helpers/wrong-csr.pem +11 -11
  48. package/test/helpers/wrong-key.pem +15 -15
  49. package/test/mocha.opts +4 -4
  50. package/test/mqtt.js +230 -230
  51. package/test/mqtt_store.js +9 -9
  52. package/test/secure_client.js +157 -157
  53. package/test/server.js +93 -65
  54. package/test/store.js +10 -10
  55. package/test/typescript/broker-connect-subscribe-and-publish.js +24 -0
  56. package/test/typescript/broker-connect-subscribe-and-publish.js.map +1 -0
  57. package/test/typescript/broker-connect-subscribe-and-publish.ts +22 -22
  58. package/test/typescript/tsconfig.json +14 -14
  59. package/test/util.js +13 -13
  60. package/test/websocket_client.js +144 -144
  61. package/types/index.d.ts +27 -27
  62. package/types/lib/client-options.d.ts +178 -137
  63. package/types/lib/client.d.ts +231 -196
  64. package/types/lib/connect/index.d.ts +10 -10
  65. package/types/lib/store-options.d.ts +6 -6
  66. package/types/lib/store.d.ts +46 -46
  67. package/test/browser/wx.js +0 -93
package/README.md CHANGED
@@ -1,612 +1,689 @@
1
- ![mqtt.js](https://raw.githubusercontent.com/mqttjs/MQTT.js/137ee0e3940c1f01049a30248c70f24dc6e6f829/MQTT.js.png)
2
- =======
3
-
4
- [![Build Status](https://travis-ci.org/mqttjs/MQTT.js.svg)](https://travis-ci.org/mqttjs/MQTT.js) [![codecov](https://codecov.io/gh/mqttjs/MQTT.js/branch/master/graph/badge.svg)](https://codecov.io/gh/mqttjs/MQTT.js)
5
-
6
- [![NPM](https://nodei.co/npm-dl/mqtt.png)](https://nodei.co/npm/mqtt/) [![NPM](https://nodei.co/npm/mqtt.png)](https://nodei.co/npm/mqtt/)
7
-
8
- [![Sauce Test Status](https://saucelabs.com/browser-matrix/mqttjs.svg)](https://saucelabs.com/u/mqttjs)
9
-
10
- MQTT.js is a client library for the [MQTT](http://mqtt.org/) protocol, written
11
- in JavaScript for node.js and the browser.
12
-
13
- * [Upgrade notes](#notes)
14
- * [Installation](#install)
15
- * [Example](#example)
16
- * [Command Line Tools](#cli)
17
- * [API](#api)
18
- * [Browser](#browser)
19
- * [Weapp](#weapp)
20
- * [About QoS](#qos)
21
- * [TypeScript](#typescript)
22
- * [Contributing](#contributing)
23
- * [License](#license)
24
-
25
- MQTT.js is an OPEN Open Source Project, see the [Contributing](#contributing) section to find out what this means.
26
-
27
- [![JavaScript Style
28
- Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
29
-
30
-
31
- <a name="notes"></a>
32
- ## Important notes for existing users
33
-
34
- v2.0.0 removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending
35
- packets. It also removes all the deprecated functionality in v1.0.0,
36
- mainly `mqtt.createConnection` and `mqtt.Server`. From v2.0.0,
37
- subscriptions are restored upon reconnection if `clean: true`.
38
- v1.x.x is now in *LTS*, and it will keep being supported as long as
39
- there are v0.8, v0.10 and v0.12 users.
40
-
41
- v1.0.0 improves the overall architecture of the project, which is now
42
- split into three components: MQTT.js keeps the Client,
43
- [mqtt-connection](http://npm.im/mqtt-connection) includes the barebone
44
- Connection code for server-side usage, and [mqtt-packet](http://npm.im/mqtt-packet)
45
- includes the protocol parser and generator. The new Client improves
46
- performance by a 30% factor, embeds Websocket support
47
- ([MOWS](http://npm.im/mows) is now deprecated), and it has a better
48
- support for QoS 1 and 2. The previous API is still supported but
49
- deprecated, as such, it is not documented in this README.
50
-
51
- As a __breaking change__, the `encoding` option in the old client is
52
- removed, and now everything is UTF-8 with the exception of the
53
- `password` in the CONNECT message and `payload` in the PUBLISH message,
54
- which are `Buffer`.
55
-
56
- Another __breaking change__ is that MQTT.js now defaults to MQTT v3.1.1,
57
- so to support old brokers, please read the [client options doc](#client).
58
-
59
- <a name="install"></a>
60
- ## Installation
61
-
62
- ```sh
63
- npm install mqtt --save
64
- ```
65
-
66
- <a name="example"></a>
67
- ## Example
68
-
69
- For the sake of simplicity, let's put the subscriber and the publisher in the same file:
70
-
71
- ```js
72
- var mqtt = require('mqtt')
73
- var client = mqtt.connect('mqtt://test.mosquitto.org')
74
-
75
- client.on('connect', function () {
76
- client.subscribe('presence', function (err) {
77
- if (!err) {
78
- client.publish('presence', 'Hello mqtt')
79
- }
80
- })
81
- })
82
-
83
- client.on('message', function (topic, message) {
84
- // message is Buffer
85
- console.log(message.toString())
86
- client.end()
87
- })
88
- ```
89
-
90
- output:
91
- ```
92
- Hello mqtt
93
- ```
94
-
95
- If you want to run your own MQTT broker, you can use
96
- [Mosquitto](http://mosquitto.org) or
97
- [Mosca](http://mcollina.github.io/mosca/), and launch it.
98
- You can also use a test instance: test.mosquitto.org and test.mosca.io
99
- are both public.
100
-
101
- If you do not want to install a separate broker, you can try using the
102
- [mqtt-connection](https://www.npmjs.com/package/mqtt-connection).
103
-
104
- to use MQTT.js in the browser see the [browserify](#browserify) section
105
-
106
- <a name="promises"></a>
107
- ## Promise support
108
-
109
- If you want to use the new [async-await](https://blog.risingstack.com/async-await-node-js-7-nightly/) functionality in JavaScript, or just prefer using Promises instead of callbacks, [async-mqtt](https://github.com/mqttjs/async-mqtt) is a wrapper over MQTT.js which uses promises instead of callbacks when possible.
110
-
111
- <a name="cli"></a>
112
- ## Command Line Tools
113
-
114
- MQTT.js bundles a command to interact with a broker.
115
- In order to have it available on your path, you should install MQTT.js
116
- globally:
117
-
118
- ```sh
119
- npm install mqtt -g
120
- ```
121
-
122
- Then, on one terminal
123
-
124
- ```
125
- mqtt sub -t 'hello' -h 'test.mosquitto.org' -v
126
- ```
127
-
128
- On another
129
-
130
- ```
131
- mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'
132
- ```
133
-
134
- See `mqtt help <command>` for the command help.
135
-
136
- <a name="api"></a>
137
- ## API
138
-
139
- * <a href="#connect"><code>mqtt.<b>connect()</b></code></a>
140
- * <a href="#client"><code>mqtt.<b>Client()</b></code></a>
141
- * <a href="#publish"><code>mqtt.Client#<b>publish()</b></code></a>
142
- * <a href="#subscribe"><code>mqtt.Client#<b>subscribe()</b></code></a>
143
- * <a href="#unsubscribe"><code>mqtt.Client#<b>unsubscribe()</b></code></a>
144
- * <a href="#end"><code>mqtt.Client#<b>end()</b></code></a>
145
- * <a href="#removeOutgoingMessage"><code>mqtt.Client#<b>removeOutgoingMessage()</b></code></a>
146
- * <a href="#reconnect"><code>mqtt.Client#<b>reconnect()</b></code></a>
147
- * <a href="#handleMessage"><code>mqtt.Client#<b>handleMessage()</b></code></a>
148
- * <a href="#connected"><code>mqtt.Client#<b>connected</b></code></a>
149
- * <a href="#reconnecting"><code>mqtt.Client#<b>reconnecting</b></code></a>
150
- * <a href="#getLastMessageId"><code>mqtt.Client#<b>getLastMessageId()</b></code></a>
151
- * <a href="#store"><code>mqtt.<b>Store()</b></code></a>
152
- * <a href="#put"><code>mqtt.Store#<b>put()</b></code></a>
153
- * <a href="#del"><code>mqtt.Store#<b>del()</b></code></a>
154
- * <a href="#createStream"><code>mqtt.Store#<b>createStream()</b></code></a>
155
- * <a href="#close"><code>mqtt.Store#<b>close()</b></code></a>
156
-
157
- -------------------------------------------------------
158
- <a name="connect"></a>
159
- ### mqtt.connect([url], options)
160
-
161
- Connects to the broker specified by the given url and options and
162
- returns a [Client](#client).
163
-
164
- The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp',
165
- 'tls', 'ws', 'wss'. The URL can also be an object as returned by
166
- [`URL.parse()`](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost),
167
- in that case the two objects are merged, i.e. you can pass a single
168
- object with both the URL and the connect options.
169
-
170
- You can also specify a `servers` options with content: `[{ host:
171
- 'localhost', port: 1883 }, ... ]`, in that case that array is iterated
172
- at every connect.
173
-
174
- For all MQTT-related options, see the [Client](#client)
175
- constructor.
176
-
177
- -------------------------------------------------------
178
- <a name="client"></a>
179
- ### mqtt.Client(streamBuilder, options)
180
-
181
- The `Client` class wraps a client connection to an
182
- MQTT broker over an arbitrary transport method (TCP, TLS,
183
- WebSocket, ecc).
184
-
185
- `Client` automatically handles the following:
186
-
187
- * Regular server pings
188
- * QoS flow
189
- * Automatic reconnections
190
- * Start publishing before being connected
191
-
192
- The arguments are:
193
-
194
- * `streamBuilder` is a function that returns a subclass of the `Stream` class that supports
195
- the `connect` event. Typically a `net.Socket`.
196
- * `options` is the client connection options (see: the [connect packet](https://github.com/mcollina/mqtt-packet#connect)). Defaults:
197
- * `wsOptions`: is the WebSocket connection options. Default is `{}`.
198
- It's specific for WebSockets. For possible options have a look at: https://github.com/websockets/ws/blob/master/doc/ws.md.
199
- * `keepalive`: `60` seconds, set to `0` to disable
200
- * `reschedulePings`: reschedule ping messages after sending packets (default `true`)
201
- * `clientId`: `'mqttjs_' + Math.random().toString(16).substr(2, 8)`
202
- * `protocolId`: `'MQTT'`
203
- * `protocolVersion`: `4`
204
- * `clean`: `true`, set to false to receive QoS 1 and 2 messages while
205
- offline
206
- * `reconnectPeriod`: `1000` milliseconds, interval between two
207
- reconnections
208
- * `connectTimeout`: `30 * 1000` milliseconds, time to wait before a
209
- CONNACK is received
210
- * `username`: the username required by your broker, if any
211
- * `password`: the password required by your broker, if any
212
- * `incomingStore`: a [Store](#store) for the incoming packets
213
- * `outgoingStore`: a [Store](#store) for the outgoing packets
214
- * `queueQoSZero`: if connection is broken, queue outgoing QoS zero messages (default `true`)
215
- * `will`: a message that will sent by the broker automatically when
216
- the client disconnect badly. The format is:
217
- * `topic`: the topic to publish
218
- * `payload`: the message to publish
219
- * `qos`: the QoS
220
- * `retain`: the retain flag
221
- * `transformWsUrl` : optional `(url, options, client) => url` function
222
- For ws/wss protocols only. Can be used to implement signing
223
- urls which upon reconnect can have become expired.
224
- * `resubscribe` : if connection is broken and reconnects,
225
- subscribed topics are automatically subscribed again (default `true`)
226
-
227
- In case mqtts (mqtt over tls) is required, the `options` object is
228
- passed through to
229
- [`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
230
- If you are using a **self-signed certificate**, pass the `rejectUnauthorized: false` option.
231
- Beware that you are exposing yourself to man in the middle attacks, so it is a configuration
232
- that is not recommended for production environments.
233
-
234
- If you are connecting to a broker that supports only MQTT 3.1 (not
235
- 3.1.1 compliant), you should pass these additional options:
236
-
237
- ```js
238
- {
239
- protocolId: 'MQIsdp',
240
- protocolVersion: 3
241
- }
242
- ```
243
-
244
- This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto
245
- version 1.3 and 1.4 works fine without those.
246
-
247
- #### Event `'connect'`
248
-
249
- `function (connack) {}`
250
-
251
- Emitted on successful (re)connection (i.e. connack rc=0).
252
- * `connack` received connack packet. When `clean` connection option is `false` and server has a previous session
253
- for `clientId` connection option, then `connack.sessionPresent` flag is `true`. When that is the case,
254
- you may rely on stored session and prefer not to send subscribe commands for the client.
255
-
256
- #### Event `'reconnect'`
257
-
258
- `function () {}`
259
-
260
- Emitted when a reconnect starts.
261
-
262
- #### Event `'close'`
263
-
264
- `function () {}`
265
-
266
- Emitted after a disconnection.
267
-
268
- #### Event `'offline'`
269
-
270
- `function () {}`
271
-
272
- Emitted when the client goes offline.
273
-
274
- #### Event `'error'`
275
-
276
- `function (error) {}`
277
-
278
- Emitted when the client cannot connect (i.e. connack rc != 0) or when a
279
- parsing error occurs.
280
-
281
- #### Event `'end'`
282
-
283
- `function () {}`
284
-
285
- Emitted when <a href="#end"><code>mqtt.Client#<b>end()</b></code></a> is called.
286
- If a callback was passed to `mqtt.Client#end()`, this event is emitted once the
287
- callback returns.
288
-
289
- #### Event `'message'`
290
-
291
- `function (topic, message, packet) {}`
292
-
293
- Emitted when the client receives a publish packet
294
- * `topic` topic of the received packet
295
- * `message` payload of the received packet
296
- * `packet` received packet, as defined in
297
- [mqtt-packet](https://github.com/mcollina/mqtt-packet#publish)
298
-
299
- #### Event `'packetsend'`
300
-
301
- `function (packet) {}`
302
-
303
- Emitted when the client sends any packet. This includes .published() packets
304
- as well as packets used by MQTT for managing subscriptions and connections
305
- * `packet` received packet, as defined in
306
- [mqtt-packet](https://github.com/mcollina/mqtt-packet)
307
-
308
- #### Event `'packetreceive'`
309
-
310
- `function (packet) {}`
311
-
312
- Emitted when the client receives any packet. This includes packets from
313
- subscribed topics as well as packets used by MQTT for managing subscriptions
314
- and connections
315
- * `packet` received packet, as defined in
316
- [mqtt-packet](https://github.com/mcollina/mqtt-packet)
317
-
318
- -------------------------------------------------------
319
- <a name="publish"></a>
320
- ### mqtt.Client#publish(topic, message, [options], [callback])
321
-
322
- Publish a message to a topic
323
-
324
- * `topic` is the topic to publish to, `String`
325
- * `message` is the message to publish, `Buffer` or `String`
326
- * `options` is the options to publish with, including:
327
- * `qos` QoS level, `Number`, default `0`
328
- * `retain` retain flag, `Boolean`, default `false`
329
- * `dup` mark as duplicate flag, `Boolean`, default `false`
330
- * `callback` - `function (err)`, fired when the QoS handling completes,
331
- or at the next tick if QoS 0. An error occurs if client is disconnecting.
332
-
333
- -------------------------------------------------------
334
- <a name="subscribe"></a>
335
- ### mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback])
336
-
337
- Subscribe to a topic or topics
338
-
339
- * `topic` is a `String` topic to subscribe to or an `Array` of
340
- topics to subscribe to. It can also be an object, it has as object
341
- keys the topic name and as value the QoS, like `{'test1': 0, 'test2': 1}`.
342
- MQTT `topic` wildcard characters are supported (`+` - for single level and `#` - for multi level)
343
- * `options` is the options to subscribe with, including:
344
- * `qos` qos subscription level, default 0
345
- * `callback` - `function (err, granted)`
346
- callback fired on suback where:
347
- * `err` a subscription error or an error that occurs when client is disconnecting
348
- * `granted` is an array of `{topic, qos}` where:
349
- * `topic` is a subscribed to topic
350
- * `qos` is the granted qos level on it
351
-
352
- -------------------------------------------------------
353
- <a name="unsubscribe"></a>
354
- ### mqtt.Client#unsubscribe(topic/topic array, [callback])
355
-
356
- Unsubscribe from a topic or topics
357
-
358
- * `topic` is a `String` topic or an array of topics to unsubscribe from
359
- * `callback` - `function (err)`, fired on unsuback. An error occurs if client is disconnecting.
360
-
361
- -------------------------------------------------------
362
- <a name="end"></a>
363
- ### mqtt.Client#end([force], [cb])
364
-
365
- Close the client, accepts the following options:
366
-
367
- * `force`: passing it to true will close the client right away, without
368
- waiting for the in-flight messages to be acked. This parameter is
369
- optional.
370
- * `cb`: will be called when the client is closed. This parameter is
371
- optional.
372
-
373
- -------------------------------------------------------
374
- <a name="removeOutgoingMessage"></a>
375
- ### mqtt.Client#removeOutgoingMessage(mid)
376
-
377
- Remove a message from the outgoingStore.
378
- The outgoing callback will be called with Error('Message removed') if the message is removed.
379
-
380
- After this function is called, the messageId is released and becomes reusable.
381
-
382
- * `mid`: The messageId of the message in the outgoingStore.
383
-
384
- -------------------------------------------------------
385
- <a name="reconnect"></a>
386
- ### mqtt.Client#reconnect()
387
-
388
- Connect again using the same options as connect()
389
-
390
- -------------------------------------------------------
391
- <a name="handleMessage"></a>
392
- ### mqtt.Client#handleMessage(packet, callback)
393
-
394
- Handle messages with backpressure support, one at a time.
395
- Override at will, but __always call `callback`__, or the client
396
- will hang.
397
-
398
- -------------------------------------------------------
399
- <a name="connected"></a>
400
- ### mqtt.Client#connected
401
-
402
- Boolean : set to `true` if the client is connected. `false` otherwise.
403
-
404
- -------------------------------------------------------
405
- <a name="getLastMessageId"></a>
406
- ### mqtt.Client#getLastMessageId()
407
-
408
- Number : get last message id. This is for sent messages only.
409
-
410
- -------------------------------------------------------
411
- <a name="reconnecting"></a>
412
- ### mqtt.Client#reconnecting
413
-
414
- Boolean : set to `true` if the client is trying to reconnect to the server. `false` otherwise.
415
-
416
- -------------------------------------------------------
417
- <a name="store"></a>
418
- ### mqtt.Store(options)
419
-
420
- In-memory implementation of the message store.
421
-
422
- * `options` is the store options:
423
- * `clean`: `true`, clean inflight messages when close is called (default `true`)
424
-
425
- Other implementations of `mqtt.Store`:
426
-
427
- * [mqtt-level-store](http://npm.im/mqtt-level-store) which uses
428
- [Level-browserify](http://npm.im/level-browserify) to store the inflight
429
- data, making it usable both in Node and the Browser.
430
- * [mqtt-nedbb-store](https://github.com/behrad/mqtt-nedb-store) which
431
- uses [nedb](https://www.npmjs.com/package/nedb) to store the inflight
432
- data.
433
- * [mqtt-localforage-store](http://npm.im/mqtt-localforage-store) which uses
434
- [localForage](http://npm.im/localforage) to store the inflight
435
- data, making it usable in the Browser without browserify.
436
-
437
- -------------------------------------------------------
438
- <a name="put"></a>
439
- ### mqtt.Store#put(packet, callback)
440
-
441
- Adds a packet to the store, a packet is
442
- anything that has a `messageId` property.
443
- The callback is called when the packet has been stored.
444
-
445
- -------------------------------------------------------
446
- <a name="createStream"></a>
447
- ### mqtt.Store#createStream()
448
-
449
- Creates a stream with all the packets in the store.
450
-
451
- -------------------------------------------------------
452
- <a name="del"></a>
453
- ### mqtt.Store#del(packet, cb)
454
-
455
- Removes a packet from the store, a packet is
456
- anything that has a `messageId` property.
457
- The callback is called when the packet has been removed.
458
-
459
- -------------------------------------------------------
460
- <a name="close"></a>
461
- ### mqtt.Store#close(cb)
462
-
463
- Closes the Store.
464
-
465
- <a name="browser"></a>
466
- ## Browser
467
-
468
- <a name="cdn"></a>
469
- ### Via CDN
470
-
471
- The MQTT.js bundle is available through http://unpkg.com, specifically
472
- at https://unpkg.com/mqtt/dist/mqtt.min.js.
473
- See http://unpkg.com for the full documentation on version ranges.
474
-
475
- <a name="weapp"></a>
476
- ## Weixin App
477
- Surport [Weixin App](https://mp.weixin.qq.com/). See [Doc](https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-socket.html).
478
- <a name="example"></a>
479
-
480
- ## Example(js)
481
-
482
- ```js
483
- var mqtt = require('mqtt')
484
- var client = mqtt.connect('wxs://test.mosquitto.org')
485
- ```
486
-
487
- ## Example(ts)
488
-
489
- ```ts
490
- import { connect } from 'mqtt';
491
- const client = connect('wxs://test.mosquitto.org');
492
- ```
493
-
494
- <a name="browserify"></a>
495
- ### Browserify
496
-
497
- In order to use MQTT.js as a browserify module you can either require it in your browserify bundles or build it as a stand alone module. The exported module is AMD/CommonJs compatible and it will add an object in the global space.
498
-
499
- ```javascript
500
- npm install -g browserify // install browserify
501
- cd node_modules/mqtt
502
- npm install . // install dev dependencies
503
- browserify mqtt.js -s mqtt > browserMqtt.js // require mqtt in your client-side app
504
- ```
505
-
506
- <a name="webpack"></a>
507
- ### Webpack
508
-
509
- Just like browserify, export MQTT.js as library. The exported module would be `var mqtt = xxx` and it will add an object in the global space. You could also export module in other [formats (AMD/CommonJS/others)](http://webpack.github.io/docs/configuration.html#output-librarytarget) by setting **output.libraryTarget** in webpack configuration.
510
-
511
- ```javascript
512
- npm install -g webpack // install webpack
513
-
514
- cd node_modules/mqtt
515
- npm install . // install dev dependencies
516
- webpack mqtt.js ./browserMqtt.js --output-library mqtt
517
- ```
518
-
519
- you can then use mqtt.js in the browser with the same api than node's one.
520
-
521
- ```html
522
- <html>
523
- <head>
524
- <title>test Ws mqtt.js</title>
525
- </head>
526
- <body>
527
- <script src="./browserMqtt.js"></script>
528
- <script>
529
- var client = mqtt.connect() // you add a ws:// url here
530
- client.subscribe("mqtt/demo")
531
-
532
- client.on("message", function (topic, payload) {
533
- alert([topic, payload].join(": "))
534
- client.end()
535
- })
536
-
537
- client.publish("mqtt/demo", "hello world!")
538
- </script>
539
- </body>
540
- </html>
541
- ```
542
-
543
- Your broker should accept websocket connection (see [MQTT over Websockets](https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets) to setup [Mosca](http://mcollina.github.io/mosca/)).
544
-
545
- <a name="signedurls"></a>
546
- ### Signed WebSocket Urls
547
-
548
- If you need to sign an url, for example for [AWS IoT](http://docs.aws.amazon.com/iot/latest/developerguide/protocols.html#mqtt-ws),
549
- then you can pass in a `transformWsUrl` function to the <a href="#connect"><code>mqtt.<b>connect()</b></code></a> options
550
- This is needed because signed urls have an expiry and eventually upon reconnects, a new signed url needs to be created:
551
-
552
- ```js
553
- // This module doesn't actually exist, just an example
554
- var awsIotUrlSigner = require('awsIotUrlSigner')
555
- mqtt.connect('wss://a2ukbzaqo9vbpb.iot.ap-southeast-1.amazonaws.com/mqtt', {
556
- transformWsUrl: function (url, options, client) {
557
- // It's possible to inspect some state on options(pre parsed url components)
558
- // and the client (reconnect state etc)
559
- return awsIotUrlSigner(url)
560
- }
561
- })
562
-
563
- // Now every time a new WebSocket connection is opened (hopefully not that
564
- // often) we get a freshly signed url
565
-
566
- ```
567
-
568
- <a name="qos"></a>
569
- ## About QoS
570
-
571
- Here is how QoS works:
572
-
573
- * QoS 0 : received **at most once** : The packet is sent, and that's it. There is no validation about whether it has been received.
574
- * QoS 1 : received **at least once** : The packet is sent and stored as long as the client has not received a confirmation from the server. MQTT ensures that it *will* be received, but there can be duplicates.
575
- * QoS 2 : received **exactly once** : Same as QoS 1 but there is no duplicates.
576
-
577
- About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that's a concern to you.
578
-
579
- <a name="typescript"></a>
580
- ## Usage with TypeScript
581
- This repo bundles TypeScript definition files for use in TypeScript projects and to support tools that can read `.d.ts` files.
582
-
583
- ### Pre-requisites
584
- Before you can begin using these TypeScript definitions with your project, you need to make sure your project meets a few of these requirements:
585
- * TypeScript >= 2.1
586
- * Set tsconfig.json: `{"compilerOptions" : {"moduleResolution" : "node"}, ...}`
587
- * Includes the TypeScript definitions for node. You can use npm to install this by typing the following into a terminal window:
588
- `npm install --save-dev @types/node`
589
-
590
- <a name="contributing"></a>
591
- ## Contributing
592
-
593
- MQTT.js is an **OPEN Open Source Project**. This means that:
594
-
595
- > 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.
596
-
597
- See the [CONTRIBUTING.md](https://github.com/mqttjs/MQTT.js/blob/master/CONTRIBUTING.md) file for more details.
598
-
599
- ### Contributors
600
-
601
- MQTT.js is only possible due to the excellent work of the following contributors:
602
-
603
- <table><tbody>
604
- <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>
605
- <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>
606
- <tr><th align="left">Maxime Agor</th><td><a href="https://github.com/4rzael">GitHub/4rzael</a></td><td><a href="http://twitter.com/4rzael">Twitter/@4rzael</a></td></tr>
607
- </tbody></table>
608
-
609
- <a name="license"></a>
610
- ## License
611
-
612
- MIT
1
+ ![mqtt.js](https://raw.githubusercontent.com/mqttjs/MQTT.js/137ee0e3940c1f01049a30248c70f24dc6e6f829/MQTT.js.png)
2
+ =======
3
+
4
+ [![Build Status](https://travis-ci.org/mqttjs/MQTT.js.svg)](https://travis-ci.org/mqttjs/MQTT.js) [![codecov](https://codecov.io/gh/mqttjs/MQTT.js/branch/master/graph/badge.svg)](https://codecov.io/gh/mqttjs/MQTT.js)
5
+
6
+ [![NPM](https://nodei.co/npm-dl/mqtt.png)](https://nodei.co/npm/mqtt/) [![NPM](https://nodei.co/npm/mqtt.png)](https://nodei.co/npm/mqtt/)
7
+
8
+ [![Sauce Test Status](https://saucelabs.com/browser-matrix/mqttjs.svg)](https://saucelabs.com/u/mqttjs)
9
+
10
+ MQTT.js is a client library for the [MQTT](http://mqtt.org/) protocol, written
11
+ in JavaScript for node.js and the browser.
12
+
13
+ * [Upgrade notes](#notes)
14
+ * [Installation](#install)
15
+ * [Example](#example)
16
+ * [Command Line Tools](#cli)
17
+ * [API](#api)
18
+ * [Browser](#browser)
19
+ * [Weapp](#weapp)
20
+ * [About QoS](#qos)
21
+ * [TypeScript](#typescript)
22
+ * [Contributing](#contributing)
23
+ * [License](#license)
24
+
25
+ MQTT.js is an OPEN Open Source Project, see the [Contributing](#contributing) section to find out what this means.
26
+
27
+ [![JavaScript Style
28
+ Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
29
+
30
+
31
+ <a name="notes"></a>
32
+ ## Important notes for existing users
33
+
34
+ v2.0.0 removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending
35
+ packets. It also removes all the deprecated functionality in v1.0.0,
36
+ mainly `mqtt.createConnection` and `mqtt.Server`. From v2.0.0,
37
+ subscriptions are restored upon reconnection if `clean: true`.
38
+ v1.x.x is now in *LTS*, and it will keep being supported as long as
39
+ there are v0.8, v0.10 and v0.12 users.
40
+
41
+ v1.0.0 improves the overall architecture of the project, which is now
42
+ split into three components: MQTT.js keeps the Client,
43
+ [mqtt-connection](http://npm.im/mqtt-connection) includes the barebone
44
+ Connection code for server-side usage, and [mqtt-packet](http://npm.im/mqtt-packet)
45
+ includes the protocol parser and generator. The new Client improves
46
+ performance by a 30% factor, embeds Websocket support
47
+ ([MOWS](http://npm.im/mows) is now deprecated), and it has a better
48
+ support for QoS 1 and 2. The previous API is still supported but
49
+ deprecated, as such, it is not documented in this README.
50
+
51
+ As a __breaking change__, the `encoding` option in the old client is
52
+ removed, and now everything is UTF-8 with the exception of the
53
+ `password` in the CONNECT message and `payload` in the PUBLISH message,
54
+ which are `Buffer`.
55
+
56
+ Another __breaking change__ is that MQTT.js now defaults to MQTT v3.1.1,
57
+ so to support old brokers, please read the [client options doc](#client).
58
+
59
+ MQTT v5 support is experimental as it has not been implemented by brokers yet.
60
+
61
+ <a name="install"></a>
62
+ ## Installation
63
+
64
+ ```sh
65
+ npm install mqtt --save
66
+ ```
67
+
68
+ <a name="example"></a>
69
+ ## Example
70
+
71
+ For the sake of simplicity, let's put the subscriber and the publisher in the same file:
72
+
73
+ ```js
74
+ var mqtt = require('mqtt')
75
+ var client = mqtt.connect('mqtt://test.mosquitto.org')
76
+
77
+ client.on('connect', function () {
78
+ client.subscribe('presence', function (err) {
79
+ if (!err) {
80
+ client.publish('presence', 'Hello mqtt')
81
+ }
82
+ })
83
+ })
84
+
85
+ client.on('message', function (topic, message) {
86
+ // message is Buffer
87
+ console.log(message.toString())
88
+ client.end()
89
+ })
90
+ ```
91
+
92
+ output:
93
+ ```
94
+ Hello mqtt
95
+ ```
96
+
97
+ If you want to run your own MQTT broker, you can use
98
+ [Mosquitto](http://mosquitto.org) or
99
+ [Mosca](http://mcollina.github.io/mosca/), and launch it.
100
+ You can also use a test instance: test.mosquitto.org and test.mosca.io
101
+ are both public.
102
+
103
+ If you do not want to install a separate broker, you can try using the
104
+ [mqtt-connection](https://www.npmjs.com/package/mqtt-connection).
105
+
106
+ to use MQTT.js in the browser see the [browserify](#browserify) section
107
+
108
+ <a name="promises"></a>
109
+ ## Promise support
110
+
111
+ If you want to use the new [async-await](https://blog.risingstack.com/async-await-node-js-7-nightly/) functionality in JavaScript, or just prefer using Promises instead of callbacks, [async-mqtt](https://github.com/mqttjs/async-mqtt) is a wrapper over MQTT.js which uses promises instead of callbacks when possible.
112
+
113
+ <a name="cli"></a>
114
+ ## Command Line Tools
115
+
116
+ MQTT.js bundles a command to interact with a broker.
117
+ In order to have it available on your path, you should install MQTT.js
118
+ globally:
119
+
120
+ ```sh
121
+ npm install mqtt -g
122
+ ```
123
+
124
+ Then, on one terminal
125
+
126
+ ```
127
+ mqtt sub -t 'hello' -h 'test.mosquitto.org' -v
128
+ ```
129
+
130
+ On another
131
+
132
+ ```
133
+ mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'
134
+ ```
135
+
136
+ See `mqtt help <command>` for the command help.
137
+
138
+ <a name="api"></a>
139
+ ## API
140
+
141
+ * <a href="#connect"><code>mqtt.<b>connect()</b></code></a>
142
+ * <a href="#client"><code>mqtt.<b>Client()</b></code></a>
143
+ * <a href="#publish"><code>mqtt.Client#<b>publish()</b></code></a>
144
+ * <a href="#subscribe"><code>mqtt.Client#<b>subscribe()</b></code></a>
145
+ * <a href="#unsubscribe"><code>mqtt.Client#<b>unsubscribe()</b></code></a>
146
+ * <a href="#end"><code>mqtt.Client#<b>end()</b></code></a>
147
+ * <a href="#removeOutgoingMessage"><code>mqtt.Client#<b>removeOutgoingMessage()</b></code></a>
148
+ * <a href="#reconnect"><code>mqtt.Client#<b>reconnect()</b></code></a>
149
+ * <a href="#handleMessage"><code>mqtt.Client#<b>handleMessage()</b></code></a>
150
+ * <a href="#connected"><code>mqtt.Client#<b>connected</b></code></a>
151
+ * <a href="#reconnecting"><code>mqtt.Client#<b>reconnecting</b></code></a>
152
+ * <a href="#getLastMessageId"><code>mqtt.Client#<b>getLastMessageId()</b></code></a>
153
+ * <a href="#store"><code>mqtt.<b>Store()</b></code></a>
154
+ * <a href="#put"><code>mqtt.Store#<b>put()</b></code></a>
155
+ * <a href="#del"><code>mqtt.Store#<b>del()</b></code></a>
156
+ * <a href="#createStream"><code>mqtt.Store#<b>createStream()</b></code></a>
157
+ * <a href="#close"><code>mqtt.Store#<b>close()</b></code></a>
158
+
159
+ -------------------------------------------------------
160
+ <a name="connect"></a>
161
+ ### mqtt.connect([url], options)
162
+
163
+ Connects to the broker specified by the given url and options and
164
+ returns a [Client](#client).
165
+
166
+ The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp',
167
+ 'tls', 'ws', 'wss'. The URL can also be an object as returned by
168
+ [`URL.parse()`](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost),
169
+ in that case the two objects are merged, i.e. you can pass a single
170
+ object with both the URL and the connect options.
171
+
172
+ You can also specify a `servers` options with content: `[{ host:
173
+ 'localhost', port: 1883 }, ... ]`, in that case that array is iterated
174
+ at every connect.
175
+
176
+ For all MQTT-related options, see the [Client](#client)
177
+ constructor.
178
+
179
+ -------------------------------------------------------
180
+ <a name="client"></a>
181
+ ### mqtt.Client(streamBuilder, options)
182
+
183
+ The `Client` class wraps a client connection to an
184
+ MQTT broker over an arbitrary transport method (TCP, TLS,
185
+ WebSocket, ecc).
186
+
187
+ `Client` automatically handles the following:
188
+
189
+ * Regular server pings
190
+ * QoS flow
191
+ * Automatic reconnections
192
+ * Start publishing before being connected
193
+
194
+ The arguments are:
195
+
196
+ * `streamBuilder` is a function that returns a subclass of the `Stream` class that supports
197
+ the `connect` event. Typically a `net.Socket`.
198
+ * `options` is the client connection options (see: the [connect packet](https://github.com/mcollina/mqtt-packet#connect)). Defaults:
199
+ * `wsOptions`: is the WebSocket connection options. Default is `{}`.
200
+ It's specific for WebSockets. For possible options have a look at: https://github.com/websockets/ws/blob/master/doc/ws.md.
201
+ * `keepalive`: `60` seconds, set to `0` to disable
202
+ * `reschedulePings`: reschedule ping messages after sending packets (default `true`)
203
+ * `clientId`: `'mqttjs_' + Math.random().toString(16).substr(2, 8)`
204
+ * `protocolId`: `'MQTT'`
205
+ * `protocolVersion`: `4`
206
+ * `clean`: `true`, set to false to receive QoS 1 and 2 messages while
207
+ offline
208
+ * `reconnectPeriod`: `1000` milliseconds, interval between two
209
+ reconnections
210
+ * `connectTimeout`: `30 * 1000` milliseconds, time to wait before a
211
+ CONNACK is received
212
+ * `username`: the username required by your broker, if any
213
+ * `password`: the password required by your broker, if any
214
+ * `incomingStore`: a [Store](#store) for the incoming packets
215
+ * `outgoingStore`: a [Store](#store) for the outgoing packets
216
+ * `queueQoSZero`: if connection is broken, queue outgoing QoS zero messages (default `true`)
217
+ * `customHandleAcks`: MQTT 5 feature of custom handling puback and pubrec packets. Its callback:
218
+ ```js
219
+ customHandleAcks: function(topic, message, packet, done) {*some logic wit colling done(error, reasonCode)*}
220
+ ```
221
+ * `properties`: properties MQTT 5.0.
222
+ `object` that supports the following properties:
223
+ * `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
224
+ * `receiveMaximum`: representing the Receive Maximum value `number`,
225
+ * `maximumPacketSize`: representing the Maximum Packet Size the Client is willing to accept `number`,
226
+ * `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`,
227
+ * `requestResponseInformation`: The Client uses this value to request the Server to return Response Information in the CONNACK `boolean`,
228
+ * `requestProblemInformation`: The Client uses this value to indicate whether the Reason String or User Properties are sent in the case of failures `boolean`,
229
+ * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
230
+ * `authenticationMethod`: the name of the authentication method used for extended authentication `string`,
231
+ * `authenticationData`: Binary Data containing authentication data `binary`
232
+ * `authPacket`: settings for auth packet `object`
233
+ * `will`: a message that will sent by the broker automatically when
234
+ the client disconnect badly. The format is:
235
+ * `topic`: the topic to publish
236
+ * `payload`: the message to publish
237
+ * `qos`: the QoS
238
+ * `retain`: the retain flag
239
+ * `properties`: properties of will by MQTT 5.0:
240
+ * `willDelayInterval`: representing the Will Delay Interval in seconds `number`,
241
+ * `payloadFormatIndicator`: Will Message is UTF-8 Encoded Character Data or not `boolean`,
242
+ * `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`,
243
+ * `contentType`: describing the content of the Will Message `string`,
244
+ * `responseTopic`: String which is used as the Topic Name for a response message `string`,
245
+ * `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`,
246
+ * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
247
+ * `transformWsUrl` : optional `(url, options, client) => url` function
248
+ For ws/wss protocols only. Can be used to implement signing
249
+ urls which upon reconnect can have become expired.
250
+ * `resubscribe` : if connection is broken and reconnects,
251
+ subscribed topics are automatically subscribed again (default `true`)
252
+
253
+ In case mqtts (mqtt over tls) is required, the `options` object is
254
+ passed through to
255
+ [`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
256
+ If you are using a **self-signed certificate**, pass the `rejectUnauthorized: false` option.
257
+ Beware that you are exposing yourself to man in the middle attacks, so it is a configuration
258
+ that is not recommended for production environments.
259
+
260
+ If you are connecting to a broker that supports only MQTT 3.1 (not
261
+ 3.1.1 compliant), you should pass these additional options:
262
+
263
+ ```js
264
+ {
265
+ protocolId: 'MQIsdp',
266
+ protocolVersion: 3
267
+ }
268
+ ```
269
+
270
+ This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto
271
+ version 1.3 and 1.4 works fine without those.
272
+
273
+ #### Event `'connect'`
274
+
275
+ `function (connack) {}`
276
+
277
+ Emitted on successful (re)connection (i.e. connack rc=0).
278
+ * `connack` received connack packet. When `clean` connection option is `false` and server has a previous session
279
+ for `clientId` connection option, then `connack.sessionPresent` flag is `true`. When that is the case,
280
+ you may rely on stored session and prefer not to send subscribe commands for the client.
281
+
282
+ #### Event `'reconnect'`
283
+
284
+ `function () {}`
285
+
286
+ Emitted when a reconnect starts.
287
+
288
+ #### Event `'close'`
289
+
290
+ `function () {}`
291
+
292
+ Emitted after a disconnection.
293
+
294
+ #### Event `'disconnect'`
295
+
296
+ `function (packet) {}`
297
+
298
+ Emitted after receiving disconnect packet from broker. MQTT 5.0 feature.
299
+
300
+ #### Event `'offline'`
301
+
302
+ `function () {}`
303
+
304
+ Emitted when the client goes offline.
305
+
306
+ #### Event `'error'`
307
+
308
+ `function (error) {}`
309
+
310
+ Emitted when the client cannot connect (i.e. connack rc != 0) or when a
311
+ parsing error occurs.
312
+
313
+ #### Event `'end'`
314
+
315
+ `function () {}`
316
+
317
+ Emitted when <a href="#end"><code>mqtt.Client#<b>end()</b></code></a> is called.
318
+ If a callback was passed to `mqtt.Client#end()`, this event is emitted once the
319
+ callback returns.
320
+
321
+ #### Event `'message'`
322
+
323
+ `function (topic, message, packet) {}`
324
+
325
+ Emitted when the client receives a publish packet
326
+ * `topic` topic of the received packet
327
+ * `message` payload of the received packet
328
+ * `packet` received packet, as defined in
329
+ [mqtt-packet](https://github.com/mcollina/mqtt-packet#publish)
330
+
331
+ #### Event `'packetsend'`
332
+
333
+ `function (packet) {}`
334
+
335
+ Emitted when the client sends any packet. This includes .published() packets
336
+ as well as packets used by MQTT for managing subscriptions and connections
337
+ * `packet` received packet, as defined in
338
+ [mqtt-packet](https://github.com/mcollina/mqtt-packet)
339
+
340
+ #### Event `'packetreceive'`
341
+
342
+ `function (packet) {}`
343
+
344
+ Emitted when the client receives any packet. This includes packets from
345
+ subscribed topics as well as packets used by MQTT for managing subscriptions
346
+ and connections
347
+ * `packet` received packet, as defined in
348
+ [mqtt-packet](https://github.com/mcollina/mqtt-packet)
349
+
350
+ -------------------------------------------------------
351
+ <a name="publish"></a>
352
+ ### mqtt.Client#publish(topic, message, [options], [callback])
353
+
354
+ Publish a message to a topic
355
+
356
+ * `topic` is the topic to publish to, `String`
357
+ * `message` is the message to publish, `Buffer` or `String`
358
+ * `options` is the options to publish with, including:
359
+ * `qos` QoS level, `Number`, default `0`
360
+ * `retain` retain flag, `Boolean`, default `false`
361
+ * `dup` mark as duplicate flag, `Boolean`, default `false`
362
+ * `properties`: MQTT 5.0 properties `object`
363
+ * `payloadFormatIndicator`: Payload is UTF-8 Encoded Character Data or not `boolean`,
364
+ * `messageExpiryInterval`: the lifetime of the Application Message in seconds `number`,
365
+ * `topicAlias`: value that is used to identify the Topic instead of using the Topic Name `number`,
366
+ * `responseTopic`: String which is used as the Topic Name for a response message `string`,
367
+ * `correlationData`: used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`,
368
+ * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
369
+ * `subscriptionIdentifier`: representing the identifier of the subscription `number`,
370
+ * `contentType`: String describing the content of the Application Message `string`
371
+ * `cbStorePut` - `function ()`, fired when message is put into `outgoingStore` if QoS is `1` or `2`.
372
+ * `callback` - `function (err)`, fired when the QoS handling completes,
373
+ or at the next tick if QoS 0. An error occurs if client is disconnecting.
374
+
375
+ -------------------------------------------------------
376
+ <a name="subscribe"></a>
377
+ ### mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback])
378
+
379
+ Subscribe to a topic or topics
380
+
381
+ * `topic` is a `String` topic to subscribe to or an `Array` of
382
+ topics to subscribe to. It can also be an object, it has as object
383
+ keys the topic name and as value the QoS, like `{'test1': {qos: 0}, 'test2': {qos: 1}}`.
384
+ MQTT `topic` wildcard characters are supported (`+` - for single level and `#` - for multi level)
385
+ * `options` is the options to subscribe with, including:
386
+ * `qos` qos subscription level, default 0
387
+ * `nl` No Local MQTT 5.0 flag (If the value is true, Application Messages MUST NOT be forwarded to a connection with a ClientID equal to the ClientID of the publishing connection)
388
+ * `rap` Retain as Published MQTT 5.0 flag (If true, Application Messages forwarded using this subscription keep the RETAIN flag they were published with. If false, Application Messages forwarded using this subscription have the RETAIN flag set to 0.)
389
+ * `rh` Retain Handling MQTT 5.0 (This option specifies whether retained messages are sent when the subscription is established.)
390
+ * `properties`: `object`
391
+ * `subscriptionIdentifier`: representing the identifier of the subscription `number`,
392
+ * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
393
+ * `callback` - `function (err, granted)`
394
+ callback fired on suback where:
395
+ * `err` a subscription error or an error that occurs when client is disconnecting
396
+ * `granted` is an array of `{topic, qos}` where:
397
+ * `topic` is a subscribed to topic
398
+ * `qos` is the granted qos level on it
399
+
400
+ -------------------------------------------------------
401
+ <a name="unsubscribe"></a>
402
+ ### mqtt.Client#unsubscribe(topic/topic array, [options], [callback])
403
+
404
+ Unsubscribe from a topic or topics
405
+
406
+ * `topic` is a `String` topic or an array of topics to unsubscribe from
407
+ * `options`: options of unsubscribe.
408
+ * `properties`: `object`
409
+ * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
410
+ * `callback` - `function (err)`, fired on unsuback. An error occurs if client is disconnecting.
411
+
412
+ -------------------------------------------------------
413
+ <a name="end"></a>
414
+ ### mqtt.Client#end([force], [options], [cb])
415
+
416
+ Close the client, accepts the following options:
417
+
418
+ * `force`: passing it to true will close the client right away, without
419
+ waiting for the in-flight messages to be acked. This parameter is
420
+ optional.
421
+ * `options`: options of disconnect.
422
+ * `reasonCode`: Disconnect Reason Code `number`
423
+ * `properties`: `object`
424
+ * `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
425
+ * `reasonString`: representing the reason for the disconnect `string`,
426
+ * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
427
+ * `serverReference`: String which can be used by the Client to identify another Server to use `string`
428
+ * `cb`: will be called when the client is closed. This parameter is
429
+ optional.
430
+
431
+ -------------------------------------------------------
432
+ <a name="removeOutgoingMessage"></a>
433
+ ### mqtt.Client#removeOutgoingMessage(mid)
434
+
435
+ Remove a message from the outgoingStore.
436
+ The outgoing callback will be called with Error('Message removed') if the message is removed.
437
+
438
+ After this function is called, the messageId is released and becomes reusable.
439
+
440
+ * `mid`: The messageId of the message in the outgoingStore.
441
+
442
+ -------------------------------------------------------
443
+ <a name="reconnect"></a>
444
+ ### mqtt.Client#reconnect()
445
+
446
+ Connect again using the same options as connect()
447
+
448
+ -------------------------------------------------------
449
+ <a name="handleMessage"></a>
450
+ ### mqtt.Client#handleMessage(packet, callback)
451
+
452
+ Handle messages with backpressure support, one at a time.
453
+ Override at will, but __always call `callback`__, or the client
454
+ will hang.
455
+
456
+ -------------------------------------------------------
457
+ <a name="connected"></a>
458
+ ### mqtt.Client#connected
459
+
460
+ Boolean : set to `true` if the client is connected. `false` otherwise.
461
+
462
+ -------------------------------------------------------
463
+ <a name="getLastMessageId"></a>
464
+ ### mqtt.Client#getLastMessageId()
465
+
466
+ Number : get last message id. This is for sent messages only.
467
+
468
+ -------------------------------------------------------
469
+ <a name="reconnecting"></a>
470
+ ### mqtt.Client#reconnecting
471
+
472
+ Boolean : set to `true` if the client is trying to reconnect to the server. `false` otherwise.
473
+
474
+ -------------------------------------------------------
475
+ <a name="store"></a>
476
+ ### mqtt.Store(options)
477
+
478
+ In-memory implementation of the message store.
479
+
480
+ * `options` is the store options:
481
+ * `clean`: `true`, clean inflight messages when close is called (default `true`)
482
+
483
+ Other implementations of `mqtt.Store`:
484
+
485
+ * [mqtt-level-store](http://npm.im/mqtt-level-store) which uses
486
+ [Level-browserify](http://npm.im/level-browserify) to store the inflight
487
+ data, making it usable both in Node and the Browser.
488
+ * [mqtt-nedbb-store](https://github.com/behrad/mqtt-nedb-store) which
489
+ uses [nedb](https://www.npmjs.com/package/nedb) to store the inflight
490
+ data.
491
+ * [mqtt-localforage-store](http://npm.im/mqtt-localforage-store) which uses
492
+ [localForage](http://npm.im/localforage) to store the inflight
493
+ data, making it usable in the Browser without browserify.
494
+
495
+ -------------------------------------------------------
496
+ <a name="put"></a>
497
+ ### mqtt.Store#put(packet, callback)
498
+
499
+ Adds a packet to the store, a packet is
500
+ anything that has a `messageId` property.
501
+ The callback is called when the packet has been stored.
502
+
503
+ -------------------------------------------------------
504
+ <a name="createStream"></a>
505
+ ### mqtt.Store#createStream()
506
+
507
+ Creates a stream with all the packets in the store.
508
+
509
+ -------------------------------------------------------
510
+ <a name="del"></a>
511
+ ### mqtt.Store#del(packet, cb)
512
+
513
+ Removes a packet from the store, a packet is
514
+ anything that has a `messageId` property.
515
+ The callback is called when the packet has been removed.
516
+
517
+ -------------------------------------------------------
518
+ <a name="close"></a>
519
+ ### mqtt.Store#close(cb)
520
+
521
+ Closes the Store.
522
+
523
+ <a name="browser"></a>
524
+ ## Browser
525
+
526
+ <a name="cdn"></a>
527
+ ### Via CDN
528
+
529
+ The MQTT.js bundle is available through http://unpkg.com, specifically
530
+ at https://unpkg.com/mqtt/dist/mqtt.min.js.
531
+ See http://unpkg.com for the full documentation on version ranges.
532
+
533
+ <a name="weapp"></a>
534
+ ## WeChat Mini Program
535
+ Support [WeChat Mini Program](https://mp.weixin.qq.com/). See [Doc](https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-socket.html).
536
+ <a name="example"></a>
537
+
538
+ ## Example(js)
539
+
540
+ ```js
541
+ var mqtt = require('mqtt')
542
+ var client = mqtt.connect('wxs://test.mosquitto.org')
543
+ ```
544
+
545
+ ## Example(ts)
546
+
547
+ ```ts
548
+ import { connect } from 'mqtt';
549
+ const client = connect('wxs://test.mosquitto.org');
550
+ ```
551
+
552
+ ## Ali Mini Program
553
+ Surport [Ali Mini Program](https://open.alipay.com/channel/miniIndex.htm). See [Doc](https://docs.alipay.com/mini/developer/getting-started).
554
+ <a name="example"></a>
555
+
556
+ ## Example(js)
557
+
558
+ ```js
559
+ var mqtt = require('mqtt')
560
+ var client = mqtt.connect('alis://test.mosquitto.org')
561
+ ```
562
+
563
+ ## Example(ts)
564
+
565
+ ```ts
566
+ import { connect } from 'mqtt';
567
+ const client = connect('alis://test.mosquitto.org');
568
+ ```
569
+
570
+ <a name="browserify"></a>
571
+ ### Browserify
572
+
573
+ In order to use MQTT.js as a browserify module you can either require it in your browserify bundles or build it as a stand alone module. The exported module is AMD/CommonJs compatible and it will add an object in the global space.
574
+
575
+ ```javascript
576
+ npm install -g browserify // install browserify
577
+ cd node_modules/mqtt
578
+ npm install . // install dev dependencies
579
+ browserify mqtt.js -s mqtt > browserMqtt.js // require mqtt in your client-side app
580
+ ```
581
+
582
+ <a name="webpack"></a>
583
+ ### Webpack
584
+
585
+ Just like browserify, export MQTT.js as library. The exported module would be `var mqtt = xxx` and it will add an object in the global space. You could also export module in other [formats (AMD/CommonJS/others)](http://webpack.github.io/docs/configuration.html#output-librarytarget) by setting **output.libraryTarget** in webpack configuration.
586
+
587
+ ```javascript
588
+ npm install -g webpack // install webpack
589
+
590
+ cd node_modules/mqtt
591
+ npm install . // install dev dependencies
592
+ webpack mqtt.js ./browserMqtt.js --output-library mqtt
593
+ ```
594
+
595
+ you can then use mqtt.js in the browser with the same api than node's one.
596
+
597
+ ```html
598
+ <html>
599
+ <head>
600
+ <title>test Ws mqtt.js</title>
601
+ </head>
602
+ <body>
603
+ <script src="./browserMqtt.js"></script>
604
+ <script>
605
+ var client = mqtt.connect() // you add a ws:// url here
606
+ client.subscribe("mqtt/demo")
607
+
608
+ client.on("message", function (topic, payload) {
609
+ alert([topic, payload].join(": "))
610
+ client.end()
611
+ })
612
+
613
+ client.publish("mqtt/demo", "hello world!")
614
+ </script>
615
+ </body>
616
+ </html>
617
+ ```
618
+
619
+ Your broker should accept websocket connection (see [MQTT over Websockets](https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets) to setup [Mosca](http://mcollina.github.io/mosca/)).
620
+
621
+ <a name="signedurls"></a>
622
+ ### Signed WebSocket Urls
623
+
624
+ If you need to sign an url, for example for [AWS IoT](http://docs.aws.amazon.com/iot/latest/developerguide/protocols.html#mqtt-ws),
625
+ then you can pass in a `transformWsUrl` function to the <a href="#connect"><code>mqtt.<b>connect()</b></code></a> options
626
+ This is needed because signed urls have an expiry and eventually upon reconnects, a new signed url needs to be created:
627
+
628
+ ```js
629
+ // This module doesn't actually exist, just an example
630
+ var awsIotUrlSigner = require('awsIotUrlSigner')
631
+ mqtt.connect('wss://a2ukbzaqo9vbpb.iot.ap-southeast-1.amazonaws.com/mqtt', {
632
+ transformWsUrl: function (url, options, client) {
633
+ // It's possible to inspect some state on options(pre parsed url components)
634
+ // and the client (reconnect state etc)
635
+ return awsIotUrlSigner(url)
636
+ }
637
+ })
638
+
639
+ // Now every time a new WebSocket connection is opened (hopefully not that
640
+ // often) we get a freshly signed url
641
+
642
+ ```
643
+
644
+ <a name="qos"></a>
645
+ ## About QoS
646
+
647
+ Here is how QoS works:
648
+
649
+ * QoS 0 : received **at most once** : The packet is sent, and that's it. There is no validation about whether it has been received.
650
+ * QoS 1 : received **at least once** : The packet is sent and stored as long as the client has not received a confirmation from the server. MQTT ensures that it *will* be received, but there can be duplicates.
651
+ * QoS 2 : received **exactly once** : Same as QoS 1 but there is no duplicates.
652
+
653
+ About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that's a concern to you.
654
+
655
+ <a name="typescript"></a>
656
+ ## Usage with TypeScript
657
+ This repo bundles TypeScript definition files for use in TypeScript projects and to support tools that can read `.d.ts` files.
658
+
659
+ ### Pre-requisites
660
+ Before you can begin using these TypeScript definitions with your project, you need to make sure your project meets a few of these requirements:
661
+ * TypeScript >= 2.1
662
+ * Set tsconfig.json: `{"compilerOptions" : {"moduleResolution" : "node"}, ...}`
663
+ * Includes the TypeScript definitions for node. You can use npm to install this by typing the following into a terminal window:
664
+ `npm install --save-dev @types/node`
665
+
666
+ <a name="contributing"></a>
667
+ ## Contributing
668
+
669
+ MQTT.js is an **OPEN Open Source Project**. This means that:
670
+
671
+ > 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.
672
+
673
+ See the [CONTRIBUTING.md](https://github.com/mqttjs/MQTT.js/blob/master/CONTRIBUTING.md) file for more details.
674
+
675
+ ### Contributors
676
+
677
+ MQTT.js is only possible due to the excellent work of the following contributors:
678
+
679
+ <table><tbody>
680
+ <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>
681
+ <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>
682
+ <tr><th align="left">Maxime Agor</th><td><a href="https://github.com/4rzael">GitHub/4rzael</a></td><td><a href="http://twitter.com/4rzael">Twitter/@4rzael</a></td></tr>
683
+ <tr><th align="left">Siarhei Buntsevich</th><td><a href="https://github.com/scarry1992">GitHub/scarry1992</a></td></tr>
684
+ </tbody></table>
685
+
686
+ <a name="license"></a>
687
+ ## License
688
+
689
+ MIT