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/lib/client.js CHANGED
@@ -1,1129 +1,1129 @@
1
- 'use strict'
2
-
3
- /**
4
- * Module dependencies
5
- */
6
- var events = require('events')
7
- var Store = require('./store')
8
- var eos = require('end-of-stream')
9
- var mqttPacket = require('mqtt-packet')
10
- var Writable = require('readable-stream').Writable
11
- var inherits = require('inherits')
12
- var reInterval = require('reinterval')
13
- var validations = require('./validations')
14
- var xtend = require('xtend')
15
- var setImmediate = global.setImmediate || function (callback) {
16
- // works in node v0.8
17
- process.nextTick(callback)
18
- }
19
- var defaultConnectOptions = {
20
- keepalive: 60,
21
- reschedulePings: true,
22
- protocolId: 'MQTT',
23
- protocolVersion: 4,
24
- reconnectPeriod: 1000,
25
- connectTimeout: 30 * 1000,
26
- clean: true,
27
- resubscribe: true
28
- }
29
-
30
- function defaultId () {
31
- return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
32
- }
33
-
34
- function sendPacket (client, packet, cb) {
35
- client.emit('packetsend', packet)
36
-
37
- var result = mqttPacket.writeToStream(packet, client.stream)
38
-
39
- if (!result && cb) {
40
- client.stream.once('drain', cb)
41
- } else if (cb) {
42
- cb()
43
- }
44
- }
45
-
46
- function flush (queue) {
47
- if (queue) {
48
- Object.keys(queue).forEach(function (messageId) {
49
- if (typeof queue[messageId] === 'function') {
50
- queue[messageId](new Error('Connection closed'))
51
- delete queue[messageId]
52
- }
53
- })
54
- }
55
- }
56
-
57
- function storeAndSend (client, packet, cb) {
58
- client.outgoingStore.put(packet, function storedPacket (err) {
59
- if (err) {
60
- return cb && cb(err)
61
- }
62
- sendPacket(client, packet, cb)
63
- })
64
- }
65
-
66
- function nop () {}
67
-
68
- /**
69
- * MqttClient constructor
70
- *
71
- * @param {Stream} stream - stream
72
- * @param {Object} [options] - connection options
73
- * (see Connection#connect)
74
- */
75
- function MqttClient (streamBuilder, options) {
76
- var k
77
- var that = this
78
-
79
- if (!(this instanceof MqttClient)) {
80
- return new MqttClient(streamBuilder, options)
81
- }
82
-
83
- this.options = options || {}
84
-
85
- // Defaults
86
- for (k in defaultConnectOptions) {
87
- if (typeof this.options[k] === 'undefined') {
88
- this.options[k] = defaultConnectOptions[k]
89
- } else {
90
- this.options[k] = options[k]
91
- }
92
- }
93
-
94
- this.options.clientId = (typeof this.options.clientId === 'string') ? this.options.clientId : defaultId()
95
-
96
- this.streamBuilder = streamBuilder
97
-
98
- // Inflight message storages
99
- this.outgoingStore = this.options.outgoingStore || new Store()
100
- this.incomingStore = this.options.incomingStore || new Store()
101
-
102
- // Should QoS zero messages be queued when the connection is broken?
103
- this.queueQoSZero = this.options.queueQoSZero === undefined ? true : this.options.queueQoSZero
104
-
105
- // map of subscribed topics to support reconnection
106
- this._resubscribeTopics = {}
107
-
108
- // map of a subscribe messageId and a topic
109
- this.messageIdToTopic = {}
110
-
111
- // Ping timer, setup in _setupPingTimer
112
- this.pingTimer = null
113
- // Is the client connected?
114
- this.connected = false
115
- // Are we disconnecting?
116
- this.disconnecting = false
117
- // Packet queue
118
- this.queue = []
119
- // connack timer
120
- this.connackTimer = null
121
- // Reconnect timer
122
- this.reconnectTimer = null
123
- /**
124
- * MessageIDs starting with 1
125
- * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
126
- */
127
- this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
128
-
129
- // Inflight callbacks
130
- this.outgoing = {}
131
-
132
- // Mark connected on connect
133
- this.on('connect', function () {
134
- if (this.disconnected) {
135
- return
136
- }
137
-
138
- this.connected = true
139
- var outStore = this.outgoingStore.createStream()
140
-
141
- this.once('close', remove)
142
- outStore.on('end', function () {
143
- that.removeListener('close', remove)
144
- })
145
- outStore.on('error', function (err) {
146
- that.removeListener('close', remove)
147
- that.emit('error', err)
148
- })
149
-
150
- function remove () {
151
- outStore.destroy()
152
- outStore = null
153
- }
154
-
155
- function storeDeliver () {
156
- // edge case, we wrapped this twice
157
- if (!outStore) {
158
- return
159
- }
160
-
161
- var packet = outStore.read(1)
162
- var cb
163
-
164
- if (!packet) {
165
- // read when data is available in the future
166
- outStore.once('readable', storeDeliver)
167
- return
168
- }
169
-
170
- // Avoid unnecessary stream read operations when disconnected
171
- if (!that.disconnecting && !that.reconnectTimer) {
172
- cb = that.outgoing[packet.messageId]
173
- that.outgoing[packet.messageId] = function (err, status) {
174
- // Ensure that the original callback passed in to publish gets invoked
175
- if (cb) {
176
- cb(err, status)
177
- }
178
-
179
- storeDeliver()
180
- }
181
- that._sendPacket(packet)
182
- } else if (outStore.destroy) {
183
- outStore.destroy()
184
- }
185
- }
186
-
187
- // start flowing
188
- storeDeliver()
189
- })
190
-
191
- // Mark disconnected on stream close
192
- this.on('close', function () {
193
- this.connected = false
194
- clearTimeout(this.connackTimer)
195
- })
196
-
197
- // Setup ping timer
198
- this.on('connect', this._setupPingTimer)
199
-
200
- // Send queued packets
201
- this.on('connect', function () {
202
- var queue = this.queue
203
-
204
- function deliver () {
205
- var entry = queue.shift()
206
- var packet = null
207
-
208
- if (!entry) {
209
- return
210
- }
211
-
212
- packet = entry.packet
213
-
214
- that._sendPacket(
215
- packet,
216
- function (err) {
217
- if (entry.cb) {
218
- entry.cb(err)
219
- }
220
- deliver()
221
- }
222
- )
223
- }
224
-
225
- deliver()
226
- })
227
-
228
- var firstConnection = true
229
- // resubscribe
230
- this.on('connect', function () {
231
- if (!firstConnection &&
232
- this.options.clean &&
233
- Object.keys(this._resubscribeTopics).length > 0) {
234
- if (this.options.resubscribe) {
235
- this._resubscribeTopics.resubscribe = true
236
- this.subscribe(this._resubscribeTopics)
237
- } else {
238
- this._resubscribeTopics = {}
239
- }
240
- }
241
-
242
- firstConnection = false
243
- })
244
-
245
- // Clear ping timer
246
- this.on('close', function () {
247
- if (that.pingTimer !== null) {
248
- that.pingTimer.clear()
249
- that.pingTimer = null
250
- }
251
- })
252
-
253
- // Setup reconnect timer on disconnect
254
- this.on('close', this._setupReconnect)
255
-
256
- events.EventEmitter.call(this)
257
-
258
- this._setupStream()
259
- }
260
- inherits(MqttClient, events.EventEmitter)
261
-
262
- /**
263
- * setup the event handlers in the inner stream.
264
- *
265
- * @api private
266
- */
267
- MqttClient.prototype._setupStream = function () {
268
- var connectPacket
269
- var that = this
270
- var writable = new Writable()
271
- var parser = mqttPacket.parser(this.options)
272
- var completeParse = null
273
- var packets = []
274
-
275
- this._clearReconnect()
276
-
277
- this.stream = this.streamBuilder(this)
278
-
279
- parser.on('packet', function (packet) {
280
- packets.push(packet)
281
- })
282
-
283
- function nextTickWork () {
284
- process.nextTick(work)
285
- }
286
-
287
- function work () {
288
- var packet = packets.shift()
289
- var done = completeParse
290
-
291
- if (packet) {
292
- that._handlePacket(packet, nextTickWork)
293
- } else {
294
- completeParse = null
295
- done()
296
- }
297
- }
298
-
299
- writable._write = function (buf, enc, done) {
300
- completeParse = done
301
- parser.parse(buf)
302
- work()
303
- }
304
-
305
- this.stream.pipe(writable)
306
-
307
- // Suppress connection errors
308
- this.stream.on('error', nop)
309
-
310
- // Echo stream close
311
- eos(this.stream, this.emit.bind(this, 'close'))
312
-
313
- // Send a connect packet
314
- connectPacket = Object.create(this.options)
315
- connectPacket.cmd = 'connect'
316
- // avoid message queue
317
- sendPacket(this, connectPacket)
318
-
319
- // Echo connection errors
320
- parser.on('error', this.emit.bind(this, 'error'))
321
-
322
- // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
323
- this.stream.setMaxListeners(1000)
324
-
325
- clearTimeout(this.connackTimer)
326
- this.connackTimer = setTimeout(function () {
327
- that._cleanUp(true)
328
- }, this.options.connectTimeout)
329
- }
330
-
331
- MqttClient.prototype._handlePacket = function (packet, done) {
332
- this.emit('packetreceive', packet)
333
-
334
- switch (packet.cmd) {
335
- case 'publish':
336
- this._handlePublish(packet, done)
337
- break
338
- case 'puback':
339
- case 'pubrec':
340
- case 'pubcomp':
341
- case 'suback':
342
- case 'unsuback':
343
- this._handleAck(packet)
344
- done()
345
- break
346
- case 'pubrel':
347
- this._handlePubrel(packet, done)
348
- break
349
- case 'connack':
350
- this._handleConnack(packet)
351
- done()
352
- break
353
- case 'pingresp':
354
- this._handlePingresp(packet)
355
- done()
356
- break
357
- default:
358
- // do nothing
359
- // maybe we should do an error handling
360
- // or just log it
361
- break
362
- }
363
- }
364
-
365
- MqttClient.prototype._checkDisconnecting = function (callback) {
366
- if (this.disconnecting) {
367
- if (callback) {
368
- callback(new Error('client disconnecting'))
369
- } else {
370
- this.emit('error', new Error('client disconnecting'))
371
- }
372
- }
373
- return this.disconnecting
374
- }
375
-
376
- /**
377
- * publish - publish <message> to <topic>
378
- *
379
- * @param {String} topic - topic to publish to
380
- * @param {String, Buffer} message - message to publish
381
- * @param {Object} [opts] - publish options, includes:
382
- * {Number} qos - qos level to publish on
383
- * {Boolean} retain - whether or not to retain the message
384
- * {Boolean} dup - whether or not mark a message as duplicate
385
- * @param {Function} [callback] - function(err){}
386
- * called when publish succeeds or fails
387
- * @returns {MqttClient} this - for chaining
388
- * @api public
389
- *
390
- * @example client.publish('topic', 'message');
391
- * @example
392
- * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
393
- * @example client.publish('topic', 'message', console.log);
394
- */
395
- MqttClient.prototype.publish = function (topic, message, opts, callback) {
396
- var packet
397
-
398
- // .publish(topic, payload, cb);
399
- if (typeof opts === 'function') {
400
- callback = opts
401
- opts = null
402
- }
403
-
404
- // default opts
405
- var defaultOpts = {qos: 0, retain: false, dup: false}
406
- opts = xtend(defaultOpts, opts)
407
-
408
- if (this._checkDisconnecting(callback)) {
409
- return this
410
- }
411
-
412
- packet = {
413
- cmd: 'publish',
414
- topic: topic,
415
- payload: message,
416
- qos: opts.qos,
417
- retain: opts.retain,
418
- messageId: this._nextId(),
419
- dup: opts.dup
420
- }
421
-
422
- switch (opts.qos) {
423
- case 1:
424
- case 2:
425
-
426
- // Add to callbacks
427
- this.outgoing[packet.messageId] = callback || nop
428
- this._sendPacket(packet)
429
- break
430
- default:
431
- this._sendPacket(packet, callback)
432
- break
433
- }
434
-
435
- return this
436
- }
437
-
438
- /**
439
- * subscribe - subscribe to <topic>
440
- *
441
- * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
442
- * @param {Object} [opts] - optional subscription options, includes:
443
- * {Number} qos - subscribe qos level
444
- * @param {Function} [callback] - function(err, granted){} where:
445
- * {Error} err - subscription error (none at the moment!)
446
- * {Array} granted - array of {topic: 't', qos: 0}
447
- * @returns {MqttClient} this - for chaining
448
- * @api public
449
- * @example client.subscribe('topic');
450
- * @example client.subscribe('topic', {qos: 1});
451
- * @example client.subscribe({'topic': 0, 'topic2': 1}, console.log);
452
- * @example client.subscribe('topic', console.log);
453
- */
454
- MqttClient.prototype.subscribe = function () {
455
- var packet
456
- var args = Array.prototype.slice.call(arguments)
457
- var subs = []
458
- var obj = args.shift()
459
- var resubscribe = obj.resubscribe
460
- var callback = args.pop() || nop
461
- var opts = args.pop()
462
- var invalidTopic
463
- var that = this
464
-
465
- delete obj.resubscribe
466
-
467
- if (typeof obj === 'string') {
468
- obj = [obj]
469
- }
470
-
471
- if (typeof callback !== 'function') {
472
- opts = callback
473
- callback = nop
474
- }
475
-
476
- invalidTopic = validations.validateTopics(obj)
477
- if (invalidTopic !== null) {
478
- setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
479
- return this
480
- }
481
-
482
- if (this._checkDisconnecting(callback)) {
483
- return this
484
- }
485
-
486
- var defaultOpts = { qos: 0 }
487
- opts = xtend(defaultOpts, opts)
488
-
489
- if (Array.isArray(obj)) {
490
- obj.forEach(function (topic) {
491
- if (that._resubscribeTopics[topic] < opts.qos ||
492
- !that._resubscribeTopics.hasOwnProperty(topic) ||
493
- resubscribe) {
494
- subs.push({
495
- topic: topic,
496
- qos: opts.qos
497
- })
498
- }
499
- })
500
- } else {
501
- Object
502
- .keys(obj)
503
- .forEach(function (k) {
504
- if (that._resubscribeTopics[k] < obj[k] ||
505
- !that._resubscribeTopics.hasOwnProperty(k) ||
506
- resubscribe) {
507
- subs.push({
508
- topic: k,
509
- qos: obj[k]
510
- })
511
- }
512
- })
513
- }
514
-
515
- packet = {
516
- cmd: 'subscribe',
517
- subscriptions: subs,
518
- qos: 1,
519
- retain: false,
520
- dup: false,
521
- messageId: this._nextId()
522
- }
523
-
524
- if (!subs.length) {
525
- callback(null, [])
526
- return
527
- }
528
-
529
- // subscriptions to resubscribe to in case of disconnect
530
- if (this.options.resubscribe) {
531
- var topics = []
532
- subs.forEach(function (sub) {
533
- if (that.options.reconnectPeriod > 0) {
534
- that._resubscribeTopics[sub.topic] = sub.qos
535
- topics.push(sub.topic)
536
- }
537
- })
538
- that.messageIdToTopic[packet.messageId] = topics
539
- }
540
-
541
- this.outgoing[packet.messageId] = function (err, packet) {
542
- if (!err) {
543
- var granted = packet.granted
544
- for (var i = 0; i < granted.length; i += 1) {
545
- subs[i].qos = granted[i]
546
- }
547
- }
548
-
549
- callback(err, subs)
550
- }
551
-
552
- this._sendPacket(packet)
553
-
554
- return this
555
- }
556
-
557
- /**
558
- * unsubscribe - unsubscribe from topic(s)
559
- *
560
- * @param {String, Array} topic - topics to unsubscribe from
561
- * @param {Function} [callback] - callback fired on unsuback
562
- * @returns {MqttClient} this - for chaining
563
- * @api public
564
- * @example client.unsubscribe('topic');
565
- * @example client.unsubscribe('topic', console.log);
566
- */
567
- MqttClient.prototype.unsubscribe = function (topic, callback) {
568
- var packet = {
569
- cmd: 'unsubscribe',
570
- qos: 1,
571
- messageId: this._nextId()
572
- }
573
- var that = this
574
-
575
- callback = callback || nop
576
-
577
- if (this._checkDisconnecting(callback)) {
578
- return this
579
- }
580
-
581
- if (typeof topic === 'string') {
582
- packet.unsubscriptions = [topic]
583
- } else if (typeof topic === 'object' && topic.length) {
584
- packet.unsubscriptions = topic
585
- }
586
-
587
- if (this.options.resubscribe) {
588
- packet.unsubscriptions.forEach(function (topic) {
589
- delete that._resubscribeTopics[topic]
590
- })
591
- }
592
-
593
- this.outgoing[packet.messageId] = callback
594
-
595
- this._sendPacket(packet)
596
-
597
- return this
598
- }
599
-
600
- /**
601
- * end - close connection
602
- *
603
- * @returns {MqttClient} this - for chaining
604
- * @param {Boolean} force - do not wait for all in-flight messages to be acked
605
- * @param {Function} cb - called when the client has been closed
606
- *
607
- * @api public
608
- */
609
- MqttClient.prototype.end = function (force, cb) {
610
- var that = this
611
-
612
- if (typeof force === 'function') {
613
- cb = force
614
- force = false
615
- }
616
-
617
- function closeStores () {
618
- that.disconnected = true
619
- that.incomingStore.close(function () {
620
- that.outgoingStore.close(function () {
621
- if (cb) {
622
- cb.apply(null, arguments)
623
- }
624
- that.emit('end')
625
- })
626
- })
627
- if (that._deferredReconnect) {
628
- that._deferredReconnect()
629
- }
630
- }
631
-
632
- function finish () {
633
- // defer closesStores of an I/O cycle,
634
- // just to make sure things are
635
- // ok for websockets
636
- that._cleanUp(force, setImmediate.bind(null, closeStores))
637
- }
638
-
639
- if (this.disconnecting) {
640
- return this
641
- }
642
-
643
- this._clearReconnect()
644
-
645
- this.disconnecting = true
646
-
647
- if (!force && Object.keys(this.outgoing).length > 0) {
648
- // wait 10ms, just to be sure we received all of it
649
- this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
650
- } else {
651
- finish()
652
- }
653
-
654
- return this
655
- }
656
-
657
- /**
658
- * removeOutgoingMessage - remove a message in outgoing store
659
- * the outgoing callback will be called withe Error('Message removed') if the message is removed
660
- *
661
- * @param {Number} mid - messageId to remove message
662
- * @returns {MqttClient} this - for chaining
663
- * @api public
664
- *
665
- * @example client.removeOutgoingMessage(client.getLastMessageId());
666
- */
667
- MqttClient.prototype.removeOutgoingMessage = function (mid) {
668
- var cb = this.outgoing[mid]
669
- delete this.outgoing[mid]
670
- this.outgoingStore.del({messageId: mid}, function () {
671
- cb(new Error('Message removed'))
672
- })
673
- return this
674
- }
675
-
676
- /**
677
- * reconnect - connect again using the same options as connect()
678
- *
679
- * @param {Object} [opts] - optional reconnect options, includes:
680
- * {Store} incomingStore - a store for the incoming packets
681
- * {Store} outgoingStore - a store for the outgoing packets
682
- * if opts is not given, current stores are used
683
- * @returns {MqttClient} this - for chaining
684
- *
685
- * @api public
686
- */
687
- MqttClient.prototype.reconnect = function (opts) {
688
- var that = this
689
- var f = function () {
690
- if (opts) {
691
- that.options.incomingStore = opts.incomingStore
692
- that.options.outgoingStore = opts.outgoingStore
693
- } else {
694
- that.options.incomingStore = null
695
- that.options.outgoingStore = null
696
- }
697
- that.incomingStore = that.options.incomingStore || new Store()
698
- that.outgoingStore = that.options.outgoingStore || new Store()
699
- that.disconnecting = false
700
- that.disconnected = false
701
- that._deferredReconnect = null
702
- that._reconnect()
703
- }
704
-
705
- if (this.disconnecting && !this.disconnected) {
706
- this._deferredReconnect = f
707
- } else {
708
- f()
709
- }
710
- return this
711
- }
712
-
713
- /**
714
- * _reconnect - implement reconnection
715
- * @api privateish
716
- */
717
- MqttClient.prototype._reconnect = function () {
718
- this.emit('reconnect')
719
- this._setupStream()
720
- }
721
-
722
- /**
723
- * _setupReconnect - setup reconnect timer
724
- */
725
- MqttClient.prototype._setupReconnect = function () {
726
- var that = this
727
-
728
- if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
729
- if (!this.reconnecting) {
730
- this.emit('offline')
731
- this.reconnecting = true
732
- }
733
- that.reconnectTimer = setInterval(function () {
734
- that._reconnect()
735
- }, that.options.reconnectPeriod)
736
- }
737
- }
738
-
739
- /**
740
- * _clearReconnect - clear the reconnect timer
741
- */
742
- MqttClient.prototype._clearReconnect = function () {
743
- if (this.reconnectTimer) {
744
- clearInterval(this.reconnectTimer)
745
- this.reconnectTimer = null
746
- }
747
- }
748
-
749
- /**
750
- * _cleanUp - clean up on connection end
751
- * @api private
752
- */
753
- MqttClient.prototype._cleanUp = function (forced, done) {
754
- if (done) {
755
- this.stream.on('close', done)
756
- }
757
-
758
- if (forced) {
759
- if ((this.options.reconnectPeriod === 0) && this.options.clean) {
760
- flush(this.outgoing)
761
- }
762
- this.stream.destroy()
763
- } else {
764
- this._sendPacket(
765
- { cmd: 'disconnect' },
766
- setImmediate.bind(
767
- null,
768
- this.stream.end.bind(this.stream)
769
- )
770
- )
771
- }
772
-
773
- if (!this.disconnecting) {
774
- this._clearReconnect()
775
- this._setupReconnect()
776
- }
777
-
778
- if (this.pingTimer !== null) {
779
- this.pingTimer.clear()
780
- this.pingTimer = null
781
- }
782
-
783
- if (done && !this.connected) {
784
- this.stream.removeListener('close', done)
785
- done()
786
- }
787
- }
788
-
789
- /**
790
- * _sendPacket - send or queue a packet
791
- * @param {String} type - packet type (see `protocol`)
792
- * @param {Object} packet - packet options
793
- * @param {Function} cb - callback when the packet is sent
794
- * @api private
795
- */
796
- MqttClient.prototype._sendPacket = function (packet, cb) {
797
- if (!this.connected) {
798
- if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
799
- this.queue.push({ packet: packet, cb: cb })
800
- } else if (packet.qos > 0) {
801
- cb = this.outgoing[packet.messageId]
802
- this.outgoingStore.put(packet, function (err) {
803
- if (err) {
804
- return cb && cb(err)
805
- }
806
- })
807
- } else if (cb) {
808
- cb(new Error('No connection to broker'))
809
- }
810
-
811
- return
812
- }
813
-
814
- // When sending a packet, reschedule the ping timer
815
- this._shiftPingInterval()
816
-
817
- switch (packet.cmd) {
818
- case 'publish':
819
- break
820
- case 'pubrel':
821
- storeAndSend(this, packet, cb)
822
- return
823
- default:
824
- sendPacket(this, packet, cb)
825
- return
826
- }
827
-
828
- switch (packet.qos) {
829
- case 2:
830
- case 1:
831
- storeAndSend(this, packet, cb)
832
- break
833
- /**
834
- * no need of case here since it will be caught by default
835
- * and jshint comply that before default it must be a break
836
- * anyway it will result in -1 evaluation
837
- */
838
- case 0:
839
- /* falls through */
840
- default:
841
- sendPacket(this, packet, cb)
842
- break
843
- }
844
- }
845
-
846
- /**
847
- * _setupPingTimer - setup the ping timer
848
- *
849
- * @api private
850
- */
851
- MqttClient.prototype._setupPingTimer = function () {
852
- var that = this
853
-
854
- if (!this.pingTimer && this.options.keepalive) {
855
- this.pingResp = true
856
- this.pingTimer = reInterval(function () {
857
- that._checkPing()
858
- }, this.options.keepalive * 1000)
859
- }
860
- }
861
-
862
- /**
863
- * _shiftPingInterval - reschedule the ping interval
864
- *
865
- * @api private
866
- */
867
- MqttClient.prototype._shiftPingInterval = function () {
868
- if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
869
- this.pingTimer.reschedule(this.options.keepalive * 1000)
870
- }
871
- }
872
- /**
873
- * _checkPing - check if a pingresp has come back, and ping the server again
874
- *
875
- * @api private
876
- */
877
- MqttClient.prototype._checkPing = function () {
878
- if (this.pingResp) {
879
- this.pingResp = false
880
- this._sendPacket({ cmd: 'pingreq' })
881
- } else {
882
- // do a forced cleanup since socket will be in bad shape
883
- this._cleanUp(true)
884
- }
885
- }
886
-
887
- /**
888
- * _handlePingresp - handle a pingresp
889
- *
890
- * @api private
891
- */
892
- MqttClient.prototype._handlePingresp = function () {
893
- this.pingResp = true
894
- }
895
-
896
- /**
897
- * _handleConnack
898
- *
899
- * @param {Object} packet
900
- * @api private
901
- */
902
-
903
- MqttClient.prototype._handleConnack = function (packet) {
904
- var rc = packet.returnCode
905
- var errors = [
906
- '',
907
- 'Unacceptable protocol version',
908
- 'Identifier rejected',
909
- 'Server unavailable',
910
- 'Bad username or password',
911
- 'Not authorized'
912
- ]
913
-
914
- clearTimeout(this.connackTimer)
915
-
916
- if (rc === 0) {
917
- this.reconnecting = false
918
- this.emit('connect', packet)
919
- } else if (rc > 0) {
920
- var err = new Error('Connection refused: ' + errors[rc])
921
- err.code = rc
922
- this.emit('error', err)
923
- }
924
- }
925
-
926
- /**
927
- * _handlePublish
928
- *
929
- * @param {Object} packet
930
- * @api private
931
- */
932
- /*
933
- those late 2 case should be rewrite to comply with coding style:
934
-
935
- case 1:
936
- case 0:
937
- // do not wait sending a puback
938
- // no callback passed
939
- if (1 === qos) {
940
- this._sendPacket({
941
- cmd: 'puback',
942
- messageId: mid
943
- });
944
- }
945
- // emit the message event for both qos 1 and 0
946
- this.emit('message', topic, message, packet);
947
- this.handleMessage(packet, done);
948
- break;
949
- default:
950
- // do nothing but every switch mus have a default
951
- // log or throw an error about unknown qos
952
- break;
953
-
954
- for now i just suppressed the warnings
955
- */
956
- MqttClient.prototype._handlePublish = function (packet, done) {
957
- done = typeof done !== 'undefined' ? done : nop
958
- var topic = packet.topic.toString()
959
- var message = packet.payload
960
- var qos = packet.qos
961
- var mid = packet.messageId
962
- var that = this
963
-
964
- switch (qos) {
965
- case 2:
966
- this.incomingStore.put(packet, function (err) {
967
- if (err) {
968
- return done(err)
969
- }
970
- that._sendPacket({cmd: 'pubrec', messageId: mid}, done)
971
- })
972
- break
973
- case 1:
974
- // emit the message event
975
- this.emit('message', topic, message, packet)
976
- this.handleMessage(packet, function (err) {
977
- if (err) {
978
- return done(err)
979
- }
980
- // send 'puback' if the above 'handleMessage' method executed
981
- // successfully.
982
- that._sendPacket({cmd: 'puback', messageId: mid}, done)
983
- })
984
- break
985
- case 0:
986
- // emit the message event
987
- this.emit('message', topic, message, packet)
988
- this.handleMessage(packet, done)
989
- break
990
- default:
991
- // do nothing
992
- // log or throw an error about unknown qos
993
- break
994
- }
995
- }
996
-
997
- /**
998
- * Handle messages with backpressure support, one at a time.
999
- * Override at will.
1000
- *
1001
- * @param Packet packet the packet
1002
- * @param Function callback call when finished
1003
- * @api public
1004
- */
1005
- MqttClient.prototype.handleMessage = function (packet, callback) {
1006
- callback()
1007
- }
1008
-
1009
- /**
1010
- * _handleAck
1011
- *
1012
- * @param {Object} packet
1013
- * @api private
1014
- */
1015
-
1016
- MqttClient.prototype._handleAck = function (packet) {
1017
- /* eslint no-fallthrough: "off" */
1018
- var mid = packet.messageId
1019
- var type = packet.cmd
1020
- var response = null
1021
- var cb = this.outgoing[mid]
1022
- var that = this
1023
-
1024
- if (!cb) {
1025
- // Server sent an ack in error, ignore it.
1026
- return
1027
- }
1028
-
1029
- // Process
1030
- switch (type) {
1031
- case 'pubcomp':
1032
- // same thing as puback for QoS 2
1033
- case 'puback':
1034
- // Callback - we're done
1035
- delete this.outgoing[mid]
1036
- this.outgoingStore.del(packet, cb)
1037
- break
1038
- case 'pubrec':
1039
- response = {
1040
- cmd: 'pubrel',
1041
- qos: 2,
1042
- messageId: mid
1043
- }
1044
-
1045
- this._sendPacket(response)
1046
- break
1047
- case 'suback':
1048
- delete this.outgoing[mid]
1049
- if (packet.granted.length === 1 && (packet.granted[0] & 0x80) !== 0) {
1050
- // suback with Failure status
1051
- var topics = this.messageIdToTopic[mid]
1052
- if (topics) {
1053
- topics.forEach(function (topic) {
1054
- delete that._resubscribeTopics[topic]
1055
- })
1056
- }
1057
- }
1058
- cb(null, packet)
1059
- break
1060
- case 'unsuback':
1061
- delete this.outgoing[mid]
1062
- cb(null)
1063
- break
1064
- default:
1065
- that.emit('error', new Error('unrecognized packet type'))
1066
- }
1067
-
1068
- if (this.disconnecting &&
1069
- Object.keys(this.outgoing).length === 0) {
1070
- this.emit('outgoingEmpty')
1071
- }
1072
- }
1073
-
1074
- /**
1075
- * _handlePubrel
1076
- *
1077
- * @param {Object} packet
1078
- * @api private
1079
- */
1080
- MqttClient.prototype._handlePubrel = function (packet, callback) {
1081
- callback = typeof callback !== 'undefined' ? callback : nop
1082
- var mid = packet.messageId
1083
- var that = this
1084
-
1085
- var comp = {cmd: 'pubcomp', messageId: mid}
1086
-
1087
- that.incomingStore.get(packet, function (err, pub) {
1088
- if (!err && pub.cmd !== 'pubrel') {
1089
- that.emit('message', pub.topic, pub.payload, pub)
1090
- that.incomingStore.put(packet, function (err) {
1091
- if (err) {
1092
- return callback(err)
1093
- }
1094
- that.handleMessage(pub, function (err) {
1095
- if (err) {
1096
- return callback(err)
1097
- }
1098
- that._sendPacket(comp, callback)
1099
- })
1100
- })
1101
- } else {
1102
- that._sendPacket(comp, callback)
1103
- }
1104
- })
1105
- }
1106
-
1107
- /**
1108
- * _nextId
1109
- * @return unsigned int
1110
- */
1111
- MqttClient.prototype._nextId = function () {
1112
- // id becomes current state of this.nextId and increments afterwards
1113
- var id = this.nextId++
1114
- // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
1115
- if (this.nextId === 65536) {
1116
- this.nextId = 1
1117
- }
1118
- return id
1119
- }
1120
-
1121
- /**
1122
- * getLastMessageId
1123
- * @return unsigned int
1124
- */
1125
- MqttClient.prototype.getLastMessageId = function () {
1126
- return (this.nextId === 1) ? 65535 : (this.nextId - 1)
1127
- }
1128
-
1129
- module.exports = MqttClient
1
+ 'use strict'
2
+
3
+ /**
4
+ * Module dependencies
5
+ */
6
+ var events = require('events')
7
+ var Store = require('./store')
8
+ var eos = require('end-of-stream')
9
+ var mqttPacket = require('mqtt-packet')
10
+ var Writable = require('readable-stream').Writable
11
+ var inherits = require('inherits')
12
+ var reInterval = require('reinterval')
13
+ var validations = require('./validations')
14
+ var xtend = require('xtend')
15
+ var setImmediate = global.setImmediate || function (callback) {
16
+ // works in node v0.8
17
+ process.nextTick(callback)
18
+ }
19
+ var defaultConnectOptions = {
20
+ keepalive: 60,
21
+ reschedulePings: true,
22
+ protocolId: 'MQTT',
23
+ protocolVersion: 4,
24
+ reconnectPeriod: 1000,
25
+ connectTimeout: 30 * 1000,
26
+ clean: true,
27
+ resubscribe: true
28
+ }
29
+
30
+ function defaultId () {
31
+ return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
32
+ }
33
+
34
+ function sendPacket (client, packet, cb) {
35
+ client.emit('packetsend', packet)
36
+
37
+ var result = mqttPacket.writeToStream(packet, client.stream)
38
+
39
+ if (!result && cb) {
40
+ client.stream.once('drain', cb)
41
+ } else if (cb) {
42
+ cb()
43
+ }
44
+ }
45
+
46
+ function flush (queue) {
47
+ if (queue) {
48
+ Object.keys(queue).forEach(function (messageId) {
49
+ if (typeof queue[messageId] === 'function') {
50
+ queue[messageId](new Error('Connection closed'))
51
+ delete queue[messageId]
52
+ }
53
+ })
54
+ }
55
+ }
56
+
57
+ function storeAndSend (client, packet, cb) {
58
+ client.outgoingStore.put(packet, function storedPacket (err) {
59
+ if (err) {
60
+ return cb && cb(err)
61
+ }
62
+ sendPacket(client, packet, cb)
63
+ })
64
+ }
65
+
66
+ function nop () {}
67
+
68
+ /**
69
+ * MqttClient constructor
70
+ *
71
+ * @param {Stream} stream - stream
72
+ * @param {Object} [options] - connection options
73
+ * (see Connection#connect)
74
+ */
75
+ function MqttClient (streamBuilder, options) {
76
+ var k
77
+ var that = this
78
+
79
+ if (!(this instanceof MqttClient)) {
80
+ return new MqttClient(streamBuilder, options)
81
+ }
82
+
83
+ this.options = options || {}
84
+
85
+ // Defaults
86
+ for (k in defaultConnectOptions) {
87
+ if (typeof this.options[k] === 'undefined') {
88
+ this.options[k] = defaultConnectOptions[k]
89
+ } else {
90
+ this.options[k] = options[k]
91
+ }
92
+ }
93
+
94
+ this.options.clientId = (typeof this.options.clientId === 'string') ? this.options.clientId : defaultId()
95
+
96
+ this.streamBuilder = streamBuilder
97
+
98
+ // Inflight message storages
99
+ this.outgoingStore = this.options.outgoingStore || new Store()
100
+ this.incomingStore = this.options.incomingStore || new Store()
101
+
102
+ // Should QoS zero messages be queued when the connection is broken?
103
+ this.queueQoSZero = this.options.queueQoSZero === undefined ? true : this.options.queueQoSZero
104
+
105
+ // map of subscribed topics to support reconnection
106
+ this._resubscribeTopics = {}
107
+
108
+ // map of a subscribe messageId and a topic
109
+ this.messageIdToTopic = {}
110
+
111
+ // Ping timer, setup in _setupPingTimer
112
+ this.pingTimer = null
113
+ // Is the client connected?
114
+ this.connected = false
115
+ // Are we disconnecting?
116
+ this.disconnecting = false
117
+ // Packet queue
118
+ this.queue = []
119
+ // connack timer
120
+ this.connackTimer = null
121
+ // Reconnect timer
122
+ this.reconnectTimer = null
123
+ /**
124
+ * MessageIDs starting with 1
125
+ * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
126
+ */
127
+ this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
128
+
129
+ // Inflight callbacks
130
+ this.outgoing = {}
131
+
132
+ // Mark connected on connect
133
+ this.on('connect', function () {
134
+ if (this.disconnected) {
135
+ return
136
+ }
137
+
138
+ this.connected = true
139
+ var outStore = this.outgoingStore.createStream()
140
+
141
+ this.once('close', remove)
142
+ outStore.on('end', function () {
143
+ that.removeListener('close', remove)
144
+ })
145
+ outStore.on('error', function (err) {
146
+ that.removeListener('close', remove)
147
+ that.emit('error', err)
148
+ })
149
+
150
+ function remove () {
151
+ outStore.destroy()
152
+ outStore = null
153
+ }
154
+
155
+ function storeDeliver () {
156
+ // edge case, we wrapped this twice
157
+ if (!outStore) {
158
+ return
159
+ }
160
+
161
+ var packet = outStore.read(1)
162
+ var cb
163
+
164
+ if (!packet) {
165
+ // read when data is available in the future
166
+ outStore.once('readable', storeDeliver)
167
+ return
168
+ }
169
+
170
+ // Avoid unnecessary stream read operations when disconnected
171
+ if (!that.disconnecting && !that.reconnectTimer) {
172
+ cb = that.outgoing[packet.messageId]
173
+ that.outgoing[packet.messageId] = function (err, status) {
174
+ // Ensure that the original callback passed in to publish gets invoked
175
+ if (cb) {
176
+ cb(err, status)
177
+ }
178
+
179
+ storeDeliver()
180
+ }
181
+ that._sendPacket(packet)
182
+ } else if (outStore.destroy) {
183
+ outStore.destroy()
184
+ }
185
+ }
186
+
187
+ // start flowing
188
+ storeDeliver()
189
+ })
190
+
191
+ // Mark disconnected on stream close
192
+ this.on('close', function () {
193
+ this.connected = false
194
+ clearTimeout(this.connackTimer)
195
+ })
196
+
197
+ // Setup ping timer
198
+ this.on('connect', this._setupPingTimer)
199
+
200
+ // Send queued packets
201
+ this.on('connect', function () {
202
+ var queue = this.queue
203
+
204
+ function deliver () {
205
+ var entry = queue.shift()
206
+ var packet = null
207
+
208
+ if (!entry) {
209
+ return
210
+ }
211
+
212
+ packet = entry.packet
213
+
214
+ that._sendPacket(
215
+ packet,
216
+ function (err) {
217
+ if (entry.cb) {
218
+ entry.cb(err)
219
+ }
220
+ deliver()
221
+ }
222
+ )
223
+ }
224
+
225
+ deliver()
226
+ })
227
+
228
+ var firstConnection = true
229
+ // resubscribe
230
+ this.on('connect', function () {
231
+ if (!firstConnection &&
232
+ this.options.clean &&
233
+ Object.keys(this._resubscribeTopics).length > 0) {
234
+ if (this.options.resubscribe) {
235
+ this._resubscribeTopics.resubscribe = true
236
+ this.subscribe(this._resubscribeTopics)
237
+ } else {
238
+ this._resubscribeTopics = {}
239
+ }
240
+ }
241
+
242
+ firstConnection = false
243
+ })
244
+
245
+ // Clear ping timer
246
+ this.on('close', function () {
247
+ if (that.pingTimer !== null) {
248
+ that.pingTimer.clear()
249
+ that.pingTimer = null
250
+ }
251
+ })
252
+
253
+ // Setup reconnect timer on disconnect
254
+ this.on('close', this._setupReconnect)
255
+
256
+ events.EventEmitter.call(this)
257
+
258
+ this._setupStream()
259
+ }
260
+ inherits(MqttClient, events.EventEmitter)
261
+
262
+ /**
263
+ * setup the event handlers in the inner stream.
264
+ *
265
+ * @api private
266
+ */
267
+ MqttClient.prototype._setupStream = function () {
268
+ var connectPacket
269
+ var that = this
270
+ var writable = new Writable()
271
+ var parser = mqttPacket.parser(this.options)
272
+ var completeParse = null
273
+ var packets = []
274
+
275
+ this._clearReconnect()
276
+
277
+ this.stream = this.streamBuilder(this)
278
+
279
+ parser.on('packet', function (packet) {
280
+ packets.push(packet)
281
+ })
282
+
283
+ function nextTickWork () {
284
+ process.nextTick(work)
285
+ }
286
+
287
+ function work () {
288
+ var packet = packets.shift()
289
+ var done = completeParse
290
+
291
+ if (packet) {
292
+ that._handlePacket(packet, nextTickWork)
293
+ } else {
294
+ completeParse = null
295
+ done()
296
+ }
297
+ }
298
+
299
+ writable._write = function (buf, enc, done) {
300
+ completeParse = done
301
+ parser.parse(buf)
302
+ work()
303
+ }
304
+
305
+ this.stream.pipe(writable)
306
+
307
+ // Suppress connection errors
308
+ this.stream.on('error', nop)
309
+
310
+ // Echo stream close
311
+ eos(this.stream, this.emit.bind(this, 'close'))
312
+
313
+ // Send a connect packet
314
+ connectPacket = Object.create(this.options)
315
+ connectPacket.cmd = 'connect'
316
+ // avoid message queue
317
+ sendPacket(this, connectPacket)
318
+
319
+ // Echo connection errors
320
+ parser.on('error', this.emit.bind(this, 'error'))
321
+
322
+ // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
323
+ this.stream.setMaxListeners(1000)
324
+
325
+ clearTimeout(this.connackTimer)
326
+ this.connackTimer = setTimeout(function () {
327
+ that._cleanUp(true)
328
+ }, this.options.connectTimeout)
329
+ }
330
+
331
+ MqttClient.prototype._handlePacket = function (packet, done) {
332
+ this.emit('packetreceive', packet)
333
+
334
+ switch (packet.cmd) {
335
+ case 'publish':
336
+ this._handlePublish(packet, done)
337
+ break
338
+ case 'puback':
339
+ case 'pubrec':
340
+ case 'pubcomp':
341
+ case 'suback':
342
+ case 'unsuback':
343
+ this._handleAck(packet)
344
+ done()
345
+ break
346
+ case 'pubrel':
347
+ this._handlePubrel(packet, done)
348
+ break
349
+ case 'connack':
350
+ this._handleConnack(packet)
351
+ done()
352
+ break
353
+ case 'pingresp':
354
+ this._handlePingresp(packet)
355
+ done()
356
+ break
357
+ default:
358
+ // do nothing
359
+ // maybe we should do an error handling
360
+ // or just log it
361
+ break
362
+ }
363
+ }
364
+
365
+ MqttClient.prototype._checkDisconnecting = function (callback) {
366
+ if (this.disconnecting) {
367
+ if (callback) {
368
+ callback(new Error('client disconnecting'))
369
+ } else {
370
+ this.emit('error', new Error('client disconnecting'))
371
+ }
372
+ }
373
+ return this.disconnecting
374
+ }
375
+
376
+ /**
377
+ * publish - publish <message> to <topic>
378
+ *
379
+ * @param {String} topic - topic to publish to
380
+ * @param {String, Buffer} message - message to publish
381
+ * @param {Object} [opts] - publish options, includes:
382
+ * {Number} qos - qos level to publish on
383
+ * {Boolean} retain - whether or not to retain the message
384
+ * {Boolean} dup - whether or not mark a message as duplicate
385
+ * @param {Function} [callback] - function(err){}
386
+ * called when publish succeeds or fails
387
+ * @returns {MqttClient} this - for chaining
388
+ * @api public
389
+ *
390
+ * @example client.publish('topic', 'message');
391
+ * @example
392
+ * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
393
+ * @example client.publish('topic', 'message', console.log);
394
+ */
395
+ MqttClient.prototype.publish = function (topic, message, opts, callback) {
396
+ var packet
397
+
398
+ // .publish(topic, payload, cb);
399
+ if (typeof opts === 'function') {
400
+ callback = opts
401
+ opts = null
402
+ }
403
+
404
+ // default opts
405
+ var defaultOpts = {qos: 0, retain: false, dup: false}
406
+ opts = xtend(defaultOpts, opts)
407
+
408
+ if (this._checkDisconnecting(callback)) {
409
+ return this
410
+ }
411
+
412
+ packet = {
413
+ cmd: 'publish',
414
+ topic: topic,
415
+ payload: message,
416
+ qos: opts.qos,
417
+ retain: opts.retain,
418
+ messageId: this._nextId(),
419
+ dup: opts.dup
420
+ }
421
+
422
+ switch (opts.qos) {
423
+ case 1:
424
+ case 2:
425
+
426
+ // Add to callbacks
427
+ this.outgoing[packet.messageId] = callback || nop
428
+ this._sendPacket(packet)
429
+ break
430
+ default:
431
+ this._sendPacket(packet, callback)
432
+ break
433
+ }
434
+
435
+ return this
436
+ }
437
+
438
+ /**
439
+ * subscribe - subscribe to <topic>
440
+ *
441
+ * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
442
+ * @param {Object} [opts] - optional subscription options, includes:
443
+ * {Number} qos - subscribe qos level
444
+ * @param {Function} [callback] - function(err, granted){} where:
445
+ * {Error} err - subscription error (none at the moment!)
446
+ * {Array} granted - array of {topic: 't', qos: 0}
447
+ * @returns {MqttClient} this - for chaining
448
+ * @api public
449
+ * @example client.subscribe('topic');
450
+ * @example client.subscribe('topic', {qos: 1});
451
+ * @example client.subscribe({'topic': 0, 'topic2': 1}, console.log);
452
+ * @example client.subscribe('topic', console.log);
453
+ */
454
+ MqttClient.prototype.subscribe = function () {
455
+ var packet
456
+ var args = Array.prototype.slice.call(arguments)
457
+ var subs = []
458
+ var obj = args.shift()
459
+ var resubscribe = obj.resubscribe
460
+ var callback = args.pop() || nop
461
+ var opts = args.pop()
462
+ var invalidTopic
463
+ var that = this
464
+
465
+ delete obj.resubscribe
466
+
467
+ if (typeof obj === 'string') {
468
+ obj = [obj]
469
+ }
470
+
471
+ if (typeof callback !== 'function') {
472
+ opts = callback
473
+ callback = nop
474
+ }
475
+
476
+ invalidTopic = validations.validateTopics(obj)
477
+ if (invalidTopic !== null) {
478
+ setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
479
+ return this
480
+ }
481
+
482
+ if (this._checkDisconnecting(callback)) {
483
+ return this
484
+ }
485
+
486
+ var defaultOpts = { qos: 0 }
487
+ opts = xtend(defaultOpts, opts)
488
+
489
+ if (Array.isArray(obj)) {
490
+ obj.forEach(function (topic) {
491
+ if (that._resubscribeTopics[topic] < opts.qos ||
492
+ !that._resubscribeTopics.hasOwnProperty(topic) ||
493
+ resubscribe) {
494
+ subs.push({
495
+ topic: topic,
496
+ qos: opts.qos
497
+ })
498
+ }
499
+ })
500
+ } else {
501
+ Object
502
+ .keys(obj)
503
+ .forEach(function (k) {
504
+ if (that._resubscribeTopics[k] < obj[k] ||
505
+ !that._resubscribeTopics.hasOwnProperty(k) ||
506
+ resubscribe) {
507
+ subs.push({
508
+ topic: k,
509
+ qos: obj[k]
510
+ })
511
+ }
512
+ })
513
+ }
514
+
515
+ packet = {
516
+ cmd: 'subscribe',
517
+ subscriptions: subs,
518
+ qos: 1,
519
+ retain: false,
520
+ dup: false,
521
+ messageId: this._nextId()
522
+ }
523
+
524
+ if (!subs.length) {
525
+ callback(null, [])
526
+ return
527
+ }
528
+
529
+ // subscriptions to resubscribe to in case of disconnect
530
+ if (this.options.resubscribe) {
531
+ var topics = []
532
+ subs.forEach(function (sub) {
533
+ if (that.options.reconnectPeriod > 0) {
534
+ that._resubscribeTopics[sub.topic] = sub.qos
535
+ topics.push(sub.topic)
536
+ }
537
+ })
538
+ that.messageIdToTopic[packet.messageId] = topics
539
+ }
540
+
541
+ this.outgoing[packet.messageId] = function (err, packet) {
542
+ if (!err) {
543
+ var granted = packet.granted
544
+ for (var i = 0; i < granted.length; i += 1) {
545
+ subs[i].qos = granted[i]
546
+ }
547
+ }
548
+
549
+ callback(err, subs)
550
+ }
551
+
552
+ this._sendPacket(packet)
553
+
554
+ return this
555
+ }
556
+
557
+ /**
558
+ * unsubscribe - unsubscribe from topic(s)
559
+ *
560
+ * @param {String, Array} topic - topics to unsubscribe from
561
+ * @param {Function} [callback] - callback fired on unsuback
562
+ * @returns {MqttClient} this - for chaining
563
+ * @api public
564
+ * @example client.unsubscribe('topic');
565
+ * @example client.unsubscribe('topic', console.log);
566
+ */
567
+ MqttClient.prototype.unsubscribe = function (topic, callback) {
568
+ var packet = {
569
+ cmd: 'unsubscribe',
570
+ qos: 1,
571
+ messageId: this._nextId()
572
+ }
573
+ var that = this
574
+
575
+ callback = callback || nop
576
+
577
+ if (this._checkDisconnecting(callback)) {
578
+ return this
579
+ }
580
+
581
+ if (typeof topic === 'string') {
582
+ packet.unsubscriptions = [topic]
583
+ } else if (typeof topic === 'object' && topic.length) {
584
+ packet.unsubscriptions = topic
585
+ }
586
+
587
+ if (this.options.resubscribe) {
588
+ packet.unsubscriptions.forEach(function (topic) {
589
+ delete that._resubscribeTopics[topic]
590
+ })
591
+ }
592
+
593
+ this.outgoing[packet.messageId] = callback
594
+
595
+ this._sendPacket(packet)
596
+
597
+ return this
598
+ }
599
+
600
+ /**
601
+ * end - close connection
602
+ *
603
+ * @returns {MqttClient} this - for chaining
604
+ * @param {Boolean} force - do not wait for all in-flight messages to be acked
605
+ * @param {Function} cb - called when the client has been closed
606
+ *
607
+ * @api public
608
+ */
609
+ MqttClient.prototype.end = function (force, cb) {
610
+ var that = this
611
+
612
+ if (typeof force === 'function') {
613
+ cb = force
614
+ force = false
615
+ }
616
+
617
+ function closeStores () {
618
+ that.disconnected = true
619
+ that.incomingStore.close(function () {
620
+ that.outgoingStore.close(function () {
621
+ if (cb) {
622
+ cb.apply(null, arguments)
623
+ }
624
+ that.emit('end')
625
+ })
626
+ })
627
+ if (that._deferredReconnect) {
628
+ that._deferredReconnect()
629
+ }
630
+ }
631
+
632
+ function finish () {
633
+ // defer closesStores of an I/O cycle,
634
+ // just to make sure things are
635
+ // ok for websockets
636
+ that._cleanUp(force, setImmediate.bind(null, closeStores))
637
+ }
638
+
639
+ if (this.disconnecting) {
640
+ return this
641
+ }
642
+
643
+ this._clearReconnect()
644
+
645
+ this.disconnecting = true
646
+
647
+ if (!force && Object.keys(this.outgoing).length > 0) {
648
+ // wait 10ms, just to be sure we received all of it
649
+ this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
650
+ } else {
651
+ finish()
652
+ }
653
+
654
+ return this
655
+ }
656
+
657
+ /**
658
+ * removeOutgoingMessage - remove a message in outgoing store
659
+ * the outgoing callback will be called withe Error('Message removed') if the message is removed
660
+ *
661
+ * @param {Number} mid - messageId to remove message
662
+ * @returns {MqttClient} this - for chaining
663
+ * @api public
664
+ *
665
+ * @example client.removeOutgoingMessage(client.getLastMessageId());
666
+ */
667
+ MqttClient.prototype.removeOutgoingMessage = function (mid) {
668
+ var cb = this.outgoing[mid]
669
+ delete this.outgoing[mid]
670
+ this.outgoingStore.del({messageId: mid}, function () {
671
+ cb(new Error('Message removed'))
672
+ })
673
+ return this
674
+ }
675
+
676
+ /**
677
+ * reconnect - connect again using the same options as connect()
678
+ *
679
+ * @param {Object} [opts] - optional reconnect options, includes:
680
+ * {Store} incomingStore - a store for the incoming packets
681
+ * {Store} outgoingStore - a store for the outgoing packets
682
+ * if opts is not given, current stores are used
683
+ * @returns {MqttClient} this - for chaining
684
+ *
685
+ * @api public
686
+ */
687
+ MqttClient.prototype.reconnect = function (opts) {
688
+ var that = this
689
+ var f = function () {
690
+ if (opts) {
691
+ that.options.incomingStore = opts.incomingStore
692
+ that.options.outgoingStore = opts.outgoingStore
693
+ } else {
694
+ that.options.incomingStore = null
695
+ that.options.outgoingStore = null
696
+ }
697
+ that.incomingStore = that.options.incomingStore || new Store()
698
+ that.outgoingStore = that.options.outgoingStore || new Store()
699
+ that.disconnecting = false
700
+ that.disconnected = false
701
+ that._deferredReconnect = null
702
+ that._reconnect()
703
+ }
704
+
705
+ if (this.disconnecting && !this.disconnected) {
706
+ this._deferredReconnect = f
707
+ } else {
708
+ f()
709
+ }
710
+ return this
711
+ }
712
+
713
+ /**
714
+ * _reconnect - implement reconnection
715
+ * @api privateish
716
+ */
717
+ MqttClient.prototype._reconnect = function () {
718
+ this.emit('reconnect')
719
+ this._setupStream()
720
+ }
721
+
722
+ /**
723
+ * _setupReconnect - setup reconnect timer
724
+ */
725
+ MqttClient.prototype._setupReconnect = function () {
726
+ var that = this
727
+
728
+ if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
729
+ if (!this.reconnecting) {
730
+ this.emit('offline')
731
+ this.reconnecting = true
732
+ }
733
+ that.reconnectTimer = setInterval(function () {
734
+ that._reconnect()
735
+ }, that.options.reconnectPeriod)
736
+ }
737
+ }
738
+
739
+ /**
740
+ * _clearReconnect - clear the reconnect timer
741
+ */
742
+ MqttClient.prototype._clearReconnect = function () {
743
+ if (this.reconnectTimer) {
744
+ clearInterval(this.reconnectTimer)
745
+ this.reconnectTimer = null
746
+ }
747
+ }
748
+
749
+ /**
750
+ * _cleanUp - clean up on connection end
751
+ * @api private
752
+ */
753
+ MqttClient.prototype._cleanUp = function (forced, done) {
754
+ if (done) {
755
+ this.stream.on('close', done)
756
+ }
757
+
758
+ if (forced) {
759
+ if ((this.options.reconnectPeriod === 0) && this.options.clean) {
760
+ flush(this.outgoing)
761
+ }
762
+ this.stream.destroy()
763
+ } else {
764
+ this._sendPacket(
765
+ { cmd: 'disconnect' },
766
+ setImmediate.bind(
767
+ null,
768
+ this.stream.end.bind(this.stream)
769
+ )
770
+ )
771
+ }
772
+
773
+ if (!this.disconnecting) {
774
+ this._clearReconnect()
775
+ this._setupReconnect()
776
+ }
777
+
778
+ if (this.pingTimer !== null) {
779
+ this.pingTimer.clear()
780
+ this.pingTimer = null
781
+ }
782
+
783
+ if (done && !this.connected) {
784
+ this.stream.removeListener('close', done)
785
+ done()
786
+ }
787
+ }
788
+
789
+ /**
790
+ * _sendPacket - send or queue a packet
791
+ * @param {String} type - packet type (see `protocol`)
792
+ * @param {Object} packet - packet options
793
+ * @param {Function} cb - callback when the packet is sent
794
+ * @api private
795
+ */
796
+ MqttClient.prototype._sendPacket = function (packet, cb) {
797
+ if (!this.connected) {
798
+ if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
799
+ this.queue.push({ packet: packet, cb: cb })
800
+ } else if (packet.qos > 0) {
801
+ cb = this.outgoing[packet.messageId]
802
+ this.outgoingStore.put(packet, function (err) {
803
+ if (err) {
804
+ return cb && cb(err)
805
+ }
806
+ })
807
+ } else if (cb) {
808
+ cb(new Error('No connection to broker'))
809
+ }
810
+
811
+ return
812
+ }
813
+
814
+ // When sending a packet, reschedule the ping timer
815
+ this._shiftPingInterval()
816
+
817
+ switch (packet.cmd) {
818
+ case 'publish':
819
+ break
820
+ case 'pubrel':
821
+ storeAndSend(this, packet, cb)
822
+ return
823
+ default:
824
+ sendPacket(this, packet, cb)
825
+ return
826
+ }
827
+
828
+ switch (packet.qos) {
829
+ case 2:
830
+ case 1:
831
+ storeAndSend(this, packet, cb)
832
+ break
833
+ /**
834
+ * no need of case here since it will be caught by default
835
+ * and jshint comply that before default it must be a break
836
+ * anyway it will result in -1 evaluation
837
+ */
838
+ case 0:
839
+ /* falls through */
840
+ default:
841
+ sendPacket(this, packet, cb)
842
+ break
843
+ }
844
+ }
845
+
846
+ /**
847
+ * _setupPingTimer - setup the ping timer
848
+ *
849
+ * @api private
850
+ */
851
+ MqttClient.prototype._setupPingTimer = function () {
852
+ var that = this
853
+
854
+ if (!this.pingTimer && this.options.keepalive) {
855
+ this.pingResp = true
856
+ this.pingTimer = reInterval(function () {
857
+ that._checkPing()
858
+ }, this.options.keepalive * 1000)
859
+ }
860
+ }
861
+
862
+ /**
863
+ * _shiftPingInterval - reschedule the ping interval
864
+ *
865
+ * @api private
866
+ */
867
+ MqttClient.prototype._shiftPingInterval = function () {
868
+ if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
869
+ this.pingTimer.reschedule(this.options.keepalive * 1000)
870
+ }
871
+ }
872
+ /**
873
+ * _checkPing - check if a pingresp has come back, and ping the server again
874
+ *
875
+ * @api private
876
+ */
877
+ MqttClient.prototype._checkPing = function () {
878
+ if (this.pingResp) {
879
+ this.pingResp = false
880
+ this._sendPacket({ cmd: 'pingreq' })
881
+ } else {
882
+ // do a forced cleanup since socket will be in bad shape
883
+ this._cleanUp(true)
884
+ }
885
+ }
886
+
887
+ /**
888
+ * _handlePingresp - handle a pingresp
889
+ *
890
+ * @api private
891
+ */
892
+ MqttClient.prototype._handlePingresp = function () {
893
+ this.pingResp = true
894
+ }
895
+
896
+ /**
897
+ * _handleConnack
898
+ *
899
+ * @param {Object} packet
900
+ * @api private
901
+ */
902
+
903
+ MqttClient.prototype._handleConnack = function (packet) {
904
+ var rc = packet.returnCode
905
+ var errors = [
906
+ '',
907
+ 'Unacceptable protocol version',
908
+ 'Identifier rejected',
909
+ 'Server unavailable',
910
+ 'Bad username or password',
911
+ 'Not authorized'
912
+ ]
913
+
914
+ clearTimeout(this.connackTimer)
915
+
916
+ if (rc === 0) {
917
+ this.reconnecting = false
918
+ this.emit('connect', packet)
919
+ } else if (rc > 0) {
920
+ var err = new Error('Connection refused: ' + errors[rc])
921
+ err.code = rc
922
+ this.emit('error', err)
923
+ }
924
+ }
925
+
926
+ /**
927
+ * _handlePublish
928
+ *
929
+ * @param {Object} packet
930
+ * @api private
931
+ */
932
+ /*
933
+ those late 2 case should be rewrite to comply with coding style:
934
+
935
+ case 1:
936
+ case 0:
937
+ // do not wait sending a puback
938
+ // no callback passed
939
+ if (1 === qos) {
940
+ this._sendPacket({
941
+ cmd: 'puback',
942
+ messageId: mid
943
+ });
944
+ }
945
+ // emit the message event for both qos 1 and 0
946
+ this.emit('message', topic, message, packet);
947
+ this.handleMessage(packet, done);
948
+ break;
949
+ default:
950
+ // do nothing but every switch mus have a default
951
+ // log or throw an error about unknown qos
952
+ break;
953
+
954
+ for now i just suppressed the warnings
955
+ */
956
+ MqttClient.prototype._handlePublish = function (packet, done) {
957
+ done = typeof done !== 'undefined' ? done : nop
958
+ var topic = packet.topic.toString()
959
+ var message = packet.payload
960
+ var qos = packet.qos
961
+ var mid = packet.messageId
962
+ var that = this
963
+
964
+ switch (qos) {
965
+ case 2:
966
+ this.incomingStore.put(packet, function (err) {
967
+ if (err) {
968
+ return done(err)
969
+ }
970
+ that._sendPacket({cmd: 'pubrec', messageId: mid}, done)
971
+ })
972
+ break
973
+ case 1:
974
+ // emit the message event
975
+ this.emit('message', topic, message, packet)
976
+ this.handleMessage(packet, function (err) {
977
+ if (err) {
978
+ return done(err)
979
+ }
980
+ // send 'puback' if the above 'handleMessage' method executed
981
+ // successfully.
982
+ that._sendPacket({cmd: 'puback', messageId: mid}, done)
983
+ })
984
+ break
985
+ case 0:
986
+ // emit the message event
987
+ this.emit('message', topic, message, packet)
988
+ this.handleMessage(packet, done)
989
+ break
990
+ default:
991
+ // do nothing
992
+ // log or throw an error about unknown qos
993
+ break
994
+ }
995
+ }
996
+
997
+ /**
998
+ * Handle messages with backpressure support, one at a time.
999
+ * Override at will.
1000
+ *
1001
+ * @param Packet packet the packet
1002
+ * @param Function callback call when finished
1003
+ * @api public
1004
+ */
1005
+ MqttClient.prototype.handleMessage = function (packet, callback) {
1006
+ callback()
1007
+ }
1008
+
1009
+ /**
1010
+ * _handleAck
1011
+ *
1012
+ * @param {Object} packet
1013
+ * @api private
1014
+ */
1015
+
1016
+ MqttClient.prototype._handleAck = function (packet) {
1017
+ /* eslint no-fallthrough: "off" */
1018
+ var mid = packet.messageId
1019
+ var type = packet.cmd
1020
+ var response = null
1021
+ var cb = this.outgoing[mid]
1022
+ var that = this
1023
+
1024
+ if (!cb) {
1025
+ // Server sent an ack in error, ignore it.
1026
+ return
1027
+ }
1028
+
1029
+ // Process
1030
+ switch (type) {
1031
+ case 'pubcomp':
1032
+ // same thing as puback for QoS 2
1033
+ case 'puback':
1034
+ // Callback - we're done
1035
+ delete this.outgoing[mid]
1036
+ this.outgoingStore.del(packet, cb)
1037
+ break
1038
+ case 'pubrec':
1039
+ response = {
1040
+ cmd: 'pubrel',
1041
+ qos: 2,
1042
+ messageId: mid
1043
+ }
1044
+
1045
+ this._sendPacket(response)
1046
+ break
1047
+ case 'suback':
1048
+ delete this.outgoing[mid]
1049
+ if (packet.granted.length === 1 && (packet.granted[0] & 0x80) !== 0) {
1050
+ // suback with Failure status
1051
+ var topics = this.messageIdToTopic[mid]
1052
+ if (topics) {
1053
+ topics.forEach(function (topic) {
1054
+ delete that._resubscribeTopics[topic]
1055
+ })
1056
+ }
1057
+ }
1058
+ cb(null, packet)
1059
+ break
1060
+ case 'unsuback':
1061
+ delete this.outgoing[mid]
1062
+ cb(null)
1063
+ break
1064
+ default:
1065
+ that.emit('error', new Error('unrecognized packet type'))
1066
+ }
1067
+
1068
+ if (this.disconnecting &&
1069
+ Object.keys(this.outgoing).length === 0) {
1070
+ this.emit('outgoingEmpty')
1071
+ }
1072
+ }
1073
+
1074
+ /**
1075
+ * _handlePubrel
1076
+ *
1077
+ * @param {Object} packet
1078
+ * @api private
1079
+ */
1080
+ MqttClient.prototype._handlePubrel = function (packet, callback) {
1081
+ callback = typeof callback !== 'undefined' ? callback : nop
1082
+ var mid = packet.messageId
1083
+ var that = this
1084
+
1085
+ var comp = {cmd: 'pubcomp', messageId: mid}
1086
+
1087
+ that.incomingStore.get(packet, function (err, pub) {
1088
+ if (!err && pub.cmd !== 'pubrel') {
1089
+ that.emit('message', pub.topic, pub.payload, pub)
1090
+ that.incomingStore.put(packet, function (err) {
1091
+ if (err) {
1092
+ return callback(err)
1093
+ }
1094
+ that.handleMessage(pub, function (err) {
1095
+ if (err) {
1096
+ return callback(err)
1097
+ }
1098
+ that._sendPacket(comp, callback)
1099
+ })
1100
+ })
1101
+ } else {
1102
+ that._sendPacket(comp, callback)
1103
+ }
1104
+ })
1105
+ }
1106
+
1107
+ /**
1108
+ * _nextId
1109
+ * @return unsigned int
1110
+ */
1111
+ MqttClient.prototype._nextId = function () {
1112
+ // id becomes current state of this.nextId and increments afterwards
1113
+ var id = this.nextId++
1114
+ // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
1115
+ if (this.nextId === 65536) {
1116
+ this.nextId = 1
1117
+ }
1118
+ return id
1119
+ }
1120
+
1121
+ /**
1122
+ * getLastMessageId
1123
+ * @return unsigned int
1124
+ */
1125
+ MqttClient.prototype.getLastMessageId = function () {
1126
+ return (this.nextId === 1) ? 65535 : (this.nextId - 1)
1127
+ }
1128
+
1129
+ module.exports = MqttClient