mqtt 2.18.8 → 2.18.9

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 (66) hide show
  1. package/CONTRIBUTING.md +27 -27
  2. package/LICENSE.md +15 -15
  3. package/README.md +612 -612
  4. package/bin/pub.js +146 -146
  5. package/bin/sub.js +123 -123
  6. package/dist/mqtt.js +14248 -10729
  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 +1129 -1129
  22. package/lib/connect/index.js +149 -149
  23. package/lib/connect/tcp.js +19 -19
  24. package/lib/connect/tls.js +41 -41
  25. package/lib/connect/ws.js +92 -92
  26. package/lib/connect/wx.js +110 -110
  27. package/lib/store.js +140 -140
  28. package/lib/validations.js +52 -52
  29. package/mqtt.js +41 -41
  30. package/package.json +107 -111
  31. package/test/abstract_client.js +2667 -2667
  32. package/test/abstract_store.js +135 -135
  33. package/test/browser/server.js +132 -132
  34. package/test/browser/test.js +92 -92
  35. package/test/browser/wx.js +93 -93
  36. package/test/client.js +544 -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 +65 -65
  54. package/test/store.js +10 -10
  55. package/test/typescript/broker-connect-subscribe-and-publish.ts +22 -22
  56. package/test/typescript/tsconfig.json +14 -14
  57. package/test/util.js +13 -13
  58. package/test/websocket_client.js +144 -144
  59. package/types/index.d.ts +27 -27
  60. package/types/lib/client-options.d.ts +137 -137
  61. package/types/lib/client.d.ts +196 -196
  62. package/types/lib/connect/index.d.ts +10 -10
  63. package/types/lib/store-options.d.ts +6 -6
  64. package/types/lib/store.d.ts +46 -46
  65. package/test/typescript/broker-connect-subscribe-and-publish.js +0 -24
  66. package/test/typescript/broker-connect-subscribe-and-publish.js.map +0 -1
package/README.md CHANGED
@@ -1,612 +1,612 @@
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
+ <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