mqtt 2.18.6 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -5,7 +5,6 @@
5
5
  */
6
6
  var events = require('events')
7
7
  var Store = require('./store')
8
- var eos = require('end-of-stream')
9
8
  var mqttPacket = require('mqtt-packet')
10
9
  var Writable = require('readable-stream').Writable
11
10
  var inherits = require('inherits')
@@ -26,6 +25,51 @@ var defaultConnectOptions = {
26
25
  clean: true,
27
26
  resubscribe: true
28
27
  }
28
+ var errors = {
29
+ 0: '',
30
+ 1: 'Unacceptable protocol version',
31
+ 2: 'Identifier rejected',
32
+ 3: 'Server unavailable',
33
+ 4: 'Bad username or password',
34
+ 5: 'Not authorized',
35
+ 16: 'No matching subscribers',
36
+ 17: 'No subscription existed',
37
+ 128: 'Unspecified error',
38
+ 129: 'Malformed Packet',
39
+ 130: 'Protocol Error',
40
+ 131: 'Implementation specific error',
41
+ 132: 'Unsupported Protocol Version',
42
+ 133: 'Client Identifier not valid',
43
+ 134: 'Bad User Name or Password',
44
+ 135: 'Not authorized',
45
+ 136: 'Server unavailable',
46
+ 137: 'Server busy',
47
+ 138: 'Banned',
48
+ 139: 'Server shutting down',
49
+ 140: 'Bad authentication method',
50
+ 141: 'Keep Alive timeout',
51
+ 142: 'Session taken over',
52
+ 143: 'Topic Filter invalid',
53
+ 144: 'Topic Name invalid',
54
+ 145: 'Packet identifier in use',
55
+ 146: 'Packet Identifier not found',
56
+ 147: 'Receive Maximum exceeded',
57
+ 148: 'Topic Alias invalid',
58
+ 149: 'Packet too large',
59
+ 150: 'Message rate too high',
60
+ 151: 'Quota exceeded',
61
+ 152: 'Administrative action',
62
+ 153: 'Payload format invalid',
63
+ 154: 'Retain not supported',
64
+ 155: 'QoS not supported',
65
+ 156: 'Use another server',
66
+ 157: 'Server moved',
67
+ 158: 'Shared Subscriptions not supported',
68
+ 159: 'Connection rate exceeded',
69
+ 160: 'Maximum connect time',
70
+ 161: 'Subscription Identifiers not supported',
71
+ 162: 'Wildcard Subscriptions not supported'
72
+ }
29
73
 
30
74
  function defaultId () {
31
75
  return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
@@ -34,7 +78,7 @@ function defaultId () {
34
78
  function sendPacket (client, packet, cb) {
35
79
  client.emit('packetsend', packet)
36
80
 
37
- var result = mqttPacket.writeToStream(packet, client.stream)
81
+ var result = mqttPacket.writeToStream(packet, client.stream, client.options)
38
82
 
39
83
  if (!result && cb) {
40
84
  client.stream.once('drain', cb)
@@ -46,19 +90,31 @@ function sendPacket (client, packet, cb) {
46
90
  function flush (queue) {
47
91
  if (queue) {
48
92
  Object.keys(queue).forEach(function (messageId) {
49
- if (typeof queue[messageId] === 'function') {
50
- queue[messageId](new Error('Connection closed'))
93
+ if (typeof queue[messageId].cb === 'function') {
94
+ queue[messageId].cb(new Error('Connection closed'))
95
+ delete queue[messageId]
96
+ }
97
+ })
98
+ }
99
+ }
100
+
101
+ function flushVolatile (queue) {
102
+ if (queue) {
103
+ Object.keys(queue).forEach(function (messageId) {
104
+ if (queue[messageId].volatile && typeof queue[messageId].cb === 'function') {
105
+ queue[messageId].cb(new Error('Connection closed'))
51
106
  delete queue[messageId]
52
107
  }
53
108
  })
54
109
  }
55
110
  }
56
111
 
57
- function storeAndSend (client, packet, cb) {
112
+ function storeAndSend (client, packet, cb, cbStorePut) {
58
113
  client.outgoingStore.put(packet, function storedPacket (err) {
59
114
  if (err) {
60
115
  return cb && cb(err)
61
116
  }
117
+ cbStorePut()
62
118
  sendPacket(client, packet, cb)
63
119
  })
64
120
  }
@@ -91,16 +147,18 @@ function MqttClient (streamBuilder, options) {
91
147
  }
92
148
  }
93
149
 
94
- this.options.clientId = (typeof this.options.clientId === 'string') ? this.options.clientId : defaultId()
150
+ this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()
151
+
152
+ this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }
95
153
 
96
154
  this.streamBuilder = streamBuilder
97
155
 
98
156
  // Inflight message storages
99
- this.outgoingStore = this.options.outgoingStore || new Store()
100
- this.incomingStore = this.options.incomingStore || new Store()
157
+ this.outgoingStore = options.outgoingStore || new Store()
158
+ this.incomingStore = options.incomingStore || new Store()
101
159
 
102
160
  // Should QoS zero messages be queued when the connection is broken?
103
- this.queueQoSZero = this.options.queueQoSZero === undefined ? true : this.options.queueQoSZero
161
+ this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero
104
162
 
105
163
  // map of subscribed topics to support reconnection
106
164
  this._resubscribeTopics = {}
@@ -120,6 +178,10 @@ function MqttClient (streamBuilder, options) {
120
178
  this.connackTimer = null
121
179
  // Reconnect timer
122
180
  this.reconnectTimer = null
181
+ // Is processing store?
182
+ this._storeProcessing = false
183
+ // Packet Ids are put into the store during store processing
184
+ this._packetIdsDuringStoreProcessing = {}
123
185
  /**
124
186
  * MessageIDs starting with 1
125
187
  * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
@@ -129,64 +191,8 @@ function MqttClient (streamBuilder, options) {
129
191
  // Inflight callbacks
130
192
  this.outgoing = {}
131
193
 
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
- })
194
+ // True if connection is first time.
195
+ this._firstConnection = true
190
196
 
191
197
  // Mark disconnected on stream close
192
198
  this.on('close', function () {
@@ -194,9 +200,6 @@ function MqttClient (streamBuilder, options) {
194
200
  clearTimeout(this.connackTimer)
195
201
  })
196
202
 
197
- // Setup ping timer
198
- this.on('connect', this._setupPingTimer)
199
-
200
203
  // Send queued packets
201
204
  this.on('connect', function () {
202
205
  var queue = this.queue
@@ -225,23 +228,6 @@ function MqttClient (streamBuilder, options) {
225
228
  deliver()
226
229
  })
227
230
 
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
231
  // Clear ping timer
246
232
  this.on('close', function () {
247
233
  if (that.pingTimer !== null) {
@@ -281,18 +267,24 @@ MqttClient.prototype._setupStream = function () {
281
267
  })
282
268
 
283
269
  function nextTickWork () {
284
- process.nextTick(work)
270
+ if (packets.length) {
271
+ process.nextTick(work)
272
+ } else {
273
+ var done = completeParse
274
+ completeParse = null
275
+ done()
276
+ }
285
277
  }
286
278
 
287
279
  function work () {
288
280
  var packet = packets.shift()
289
- var done = completeParse
290
281
 
291
282
  if (packet) {
292
283
  that._handlePacket(packet, nextTickWork)
293
284
  } else {
285
+ var done = completeParse
294
286
  completeParse = null
295
- done()
287
+ if (done) done()
296
288
  }
297
289
  }
298
290
 
@@ -308,7 +300,10 @@ MqttClient.prototype._setupStream = function () {
308
300
  this.stream.on('error', nop)
309
301
 
310
302
  // Echo stream close
311
- eos(this.stream, this.emit.bind(this, 'close'))
303
+ this.stream.on('close', function () {
304
+ flushVolatile(that.outgoing)
305
+ that.emit('close')
306
+ })
312
307
 
313
308
  // Send a connect packet
314
309
  connectPacket = Object.create(this.options)
@@ -319,6 +314,18 @@ MqttClient.prototype._setupStream = function () {
319
314
  // Echo connection errors
320
315
  parser.on('error', this.emit.bind(this, 'error'))
321
316
 
317
+ // auth
318
+ if (this.options.properties) {
319
+ if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {
320
+ this.emit('error', new Error('Packet has no Authentication Method'))
321
+ return this
322
+ }
323
+ if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {
324
+ var authPacket = xtend({cmd: 'auth', reasonCode: 0}, this.options.authPacket)
325
+ sendPacket(this, authPacket)
326
+ }
327
+ }
328
+
322
329
  // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
323
330
  this.stream.setMaxListeners(1000)
324
331
 
@@ -329,6 +336,14 @@ MqttClient.prototype._setupStream = function () {
329
336
  }
330
337
 
331
338
  MqttClient.prototype._handlePacket = function (packet, done) {
339
+ var options = this.options
340
+
341
+ if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {
342
+ this.emit('error', new Error('exceeding packets size ' + packet.cmd))
343
+ this.end({reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' }})
344
+ return this
345
+ }
346
+
332
347
  this.emit('packetreceive', packet)
333
348
 
334
349
  switch (packet.cmd) {
@@ -354,6 +369,10 @@ MqttClient.prototype._handlePacket = function (packet, done) {
354
369
  this._handlePingresp(packet)
355
370
  done()
356
371
  break
372
+ case 'disconnect':
373
+ this._handleDisconnect(packet)
374
+ done()
375
+ break
357
376
  default:
358
377
  // do nothing
359
378
  // maybe we should do an error handling
@@ -382,6 +401,7 @@ MqttClient.prototype._checkDisconnecting = function (callback) {
382
401
  * {Number} qos - qos level to publish on
383
402
  * {Boolean} retain - whether or not to retain the message
384
403
  * {Boolean} dup - whether or not mark a message as duplicate
404
+ * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
385
405
  * @param {Function} [callback] - function(err){}
386
406
  * called when publish succeeds or fails
387
407
  * @returns {MqttClient} this - for chaining
@@ -394,6 +414,7 @@ MqttClient.prototype._checkDisconnecting = function (callback) {
394
414
  */
395
415
  MqttClient.prototype.publish = function (topic, message, opts, callback) {
396
416
  var packet
417
+ var options = this.options
397
418
 
398
419
  // .publish(topic, payload, cb);
399
420
  if (typeof opts === 'function') {
@@ -419,16 +440,42 @@ MqttClient.prototype.publish = function (topic, message, opts, callback) {
419
440
  dup: opts.dup
420
441
  }
421
442
 
443
+ if (options.protocolVersion === 5) {
444
+ packet.properties = opts.properties
445
+ if ((!options.properties && packet.properties && packet.properties.topicAlias) || ((opts.properties && options.properties) &&
446
+ ((opts.properties.topicAlias && options.properties.topicAliasMaximum && opts.properties.topicAlias > options.properties.topicAliasMaximum) ||
447
+ (!options.properties.topicAliasMaximum && opts.properties.topicAlias)))) {
448
+ /*
449
+ if we are don`t setup topic alias or
450
+ topic alias maximum less than topic alias or
451
+ server don`t give topic alias maximum,
452
+ we are removing topic alias from packet
453
+ */
454
+ delete packet.properties.topicAlias
455
+ }
456
+ }
457
+
422
458
  switch (opts.qos) {
423
459
  case 1:
424
460
  case 2:
425
-
426
461
  // Add to callbacks
427
- this.outgoing[packet.messageId] = callback || nop
428
- this._sendPacket(packet)
462
+ this.outgoing[packet.messageId] = {
463
+ volatile: false,
464
+ cb: callback || nop
465
+ }
466
+ if (this._storeProcessing) {
467
+ this._packetIdsDuringStoreProcessing[packet.messageId] = false
468
+ this._storePacket(packet, undefined, opts.cbStorePut)
469
+ } else {
470
+ this._sendPacket(packet, undefined, opts.cbStorePut)
471
+ }
429
472
  break
430
473
  default:
431
- this._sendPacket(packet, callback)
474
+ if (this._storeProcessing) {
475
+ this._storePacket(packet, callback, opts.cbStorePut)
476
+ } else {
477
+ this._sendPacket(packet, callback, opts.cbStorePut)
478
+ }
432
479
  break
433
480
  }
434
481
 
@@ -448,12 +495,15 @@ MqttClient.prototype.publish = function (topic, message, opts, callback) {
448
495
  * @api public
449
496
  * @example client.subscribe('topic');
450
497
  * @example client.subscribe('topic', {qos: 1});
451
- * @example client.subscribe({'topic': 0, 'topic2': 1}, console.log);
498
+ * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
452
499
  * @example client.subscribe('topic', console.log);
453
500
  */
454
501
  MqttClient.prototype.subscribe = function () {
455
502
  var packet
456
- var args = Array.prototype.slice.call(arguments)
503
+ var args = new Array(arguments.length)
504
+ for (var i = 0; i < arguments.length; i++) {
505
+ args[i] = arguments[i]
506
+ }
457
507
  var subs = []
458
508
  var obj = args.shift()
459
509
  var resubscribe = obj.resubscribe
@@ -461,6 +511,7 @@ MqttClient.prototype.subscribe = function () {
461
511
  var opts = args.pop()
462
512
  var invalidTopic
463
513
  var that = this
514
+ var version = this.options.protocolVersion
464
515
 
465
516
  delete obj.resubscribe
466
517
 
@@ -483,31 +534,52 @@ MqttClient.prototype.subscribe = function () {
483
534
  return this
484
535
  }
485
536
 
486
- var defaultOpts = { qos: 0 }
537
+ var defaultOpts = {
538
+ qos: 0
539
+ }
540
+ if (version === 5) {
541
+ defaultOpts.nl = false
542
+ defaultOpts.rap = false
543
+ defaultOpts.rh = 0
544
+ }
487
545
  opts = xtend(defaultOpts, opts)
488
546
 
489
547
  if (Array.isArray(obj)) {
490
548
  obj.forEach(function (topic) {
491
- if (that._resubscribeTopics[topic] < opts.qos ||
492
- !that._resubscribeTopics.hasOwnProperty(topic) ||
549
+ if (!that._resubscribeTopics.hasOwnProperty(topic) ||
550
+ that._resubscribeTopics[topic].qos < opts.qos ||
493
551
  resubscribe) {
494
- subs.push({
552
+ var currentOpts = {
495
553
  topic: topic,
496
554
  qos: opts.qos
497
- })
555
+ }
556
+ if (version === 5) {
557
+ currentOpts.nl = opts.nl
558
+ currentOpts.rap = opts.rap
559
+ currentOpts.rh = opts.rh
560
+ currentOpts.properties = opts.properties
561
+ }
562
+ subs.push(currentOpts)
498
563
  }
499
564
  })
500
565
  } else {
501
566
  Object
502
567
  .keys(obj)
503
568
  .forEach(function (k) {
504
- if (that._resubscribeTopics[k] < obj[k] ||
505
- !that._resubscribeTopics.hasOwnProperty(k) ||
569
+ if (!that._resubscribeTopics.hasOwnProperty(k) ||
570
+ that._resubscribeTopics[k].qos < obj[k].qos ||
506
571
  resubscribe) {
507
- subs.push({
572
+ var currentOpts = {
508
573
  topic: k,
509
- qos: obj[k]
510
- })
574
+ qos: obj[k].qos
575
+ }
576
+ if (version === 5) {
577
+ currentOpts.nl = obj[k].nl
578
+ currentOpts.rap = obj[k].rap
579
+ currentOpts.rh = obj[k].rh
580
+ currentOpts.properties = opts.properties
581
+ }
582
+ subs.push(currentOpts)
511
583
  }
512
584
  })
513
585
  }
@@ -521,6 +593,10 @@ MqttClient.prototype.subscribe = function () {
521
593
  messageId: this._nextId()
522
594
  }
523
595
 
596
+ if (opts.properties) {
597
+ packet.properties = opts.properties
598
+ }
599
+
524
600
  if (!subs.length) {
525
601
  callback(null, [])
526
602
  return
@@ -531,22 +607,32 @@ MqttClient.prototype.subscribe = function () {
531
607
  var topics = []
532
608
  subs.forEach(function (sub) {
533
609
  if (that.options.reconnectPeriod > 0) {
534
- that._resubscribeTopics[sub.topic] = sub.qos
610
+ var topic = { qos: sub.qos }
611
+ if (version === 5) {
612
+ topic.nl = sub.nl || false
613
+ topic.rap = sub.rap || false
614
+ topic.rh = sub.rh || 0
615
+ topic.properties = sub.properties
616
+ }
617
+ that._resubscribeTopics[sub.topic] = topic
535
618
  topics.push(sub.topic)
536
619
  }
537
620
  })
538
621
  that.messageIdToTopic[packet.messageId] = topics
539
622
  }
540
623
 
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]
624
+ this.outgoing[packet.messageId] = {
625
+ volatile: true,
626
+ cb: function (err, packet) {
627
+ if (!err) {
628
+ var granted = packet.granted
629
+ for (var i = 0; i < granted.length; i += 1) {
630
+ subs[i].qos = granted[i]
631
+ }
546
632
  }
547
- }
548
633
 
549
- callback(err, subs)
634
+ callback(err, subs)
635
+ }
550
636
  }
551
637
 
552
638
  this._sendPacket(packet)
@@ -558,21 +644,37 @@ MqttClient.prototype.subscribe = function () {
558
644
  * unsubscribe - unsubscribe from topic(s)
559
645
  *
560
646
  * @param {String, Array} topic - topics to unsubscribe from
647
+ * @param {Object} [opts] - optional subscription options, includes:
648
+ * {Object} properties - properties of unsubscribe packet
561
649
  * @param {Function} [callback] - callback fired on unsuback
562
650
  * @returns {MqttClient} this - for chaining
563
651
  * @api public
564
652
  * @example client.unsubscribe('topic');
565
653
  * @example client.unsubscribe('topic', console.log);
566
654
  */
567
- MqttClient.prototype.unsubscribe = function (topic, callback) {
655
+ MqttClient.prototype.unsubscribe = function () {
568
656
  var packet = {
569
657
  cmd: 'unsubscribe',
570
658
  qos: 1,
571
659
  messageId: this._nextId()
572
660
  }
573
661
  var that = this
662
+ var args = new Array(arguments.length)
663
+ for (var i = 0; i < arguments.length; i++) {
664
+ args[i] = arguments[i]
665
+ }
666
+ var topic = args.shift()
667
+ var callback = args.pop() || nop
668
+ var opts = args.pop()
574
669
 
575
- callback = callback || nop
670
+ if (typeof topic === 'string') {
671
+ topic = [topic]
672
+ }
673
+
674
+ if (typeof callback !== 'function') {
675
+ opts = callback
676
+ callback = nop
677
+ }
576
678
 
577
679
  if (this._checkDisconnecting(callback)) {
578
680
  return this
@@ -590,7 +692,14 @@ MqttClient.prototype.unsubscribe = function (topic, callback) {
590
692
  })
591
693
  }
592
694
 
593
- this.outgoing[packet.messageId] = callback
695
+ if (typeof opts === 'object' && opts.properties) {
696
+ packet.properties = opts.properties
697
+ }
698
+
699
+ this.outgoing[packet.messageId] = {
700
+ volatile: true,
701
+ cb: callback
702
+ }
594
703
 
595
704
  this._sendPacket(packet)
596
705
 
@@ -606,14 +715,33 @@ MqttClient.prototype.unsubscribe = function (topic, callback) {
606
715
  *
607
716
  * @api public
608
717
  */
609
- MqttClient.prototype.end = function (force, cb) {
718
+ MqttClient.prototype.end = function () {
610
719
  var that = this
611
720
 
612
- if (typeof force === 'function') {
613
- cb = force
721
+ var force = arguments[0]
722
+ var opts = arguments[1]
723
+ var cb = arguments[2]
724
+
725
+ if (force == null || typeof force !== 'boolean') {
726
+ cb = opts || nop
727
+ opts = force
614
728
  force = false
729
+ if (typeof opts !== 'object') {
730
+ cb = opts
731
+ opts = null
732
+ if (typeof cb !== 'function') {
733
+ cb = nop
734
+ }
735
+ }
736
+ }
737
+
738
+ if (typeof opts !== 'object') {
739
+ cb = opts
740
+ opts = null
615
741
  }
616
742
 
743
+ cb = cb || nop
744
+
617
745
  function closeStores () {
618
746
  that.disconnected = true
619
747
  that.incomingStore.close(function () {
@@ -633,7 +761,7 @@ MqttClient.prototype.end = function (force, cb) {
633
761
  // defer closesStores of an I/O cycle,
634
762
  // just to make sure things are
635
763
  // ok for websockets
636
- that._cleanUp(force, setImmediate.bind(null, closeStores))
764
+ that._cleanUp(force, setImmediate.bind(null, closeStores), opts)
637
765
  }
638
766
 
639
767
  if (this.disconnecting) {
@@ -665,7 +793,7 @@ MqttClient.prototype.end = function (force, cb) {
665
793
  * @example client.removeOutgoingMessage(client.getLastMessageId());
666
794
  */
667
795
  MqttClient.prototype.removeOutgoingMessage = function (mid) {
668
- var cb = this.outgoing[mid]
796
+ var cb = this.outgoing[mid] ? this.outgoing[mid].cb : null
669
797
  delete this.outgoing[mid]
670
798
  this.outgoingStore.del({messageId: mid}, function () {
671
799
  cb(new Error('Message removed'))
@@ -751,6 +879,7 @@ MqttClient.prototype._clearReconnect = function () {
751
879
  * @api private
752
880
  */
753
881
  MqttClient.prototype._cleanUp = function (forced, done) {
882
+ var opts = arguments[2]
754
883
  if (done) {
755
884
  this.stream.on('close', done)
756
885
  }
@@ -761,8 +890,9 @@ MqttClient.prototype._cleanUp = function (forced, done) {
761
890
  }
762
891
  this.stream.destroy()
763
892
  } else {
893
+ var packet = xtend({ cmd: 'disconnect' }, opts)
764
894
  this._sendPacket(
765
- { cmd: 'disconnect' },
895
+ packet,
766
896
  setImmediate.bind(
767
897
  null,
768
898
  this.stream.end.bind(this.stream)
@@ -791,23 +921,14 @@ MqttClient.prototype._cleanUp = function (forced, done) {
791
921
  * @param {String} type - packet type (see `protocol`)
792
922
  * @param {Object} packet - packet options
793
923
  * @param {Function} cb - callback when the packet is sent
924
+ * @param {Function} cbStorePut - called when message is put into outgoingStore
794
925
  * @api private
795
926
  */
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
- }
927
+ MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {
928
+ cbStorePut = cbStorePut || nop
810
929
 
930
+ if (!this.connected) {
931
+ this._storePacket(packet, cb, cbStorePut)
811
932
  return
812
933
  }
813
934
 
@@ -818,7 +939,7 @@ MqttClient.prototype._sendPacket = function (packet, cb) {
818
939
  case 'publish':
819
940
  break
820
941
  case 'pubrel':
821
- storeAndSend(this, packet, cb)
942
+ storeAndSend(this, packet, cb, cbStorePut)
822
943
  return
823
944
  default:
824
945
  sendPacket(this, packet, cb)
@@ -828,7 +949,7 @@ MqttClient.prototype._sendPacket = function (packet, cb) {
828
949
  switch (packet.qos) {
829
950
  case 2:
830
951
  case 1:
831
- storeAndSend(this, packet, cb)
952
+ storeAndSend(this, packet, cb, cbStorePut)
832
953
  break
833
954
  /**
834
955
  * no need of case here since it will be caught by default
@@ -843,6 +964,32 @@ MqttClient.prototype._sendPacket = function (packet, cb) {
843
964
  }
844
965
  }
845
966
 
967
+ /**
968
+ * _storePacket - queue a packet
969
+ * @param {String} type - packet type (see `protocol`)
970
+ * @param {Object} packet - packet options
971
+ * @param {Function} cb - callback when the packet is sent
972
+ * @param {Function} cbStorePut - called when message is put into outgoingStore
973
+ * @api private
974
+ */
975
+ MqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {
976
+ cbStorePut = cbStorePut || nop
977
+
978
+ if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
979
+ this.queue.push({ packet: packet, cb: cb })
980
+ } else if (packet.qos > 0) {
981
+ cb = this.outgoing[packet.messageId] ? this.outgoing[packet.messageId].cb : null
982
+ this.outgoingStore.put(packet, function (err) {
983
+ if (err) {
984
+ return cb && cb(err)
985
+ }
986
+ cbStorePut()
987
+ })
988
+ } else if (cb) {
989
+ cb(new Error('No connection to broker'))
990
+ }
991
+ }
992
+
846
993
  /**
847
994
  * _setupPingTimer - setup the ping timer
848
995
  *
@@ -901,21 +1048,30 @@ MqttClient.prototype._handlePingresp = function () {
901
1048
  */
902
1049
 
903
1050
  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
- ]
1051
+ var options = this.options
1052
+ var version = options.protocolVersion
1053
+ var rc = version === 5 ? packet.reasonCode : packet.returnCode
913
1054
 
914
1055
  clearTimeout(this.connackTimer)
915
1056
 
1057
+ if (packet.properties) {
1058
+ if (packet.properties.topicAliasMaximum) {
1059
+ if (!options.properties) { options.properties = {} }
1060
+ options.properties.topicAliasMaximum = packet.properties.topicAliasMaximum
1061
+ }
1062
+ if (packet.properties.serverKeepAlive && options.keepalive) {
1063
+ options.keepalive = packet.properties.serverKeepAlive
1064
+ this._shiftPingInterval()
1065
+ }
1066
+ if (packet.properties.maximumPacketSize) {
1067
+ if (!options.properties) { options.properties = {} }
1068
+ options.properties.maximumPacketSize = packet.properties.maximumPacketSize
1069
+ }
1070
+ }
1071
+
916
1072
  if (rc === 0) {
917
1073
  this.reconnecting = false
918
- this.emit('connect', packet)
1074
+ this._onConnect(packet)
919
1075
  } else if (rc > 0) {
920
1076
  var err = new Error('Connection refused: ' + errors[rc])
921
1077
  err.code = rc
@@ -954,30 +1110,53 @@ default:
954
1110
  for now i just suppressed the warnings
955
1111
  */
956
1112
  MqttClient.prototype._handlePublish = function (packet, done) {
1113
+ done = typeof done !== 'undefined' ? done : nop
957
1114
  var topic = packet.topic.toString()
958
1115
  var message = packet.payload
959
1116
  var qos = packet.qos
960
1117
  var mid = packet.messageId
961
1118
  var that = this
1119
+ var options = this.options
1120
+ var validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
962
1121
 
963
1122
  switch (qos) {
964
- case 2:
965
- this.incomingStore.put(packet, function () {
966
- that._sendPacket({cmd: 'pubrec', messageId: mid}, done)
1123
+ case 2: {
1124
+ options.customHandleAcks(topic, message, packet, function (error, code) {
1125
+ if (!(error instanceof Error)) {
1126
+ code = error
1127
+ error = null
1128
+ }
1129
+ if (error) { return that.emit('error', error) }
1130
+ if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }
1131
+ if (code) {
1132
+ that._sendPacket({cmd: 'pubrec', messageId: mid, reasonCode: code}, done)
1133
+ } else {
1134
+ that.incomingStore.put(packet, function () {
1135
+ that._sendPacket({cmd: 'pubrec', messageId: mid}, done)
1136
+ })
1137
+ }
967
1138
  })
968
1139
  break
969
- case 1:
1140
+ }
1141
+ case 1: {
970
1142
  // emit the message event
971
- this.emit('message', topic, message, packet)
972
- this.handleMessage(packet, function (err) {
973
- if (err) {
974
- return done && done(err)
1143
+ options.customHandleAcks(topic, message, packet, function (error, code) {
1144
+ if (!(error instanceof Error)) {
1145
+ code = error
1146
+ error = null
975
1147
  }
976
- // send 'puback' if the above 'handleMessage' method executed
977
- // successfully.
978
- that._sendPacket({cmd: 'puback', messageId: mid}, done)
1148
+ if (error) { return that.emit('error', error) }
1149
+ if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }
1150
+ if (!code) { that.emit('message', topic, message, packet) }
1151
+ that.handleMessage(packet, function (err) {
1152
+ if (err) {
1153
+ return done && done(err)
1154
+ }
1155
+ that._sendPacket({cmd: 'puback', messageId: mid, reasonCode: code}, done)
1156
+ })
979
1157
  })
980
1158
  break
1159
+ }
981
1160
  case 0:
982
1161
  // emit the message event
983
1162
  this.emit('message', topic, message, packet)
@@ -1014,8 +1193,9 @@ MqttClient.prototype._handleAck = function (packet) {
1014
1193
  var mid = packet.messageId
1015
1194
  var type = packet.cmd
1016
1195
  var response = null
1017
- var cb = this.outgoing[mid]
1196
+ var cb = this.outgoing[mid] ? this.outgoing[mid].cb : null
1018
1197
  var that = this
1198
+ var err
1019
1199
 
1020
1200
  if (!cb) {
1021
1201
  // Server sent an ack in error, ignore it.
@@ -1027,7 +1207,13 @@ MqttClient.prototype._handleAck = function (packet) {
1027
1207
  case 'pubcomp':
1028
1208
  // same thing as puback for QoS 2
1029
1209
  case 'puback':
1210
+ var pubackRC = packet.reasonCode
1030
1211
  // Callback - we're done
1212
+ if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
1213
+ err = new Error('Publish error: ' + errors[pubackRC])
1214
+ err.code = pubackRC
1215
+ cb(err, packet)
1216
+ }
1031
1217
  delete this.outgoing[mid]
1032
1218
  this.outgoingStore.del(packet, cb)
1033
1219
  break
@@ -1037,18 +1223,27 @@ MqttClient.prototype._handleAck = function (packet) {
1037
1223
  qos: 2,
1038
1224
  messageId: mid
1039
1225
  }
1226
+ var pubrecRC = packet.reasonCode
1040
1227
 
1041
- this._sendPacket(response)
1228
+ if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
1229
+ err = new Error('Publish error: ' + errors[pubrecRC])
1230
+ err.code = pubrecRC
1231
+ cb(err, packet)
1232
+ } else {
1233
+ this._sendPacket(response)
1234
+ }
1042
1235
  break
1043
1236
  case 'suback':
1044
1237
  delete this.outgoing[mid]
1045
- if (packet.granted.length === 1 && (packet.granted[0] & 0x80) !== 0) {
1046
- // suback with Failure status
1047
- var topics = this.messageIdToTopic[mid]
1048
- if (topics) {
1049
- topics.forEach(function (topic) {
1050
- delete that._resubscribeTopics[topic]
1051
- })
1238
+ for (var grantedI = 0; grantedI < packet.granted.length; grantedI++) {
1239
+ if ((packet.granted[grantedI] & 0x80) !== 0) {
1240
+ // suback with Failure status
1241
+ var topics = this.messageIdToTopic[mid]
1242
+ if (topics) {
1243
+ topics.forEach(function (topic) {
1244
+ delete that._resubscribeTopics[topic]
1245
+ })
1246
+ }
1052
1247
  }
1053
1248
  }
1054
1249
  cb(null, packet)
@@ -1074,19 +1269,20 @@ MqttClient.prototype._handleAck = function (packet) {
1074
1269
  * @api private
1075
1270
  */
1076
1271
  MqttClient.prototype._handlePubrel = function (packet, callback) {
1272
+ callback = typeof callback !== 'undefined' ? callback : nop
1077
1273
  var mid = packet.messageId
1078
1274
  var that = this
1079
1275
 
1080
1276
  var comp = {cmd: 'pubcomp', messageId: mid}
1081
1277
 
1082
1278
  that.incomingStore.get(packet, function (err, pub) {
1083
- if (!err && pub.cmd !== 'pubrel') {
1279
+ if (!err) {
1084
1280
  that.emit('message', pub.topic, pub.payload, pub)
1085
- that.incomingStore.put(packet)
1086
1281
  that.handleMessage(pub, function (err) {
1087
1282
  if (err) {
1088
- return callback && callback(err)
1283
+ return callback(err)
1089
1284
  }
1285
+ that.incomingStore.del(pub, nop)
1090
1286
  that._sendPacket(comp, callback)
1091
1287
  })
1092
1288
  } else {
@@ -1095,6 +1291,16 @@ MqttClient.prototype._handlePubrel = function (packet, callback) {
1095
1291
  })
1096
1292
  }
1097
1293
 
1294
+ /**
1295
+ * _handleDisconnect
1296
+ *
1297
+ * @param {Object} packet
1298
+ * @api private
1299
+ */
1300
+ MqttClient.prototype._handleDisconnect = function (packet) {
1301
+ this.emit('disconnect', packet)
1302
+ }
1303
+
1098
1304
  /**
1099
1305
  * _nextId
1100
1306
  * @return unsigned int
@@ -1117,4 +1323,138 @@ MqttClient.prototype.getLastMessageId = function () {
1117
1323
  return (this.nextId === 1) ? 65535 : (this.nextId - 1)
1118
1324
  }
1119
1325
 
1326
+ /**
1327
+ * _resubscribe
1328
+ * @api private
1329
+ */
1330
+ MqttClient.prototype._resubscribe = function (connack) {
1331
+ var _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
1332
+ if (!this._firstConnection &&
1333
+ (this.options.clean || (this.options.protocolVersion === 5 && !connack.sessionPresent)) &&
1334
+ _resubscribeTopicsKeys.length > 0) {
1335
+ if (this.options.resubscribe) {
1336
+ if (this.options.protocolVersion === 5) {
1337
+ for (var topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {
1338
+ var resubscribeTopic = {}
1339
+ resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]
1340
+ resubscribeTopic.resubscribe = true
1341
+ this.subscribe(resubscribeTopic, {properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties})
1342
+ }
1343
+ } else {
1344
+ this._resubscribeTopics.resubscribe = true
1345
+ this.subscribe(this._resubscribeTopics)
1346
+ }
1347
+ } else {
1348
+ this._resubscribeTopics = {}
1349
+ }
1350
+ }
1351
+
1352
+ this._firstConnection = false
1353
+ }
1354
+
1355
+ /**
1356
+ * _onConnect
1357
+ *
1358
+ * @api private
1359
+ */
1360
+ MqttClient.prototype._onConnect = function (packet) {
1361
+ if (this.disconnected) {
1362
+ this.emit('connect', packet)
1363
+ return
1364
+ }
1365
+
1366
+ var that = this
1367
+
1368
+ this._setupPingTimer()
1369
+ this._resubscribe(packet)
1370
+
1371
+ this.connected = true
1372
+
1373
+ function startStreamProcess () {
1374
+ var outStore = that.outgoingStore.createStream()
1375
+
1376
+ function clearStoreProcessing () {
1377
+ that._storeProcessing = false
1378
+ that._packetIdsDuringStoreProcessing = {}
1379
+ }
1380
+
1381
+ that.once('close', remove)
1382
+ outStore.on('error', function (err) {
1383
+ clearStoreProcessing()
1384
+ that.removeListener('close', remove)
1385
+ that.emit('error', err)
1386
+ })
1387
+
1388
+ function remove () {
1389
+ outStore.destroy()
1390
+ outStore = null
1391
+ clearStoreProcessing()
1392
+ }
1393
+
1394
+ function storeDeliver () {
1395
+ // edge case, we wrapped this twice
1396
+ if (!outStore) {
1397
+ return
1398
+ }
1399
+ that._storeProcessing = true
1400
+
1401
+ var packet = outStore.read(1)
1402
+
1403
+ var cb
1404
+
1405
+ if (!packet) {
1406
+ // read when data is available in the future
1407
+ outStore.once('readable', storeDeliver)
1408
+ return
1409
+ }
1410
+
1411
+ // Skip already processed store packets
1412
+ if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
1413
+ storeDeliver()
1414
+ return
1415
+ }
1416
+
1417
+ // Avoid unnecessary stream read operations when disconnected
1418
+ if (!that.disconnecting && !that.reconnectTimer) {
1419
+ cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null
1420
+ that.outgoing[packet.messageId] = {
1421
+ volatile: false,
1422
+ cb: function (err, status) {
1423
+ // Ensure that the original callback passed in to publish gets invoked
1424
+ if (cb) {
1425
+ cb(err, status)
1426
+ }
1427
+
1428
+ storeDeliver()
1429
+ }
1430
+ }
1431
+ that._packetIdsDuringStoreProcessing[packet.messageId] = true
1432
+ that._sendPacket(packet)
1433
+ } else if (outStore.destroy) {
1434
+ outStore.destroy()
1435
+ }
1436
+ }
1437
+
1438
+ outStore.on('end', function () {
1439
+ var allProcessed = true
1440
+ for (var id in that._packetIdsDuringStoreProcessing) {
1441
+ if (!that._packetIdsDuringStoreProcessing[id]) {
1442
+ allProcessed = false
1443
+ break
1444
+ }
1445
+ }
1446
+ if (allProcessed) {
1447
+ clearStoreProcessing()
1448
+ that.removeListener('close', remove)
1449
+ that.emit('connect', packet)
1450
+ } else {
1451
+ startStreamProcess()
1452
+ }
1453
+ })
1454
+ storeDeliver()
1455
+ }
1456
+ // start flowing
1457
+ startStreamProcess()
1458
+ }
1459
+
1120
1460
  module.exports = MqttClient