mqtt 4.2.4 → 4.2.8

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
@@ -1,1581 +1,1581 @@
1
- 'use strict'
2
-
3
- /**
4
- * Module dependencies
5
- */
6
- var EventEmitter = require('events').EventEmitter
7
- var Store = require('./store')
8
- var mqttPacket = require('mqtt-packet')
9
- var Writable = require('readable-stream').Writable
10
- var inherits = require('inherits')
11
- var reInterval = require('reinterval')
12
- var validations = require('./validations')
13
- var xtend = require('xtend')
14
- var debug = require('debug')('mqttjs:client')
15
- var nextTick = process ? process.nextTick : function (callback) { setTimeout(callback, 0) }
16
- var setImmediate = global.setImmediate || function (callback) {
17
- // works in node v0.8
18
- nextTick(callback)
19
- }
20
- var defaultConnectOptions = {
21
- keepalive: 60,
22
- reschedulePings: true,
23
- protocolId: 'MQTT',
24
- protocolVersion: 4,
25
- reconnectPeriod: 1000,
26
- connectTimeout: 30 * 1000,
27
- clean: true,
28
- resubscribe: true
29
- }
30
-
31
- var socketErrors = [
32
- 'ECONNREFUSED',
33
- 'EADDRINUSE',
34
- 'ECONNRESET',
35
- 'ENOTFOUND'
36
- ]
37
-
38
- // Other Socket Errors: EADDRINUSE, ECONNRESET, ENOTFOUND.
39
-
40
- var errors = {
41
- 0: '',
42
- 1: 'Unacceptable protocol version',
43
- 2: 'Identifier rejected',
44
- 3: 'Server unavailable',
45
- 4: 'Bad username or password',
46
- 5: 'Not authorized',
47
- 16: 'No matching subscribers',
48
- 17: 'No subscription existed',
49
- 128: 'Unspecified error',
50
- 129: 'Malformed Packet',
51
- 130: 'Protocol Error',
52
- 131: 'Implementation specific error',
53
- 132: 'Unsupported Protocol Version',
54
- 133: 'Client Identifier not valid',
55
- 134: 'Bad User Name or Password',
56
- 135: 'Not authorized',
57
- 136: 'Server unavailable',
58
- 137: 'Server busy',
59
- 138: 'Banned',
60
- 139: 'Server shutting down',
61
- 140: 'Bad authentication method',
62
- 141: 'Keep Alive timeout',
63
- 142: 'Session taken over',
64
- 143: 'Topic Filter invalid',
65
- 144: 'Topic Name invalid',
66
- 145: 'Packet identifier in use',
67
- 146: 'Packet Identifier not found',
68
- 147: 'Receive Maximum exceeded',
69
- 148: 'Topic Alias invalid',
70
- 149: 'Packet too large',
71
- 150: 'Message rate too high',
72
- 151: 'Quota exceeded',
73
- 152: 'Administrative action',
74
- 153: 'Payload format invalid',
75
- 154: 'Retain not supported',
76
- 155: 'QoS not supported',
77
- 156: 'Use another server',
78
- 157: 'Server moved',
79
- 158: 'Shared Subscriptions not supported',
80
- 159: 'Connection rate exceeded',
81
- 160: 'Maximum connect time',
82
- 161: 'Subscription Identifiers not supported',
83
- 162: 'Wildcard Subscriptions not supported'
84
- }
85
-
86
- function defaultId () {
87
- return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
88
- }
89
-
90
- function sendPacket (client, packet, cb) {
91
- debug('sendPacket :: packet: %O', packet)
92
- debug('sendPacket :: emitting `packetsend`')
93
- client.emit('packetsend', packet)
94
-
95
- debug('sendPacket :: writing to stream')
96
- var result = mqttPacket.writeToStream(packet, client.stream, client.options)
97
- debug('sendPacket :: writeToStream result %s', result)
98
- if (!result && cb) {
99
- debug('sendPacket :: handle events on `drain` once through callback.')
100
- client.stream.once('drain', cb)
101
- } else if (cb) {
102
- debug('sendPacket :: invoking cb')
103
- cb()
104
- }
105
- }
106
-
107
- function flush (queue) {
108
- if (queue) {
109
- debug('flush: queue exists? %b', !!(queue))
110
- Object.keys(queue).forEach(function (messageId) {
111
- if (typeof queue[messageId].cb === 'function') {
112
- queue[messageId].cb(new Error('Connection closed'))
113
- delete queue[messageId]
114
- }
115
- })
116
- }
117
- }
118
-
119
- function flushVolatile (queue) {
120
- if (queue) {
121
- debug('flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function')
122
- Object.keys(queue).forEach(function (messageId) {
123
- if (queue[messageId].volatile && typeof queue[messageId].cb === 'function') {
124
- queue[messageId].cb(new Error('Connection closed'))
125
- delete queue[messageId]
126
- }
127
- })
128
- }
129
- }
130
-
131
- function storeAndSend (client, packet, cb, cbStorePut) {
132
- debug('storeAndSend :: store packet with cmd %s to outgoingStore', packet.cmd)
133
- client.outgoingStore.put(packet, function storedPacket (err) {
134
- if (err) {
135
- return cb && cb(err)
136
- }
137
- cbStorePut()
138
- sendPacket(client, packet, cb)
139
- })
140
- }
141
-
142
- function nop (error) {
143
- debug('nop ::', error)
144
- }
145
-
146
- /**
147
- * MqttClient constructor
148
- *
149
- * @param {Stream} stream - stream
150
- * @param {Object} [options] - connection options
151
- * (see Connection#connect)
152
- */
153
- function MqttClient (streamBuilder, options) {
154
- var k
155
- var that = this
156
-
157
- if (!(this instanceof MqttClient)) {
158
- return new MqttClient(streamBuilder, options)
159
- }
160
-
161
- this.options = options || {}
162
-
163
- // Defaults
164
- for (k in defaultConnectOptions) {
165
- if (typeof this.options[k] === 'undefined') {
166
- this.options[k] = defaultConnectOptions[k]
167
- } else {
168
- this.options[k] = options[k]
169
- }
170
- }
171
-
172
- debug('MqttClient :: options.protocol', options.protocol)
173
- debug('MqttClient :: options.protocolVersion', options.protocolVersion)
174
- debug('MqttClient :: options.username', options.username)
175
- debug('MqttClient :: options.keepalive', options.keepalive)
176
- debug('MqttClient :: options.reconnectPeriod', options.reconnectPeriod)
177
- debug('MqttClient :: options.rejectUnauthorized', options.rejectUnauthorized)
178
-
179
- this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()
180
-
181
- debug('MqttClient :: clientId', this.options.clientId)
182
-
183
- this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }
184
-
185
- this.streamBuilder = streamBuilder
186
-
187
- // Inflight message storages
188
- this.outgoingStore = options.outgoingStore || new Store()
189
- this.incomingStore = options.incomingStore || new Store()
190
-
191
- // Should QoS zero messages be queued when the connection is broken?
192
- this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero
193
-
194
- // map of subscribed topics to support reconnection
195
- this._resubscribeTopics = {}
196
-
197
- // map of a subscribe messageId and a topic
198
- this.messageIdToTopic = {}
199
-
200
- // Ping timer, setup in _setupPingTimer
201
- this.pingTimer = null
202
- // Is the client connected?
203
- this.connected = false
204
- // Are we disconnecting?
205
- this.disconnecting = false
206
- // Packet queue
207
- this.queue = []
208
- // connack timer
209
- this.connackTimer = null
210
- // Reconnect timer
211
- this.reconnectTimer = null
212
- // Is processing store?
213
- this._storeProcessing = false
214
- // Packet Ids are put into the store during store processing
215
- this._packetIdsDuringStoreProcessing = {}
216
- /**
217
- * MessageIDs starting with 1
218
- * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
219
- */
220
- this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
221
-
222
- // Inflight callbacks
223
- this.outgoing = {}
224
-
225
- // True if connection is first time.
226
- this._firstConnection = true
227
-
228
- // Send queued packets
229
- this.on('connect', function () {
230
- var queue = this.queue
231
-
232
- function deliver () {
233
- var entry = queue.shift()
234
- debug('deliver :: entry %o', entry)
235
- var packet = null
236
-
237
- if (!entry) {
238
- return
239
- }
240
-
241
- packet = entry.packet
242
- debug('deliver :: call _sendPacket for %o', packet)
243
- that._sendPacket(
244
- packet,
245
- function (err) {
246
- if (entry.cb) {
247
- entry.cb(err)
248
- }
249
- deliver()
250
- }
251
- )
252
- }
253
-
254
- debug('connect :: sending queued packets')
255
- deliver()
256
- })
257
-
258
- this.on('close', function () {
259
- debug('close :: connected set to `false`')
260
- this.connected = false
261
-
262
- debug('close :: clearing connackTimer')
263
- clearTimeout(this.connackTimer)
264
-
265
- debug('close :: clearing ping timer')
266
- if (that.pingTimer !== null) {
267
- that.pingTimer.clear()
268
- that.pingTimer = null
269
- }
270
-
271
- debug('close :: calling _setupReconnect')
272
- this._setupReconnect()
273
- })
274
- EventEmitter.call(this)
275
-
276
- debug('MqttClient :: setting up stream')
277
- this._setupStream()
278
- }
279
- inherits(MqttClient, EventEmitter)
280
-
281
- /**
282
- * setup the event handlers in the inner stream.
283
- *
284
- * @api private
285
- */
286
- MqttClient.prototype._setupStream = function () {
287
- var connectPacket
288
- var that = this
289
- var writable = new Writable()
290
- var parser = mqttPacket.parser(this.options)
291
- var completeParse = null
292
- var packets = []
293
-
294
- debug('_setupStream :: calling method to clear reconnect')
295
- this._clearReconnect()
296
-
297
- debug('_setupStream :: using streamBuilder provided to client to create stream')
298
- this.stream = this.streamBuilder(this)
299
-
300
- parser.on('packet', function (packet) {
301
- debug('parser :: on packet push to packets array.')
302
- packets.push(packet)
303
- })
304
-
305
- function nextTickWork () {
306
- if (packets.length) {
307
- nextTick(work)
308
- } else {
309
- var done = completeParse
310
- completeParse = null
311
- done()
312
- }
313
- }
314
-
315
- function work () {
316
- debug('work :: getting next packet in queue')
317
- var packet = packets.shift()
318
-
319
- if (packet) {
320
- debug('work :: packet pulled from queue')
321
- that._handlePacket(packet, nextTickWork)
322
- } else {
323
- debug('work :: no packets in queue')
324
- var done = completeParse
325
- completeParse = null
326
- debug('work :: done flag is %s', !!(done))
327
- if (done) done()
328
- }
329
- }
330
-
331
- writable._write = function (buf, enc, done) {
332
- completeParse = done
333
- debug('writable stream :: parsing buffer')
334
- parser.parse(buf)
335
- work()
336
- }
337
-
338
- function streamErrorHandler (error) {
339
- debug('streamErrorHandler :: error', error.message)
340
- if (socketErrors.includes(error.code)) {
341
- // handle error
342
- debug('streamErrorHandler :: emitting error')
343
- that.emit('error', error)
344
- } else {
345
- nop(error)
346
- }
347
- }
348
-
349
- debug('_setupStream :: pipe stream to writable stream')
350
- this.stream.pipe(writable)
351
-
352
- // Suppress connection errors
353
- this.stream.on('error', streamErrorHandler)
354
-
355
- // Echo stream close
356
- this.stream.on('close', function () {
357
- debug('(%s)stream :: on close', that.options.clientId)
358
- flushVolatile(that.outgoing)
359
- debug('stream: emit close to MqttClient')
360
- that.emit('close')
361
- })
362
-
363
- // Send a connect packet
364
- debug('_setupStream: sending packet `connect`')
365
- connectPacket = Object.create(this.options)
366
- connectPacket.cmd = 'connect'
367
- // avoid message queue
368
- sendPacket(this, connectPacket)
369
-
370
- // Echo connection errors
371
- parser.on('error', this.emit.bind(this, 'error'))
372
-
373
- // auth
374
- if (this.options.properties) {
375
- if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {
376
- that.end(() =>
377
- this.emit('error', new Error('Packet has no Authentication Method')
378
- ))
379
- return this
380
- }
381
- if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {
382
- var authPacket = xtend({cmd: 'auth', reasonCode: 0}, this.options.authPacket)
383
- sendPacket(this, authPacket)
384
- }
385
- }
386
-
387
- // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
388
- this.stream.setMaxListeners(1000)
389
-
390
- clearTimeout(this.connackTimer)
391
- this.connackTimer = setTimeout(function () {
392
- debug('!!connectTimeout hit!! Calling _cleanUp with force `true`')
393
- that._cleanUp(true)
394
- }, this.options.connectTimeout)
395
- }
396
-
397
- MqttClient.prototype._handlePacket = function (packet, done) {
398
- var options = this.options
399
-
400
- if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {
401
- this.emit('error', new Error('exceeding packets size ' + packet.cmd))
402
- this.end({reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' }})
403
- return this
404
- }
405
- debug('_handlePacket :: emitting packetreceive')
406
- this.emit('packetreceive', packet)
407
-
408
- switch (packet.cmd) {
409
- case 'publish':
410
- this._handlePublish(packet, done)
411
- break
412
- case 'puback':
413
- case 'pubrec':
414
- case 'pubcomp':
415
- case 'suback':
416
- case 'unsuback':
417
- this._handleAck(packet)
418
- done()
419
- break
420
- case 'pubrel':
421
- this._handlePubrel(packet, done)
422
- break
423
- case 'connack':
424
- this._handleConnack(packet)
425
- done()
426
- break
427
- case 'pingresp':
428
- this._handlePingresp(packet)
429
- done()
430
- break
431
- case 'disconnect':
432
- this._handleDisconnect(packet)
433
- done()
434
- break
435
- default:
436
- // do nothing
437
- // maybe we should do an error handling
438
- // or just log it
439
- break
440
- }
441
- }
442
-
443
- MqttClient.prototype._checkDisconnecting = function (callback) {
444
- if (this.disconnecting) {
445
- if (callback) {
446
- callback(new Error('client disconnecting'))
447
- } else {
448
- this.emit('error', new Error('client disconnecting'))
449
- }
450
- }
451
- return this.disconnecting
452
- }
453
-
454
- /**
455
- * publish - publish <message> to <topic>
456
- *
457
- * @param {String} topic - topic to publish to
458
- * @param {String, Buffer} message - message to publish
459
- * @param {Object} [opts] - publish options, includes:
460
- * {Number} qos - qos level to publish on
461
- * {Boolean} retain - whether or not to retain the message
462
- * {Boolean} dup - whether or not mark a message as duplicate
463
- * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
464
- * @param {Function} [callback] - function(err){}
465
- * called when publish succeeds or fails
466
- * @returns {MqttClient} this - for chaining
467
- * @api public
468
- *
469
- * @example client.publish('topic', 'message');
470
- * @example
471
- * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
472
- * @example client.publish('topic', 'message', console.log);
473
- */
474
- MqttClient.prototype.publish = function (topic, message, opts, callback) {
475
- debug('publish :: message `%s` to topic `%s`', message, topic)
476
- var packet
477
- var options = this.options
478
-
479
- // .publish(topic, payload, cb);
480
- if (typeof opts === 'function') {
481
- callback = opts
482
- opts = null
483
- }
484
-
485
- // default opts
486
- var defaultOpts = {qos: 0, retain: false, dup: false}
487
- opts = xtend(defaultOpts, opts)
488
-
489
- if (this._checkDisconnecting(callback)) {
490
- return this
491
- }
492
-
493
- packet = {
494
- cmd: 'publish',
495
- topic: topic,
496
- payload: message,
497
- qos: opts.qos,
498
- retain: opts.retain,
499
- messageId: this._nextId(),
500
- dup: opts.dup
501
- }
502
-
503
- if (options.protocolVersion === 5) {
504
- packet.properties = opts.properties
505
- if ((!options.properties && packet.properties && packet.properties.topicAlias) || ((opts.properties && options.properties) &&
506
- ((opts.properties.topicAlias && options.properties.topicAliasMaximum && opts.properties.topicAlias > options.properties.topicAliasMaximum) ||
507
- (!options.properties.topicAliasMaximum && opts.properties.topicAlias)))) {
508
- /*
509
- if we are don`t setup topic alias or
510
- topic alias maximum less than topic alias or
511
- server don`t give topic alias maximum,
512
- we are removing topic alias from packet
513
- */
514
- delete packet.properties.topicAlias
515
- }
516
- }
517
-
518
- debug('publish :: qos', opts.qos)
519
- switch (opts.qos) {
520
- case 1:
521
- case 2:
522
- // Add to callbacks
523
- this.outgoing[packet.messageId] = {
524
- volatile: false,
525
- cb: callback || nop
526
- }
527
- if (this._storeProcessing) {
528
- debug('_storeProcessing enabled')
529
- this._packetIdsDuringStoreProcessing[packet.messageId] = false
530
- this._storePacket(packet, undefined, opts.cbStorePut)
531
- } else {
532
- debug('MqttClient:publish: packet cmd: %s', packet.cmd)
533
- this._sendPacket(packet, undefined, opts.cbStorePut)
534
- }
535
- break
536
- default:
537
- if (this._storeProcessing) {
538
- debug('_storeProcessing enabled')
539
- this._storePacket(packet, callback, opts.cbStorePut)
540
- } else {
541
- debug('MqttClient:publish: packet cmd: %s', packet.cmd)
542
- this._sendPacket(packet, callback, opts.cbStorePut)
543
- }
544
- break
545
- }
546
-
547
- return this
548
- }
549
-
550
- /**
551
- * subscribe - subscribe to <topic>
552
- *
553
- * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
554
- * @param {Object} [opts] - optional subscription options, includes:
555
- * {Number} qos - subscribe qos level
556
- * @param {Function} [callback] - function(err, granted){} where:
557
- * {Error} err - subscription error (none at the moment!)
558
- * {Array} granted - array of {topic: 't', qos: 0}
559
- * @returns {MqttClient} this - for chaining
560
- * @api public
561
- * @example client.subscribe('topic');
562
- * @example client.subscribe('topic', {qos: 1});
563
- * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
564
- * @example client.subscribe('topic', console.log);
565
- */
566
- MqttClient.prototype.subscribe = function () {
567
- var packet
568
- var args = new Array(arguments.length)
569
- for (var i = 0; i < arguments.length; i++) {
570
- args[i] = arguments[i]
571
- }
572
- var subs = []
573
- var obj = args.shift()
574
- var resubscribe = obj.resubscribe
575
- var callback = args.pop() || nop
576
- var opts = args.pop()
577
- var invalidTopic
578
- var that = this
579
- var version = this.options.protocolVersion
580
-
581
- delete obj.resubscribe
582
-
583
- if (typeof obj === 'string') {
584
- obj = [obj]
585
- }
586
-
587
- if (typeof callback !== 'function') {
588
- opts = callback
589
- callback = nop
590
- }
591
-
592
- invalidTopic = validations.validateTopics(obj)
593
- if (invalidTopic !== null) {
594
- setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
595
- return this
596
- }
597
-
598
- if (this._checkDisconnecting(callback)) {
599
- debug('subscribe: discconecting true')
600
- return this
601
- }
602
-
603
- var defaultOpts = {
604
- qos: 0
605
- }
606
- if (version === 5) {
607
- defaultOpts.nl = false
608
- defaultOpts.rap = false
609
- defaultOpts.rh = 0
610
- }
611
- opts = xtend(defaultOpts, opts)
612
-
613
- if (Array.isArray(obj)) {
614
- obj.forEach(function (topic) {
615
- debug('subscribe: array topic %s', topic)
616
- if (!that._resubscribeTopics.hasOwnProperty(topic) ||
617
- that._resubscribeTopics[topic].qos < opts.qos ||
618
- resubscribe) {
619
- var currentOpts = {
620
- topic: topic,
621
- qos: opts.qos
622
- }
623
- if (version === 5) {
624
- currentOpts.nl = opts.nl
625
- currentOpts.rap = opts.rap
626
- currentOpts.rh = opts.rh
627
- currentOpts.properties = opts.properties
628
- }
629
- debug('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos)
630
- subs.push(currentOpts)
631
- }
632
- })
633
- } else {
634
- Object
635
- .keys(obj)
636
- .forEach(function (k) {
637
- debug('subscribe: object topic %s', k)
638
- if (!that._resubscribeTopics.hasOwnProperty(k) ||
639
- that._resubscribeTopics[k].qos < obj[k].qos ||
640
- resubscribe) {
641
- var currentOpts = {
642
- topic: k,
643
- qos: obj[k].qos
644
- }
645
- if (version === 5) {
646
- currentOpts.nl = obj[k].nl
647
- currentOpts.rap = obj[k].rap
648
- currentOpts.rh = obj[k].rh
649
- currentOpts.properties = opts.properties
650
- }
651
- debug('subscribe: pushing `%s` to subs list', currentOpts)
652
- subs.push(currentOpts)
653
- }
654
- })
655
- }
656
-
657
- packet = {
658
- cmd: 'subscribe',
659
- subscriptions: subs,
660
- qos: 1,
661
- retain: false,
662
- dup: false,
663
- messageId: this._nextId()
664
- }
665
-
666
- if (opts.properties) {
667
- packet.properties = opts.properties
668
- }
669
-
670
- if (!subs.length) {
671
- callback(null, [])
672
- return
673
- }
674
-
675
- // subscriptions to resubscribe to in case of disconnect
676
- if (this.options.resubscribe) {
677
- debug('subscribe :: resubscribe true')
678
- var topics = []
679
- subs.forEach(function (sub) {
680
- if (that.options.reconnectPeriod > 0) {
681
- var topic = { qos: sub.qos }
682
- if (version === 5) {
683
- topic.nl = sub.nl || false
684
- topic.rap = sub.rap || false
685
- topic.rh = sub.rh || 0
686
- topic.properties = sub.properties
687
- }
688
- that._resubscribeTopics[sub.topic] = topic
689
- topics.push(sub.topic)
690
- }
691
- })
692
- that.messageIdToTopic[packet.messageId] = topics
693
- }
694
-
695
- this.outgoing[packet.messageId] = {
696
- volatile: true,
697
- cb: function (err, packet) {
698
- if (!err) {
699
- var granted = packet.granted
700
- for (var i = 0; i < granted.length; i += 1) {
701
- subs[i].qos = granted[i]
702
- }
703
- }
704
-
705
- callback(err, subs)
706
- }
707
- }
708
- debug('subscribe :: call _sendPacket')
709
- this._sendPacket(packet)
710
-
711
- return this
712
- }
713
-
714
- /**
715
- * unsubscribe - unsubscribe from topic(s)
716
- *
717
- * @param {String, Array} topic - topics to unsubscribe from
718
- * @param {Object} [opts] - optional subscription options, includes:
719
- * {Object} properties - properties of unsubscribe packet
720
- * @param {Function} [callback] - callback fired on unsuback
721
- * @returns {MqttClient} this - for chaining
722
- * @api public
723
- * @example client.unsubscribe('topic');
724
- * @example client.unsubscribe('topic', console.log);
725
- */
726
- MqttClient.prototype.unsubscribe = function () {
727
- var packet = {
728
- cmd: 'unsubscribe',
729
- qos: 1,
730
- messageId: this._nextId()
731
- }
732
- var that = this
733
- var args = new Array(arguments.length)
734
- for (var i = 0; i < arguments.length; i++) {
735
- args[i] = arguments[i]
736
- }
737
- var topic = args.shift()
738
- var callback = args.pop() || nop
739
- var opts = args.pop()
740
-
741
- if (typeof topic === 'string') {
742
- topic = [topic]
743
- }
744
-
745
- if (typeof callback !== 'function') {
746
- opts = callback
747
- callback = nop
748
- }
749
-
750
- if (this._checkDisconnecting(callback)) {
751
- return this
752
- }
753
-
754
- if (typeof topic === 'string') {
755
- packet.unsubscriptions = [topic]
756
- } else if (Array.isArray(topic)) {
757
- packet.unsubscriptions = topic
758
- }
759
-
760
- if (this.options.resubscribe) {
761
- packet.unsubscriptions.forEach(function (topic) {
762
- delete that._resubscribeTopics[topic]
763
- })
764
- }
765
-
766
- if (typeof opts === 'object' && opts.properties) {
767
- packet.properties = opts.properties
768
- }
769
-
770
- this.outgoing[packet.messageId] = {
771
- volatile: true,
772
- cb: callback
773
- }
774
-
775
- debug('unsubscribe: call _sendPacket')
776
- this._sendPacket(packet)
777
-
778
- return this
779
- }
780
-
781
- /**
782
- * end - close connection
783
- *
784
- * @returns {MqttClient} this - for chaining
785
- * @param {Boolean} force - do not wait for all in-flight messages to be acked
786
- * @param {Object} opts - added to the disconnect packet
787
- * @param {Function} cb - called when the client has been closed
788
- *
789
- * @api public
790
- */
791
- MqttClient.prototype.end = function (force, opts, cb) {
792
- var that = this
793
-
794
- debug('end :: (%s)', this.options.clientId)
795
-
796
- if (force == null || typeof force !== 'boolean') {
797
- cb = opts || nop
798
- opts = force
799
- force = false
800
- if (typeof opts !== 'object') {
801
- cb = opts
802
- opts = null
803
- if (typeof cb !== 'function') {
804
- cb = nop
805
- }
806
- }
807
- }
808
-
809
- if (typeof opts !== 'object') {
810
- cb = opts
811
- opts = null
812
- }
813
-
814
- debug('end :: cb? %s', !!cb)
815
- cb = cb || nop
816
-
817
- function closeStores () {
818
- debug('end :: closeStores: closing incoming and outgoing stores')
819
- that.disconnected = true
820
- that.incomingStore.close(function (e1) {
821
- that.outgoingStore.close(function (e2) {
822
- debug('end :: closeStores: emitting end')
823
- that.emit('end')
824
- if (cb) {
825
- let err = e1 || e2
826
- debug('end :: closeStores: invoking callback with args')
827
- cb(err)
828
- }
829
- })
830
- })
831
- if (that._deferredReconnect) {
832
- that._deferredReconnect()
833
- }
834
- }
835
-
836
- function finish () {
837
- // defer closesStores of an I/O cycle,
838
- // just to make sure things are
839
- // ok for websockets
840
- debug('end :: (%s) :: finish :: calling _cleanUp with force %s', that.options.clientId, force)
841
- that._cleanUp(force, () => {
842
- debug('end :: finish :: calling process.nextTick on closeStores')
843
- // var boundProcess = nextTick.bind(null, closeStores)
844
- nextTick(closeStores.bind(that))
845
- }, opts)
846
- }
847
-
848
- if (this.disconnecting) {
849
- cb()
850
- return this
851
- }
852
-
853
- this._clearReconnect()
854
-
855
- this.disconnecting = true
856
-
857
- if (!force && Object.keys(this.outgoing).length > 0) {
858
- // wait 10ms, just to be sure we received all of it
859
- debug('end :: (%s) :: calling finish in 10ms once outgoing is empty', that.options.clientId)
860
- this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
861
- } else {
862
- debug('end :: (%s) :: immediately calling finish', that.options.clientId)
863
- finish()
864
- }
865
-
866
- return this
867
- }
868
-
869
- /**
870
- * removeOutgoingMessage - remove a message in outgoing store
871
- * the outgoing callback will be called withe Error('Message removed') if the message is removed
872
- *
873
- * @param {Number} messageId - messageId to remove message
874
- * @returns {MqttClient} this - for chaining
875
- * @api public
876
- *
877
- * @example client.removeOutgoingMessage(client.getLastMessageId());
878
- */
879
- MqttClient.prototype.removeOutgoingMessage = function (messageId) {
880
- var cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
881
- delete this.outgoing[messageId]
882
- this.outgoingStore.del({messageId: messageId}, function () {
883
- cb(new Error('Message removed'))
884
- })
885
- return this
886
- }
887
-
888
- /**
889
- * reconnect - connect again using the same options as connect()
890
- *
891
- * @param {Object} [opts] - optional reconnect options, includes:
892
- * {Store} incomingStore - a store for the incoming packets
893
- * {Store} outgoingStore - a store for the outgoing packets
894
- * if opts is not given, current stores are used
895
- * @returns {MqttClient} this - for chaining
896
- *
897
- * @api public
898
- */
899
- MqttClient.prototype.reconnect = function (opts) {
900
- debug('client reconnect')
901
- var that = this
902
- var f = function () {
903
- if (opts) {
904
- that.options.incomingStore = opts.incomingStore
905
- that.options.outgoingStore = opts.outgoingStore
906
- } else {
907
- that.options.incomingStore = null
908
- that.options.outgoingStore = null
909
- }
910
- that.incomingStore = that.options.incomingStore || new Store()
911
- that.outgoingStore = that.options.outgoingStore || new Store()
912
- that.disconnecting = false
913
- that.disconnected = false
914
- that._deferredReconnect = null
915
- that._reconnect()
916
- }
917
-
918
- if (this.disconnecting && !this.disconnected) {
919
- this._deferredReconnect = f
920
- } else {
921
- f()
922
- }
923
- return this
924
- }
925
-
926
- /**
927
- * _reconnect - implement reconnection
928
- * @api privateish
929
- */
930
- MqttClient.prototype._reconnect = function () {
931
- debug('_reconnect: emitting reconnect to client')
932
- this.emit('reconnect')
933
- if (this.connected) {
934
- this.end(() => { this._setupStream() })
935
- debug('client already connected. disconnecting first.')
936
- } else {
937
- debug('_reconnect: calling _setupStream')
938
- this._setupStream()
939
- }
940
- }
941
-
942
- /**
943
- * _setupReconnect - setup reconnect timer
944
- */
945
- MqttClient.prototype._setupReconnect = function () {
946
- var that = this
947
-
948
- if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
949
- if (!this.reconnecting) {
950
- debug('_setupReconnect :: emit `offline` state')
951
- this.emit('offline')
952
- debug('_setupReconnect :: set `reconnecting` to `true`')
953
- this.reconnecting = true
954
- }
955
- debug('_setupReconnect :: setting reconnectTimer for %d ms', that.options.reconnectPeriod)
956
- that.reconnectTimer = setInterval(function () {
957
- debug('reconnectTimer :: reconnect triggered!')
958
- that._reconnect()
959
- }, that.options.reconnectPeriod)
960
- } else {
961
- debug('_setupReconnect :: doing nothing...')
962
- }
963
- }
964
-
965
- /**
966
- * _clearReconnect - clear the reconnect timer
967
- */
968
- MqttClient.prototype._clearReconnect = function () {
969
- debug('_clearReconnect : clearing reconnect timer')
970
- if (this.reconnectTimer) {
971
- clearInterval(this.reconnectTimer)
972
- this.reconnectTimer = null
973
- }
974
- }
975
-
976
- /**
977
- * _cleanUp - clean up on connection end
978
- * @api private
979
- */
980
- MqttClient.prototype._cleanUp = function (forced, done) {
981
- var opts = arguments[2]
982
- if (done) {
983
- debug('_cleanUp :: done callback provided for on stream close')
984
- this.stream.on('close', done)
985
- }
986
-
987
- debug('_cleanUp :: forced? %s', forced)
988
- if (forced) {
989
- if ((this.options.reconnectPeriod === 0) && this.options.clean) {
990
- flush(this.outgoing)
991
- }
992
- debug('_cleanUp :: (%s) :: destroying stream', this.options.clientId)
993
- this.stream.destroy()
994
- } else {
995
- var packet = xtend({ cmd: 'disconnect' }, opts)
996
- debug('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId)
997
- this._sendPacket(
998
- packet,
999
- setImmediate.bind(
1000
- null,
1001
- this.stream.end.bind(this.stream)
1002
- )
1003
- )
1004
- }
1005
-
1006
- if (!this.disconnecting) {
1007
- debug('_cleanUp :: client not disconnecting. Clearing and resetting reconnect.')
1008
- this._clearReconnect()
1009
- this._setupReconnect()
1010
- }
1011
-
1012
- if (this.pingTimer !== null) {
1013
- debug('_cleanUp :: clearing pingTimer')
1014
- this.pingTimer.clear()
1015
- this.pingTimer = null
1016
- }
1017
-
1018
- if (done && !this.connected) {
1019
- debug('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId)
1020
- this.stream.removeListener('close', done)
1021
- done()
1022
- }
1023
- }
1024
-
1025
- /**
1026
- * _sendPacket - send or queue a packet
1027
- * @param {Object} packet - packet options
1028
- * @param {Function} cb - callback when the packet is sent
1029
- * @param {Function} cbStorePut - called when message is put into outgoingStore
1030
- * @api private
1031
- */
1032
- MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {
1033
- debug('_sendPacket :: (%s) :: start', this.options.clientId)
1034
- cbStorePut = cbStorePut || nop
1035
-
1036
- if (!this.connected) {
1037
- debug('_sendPacket :: client not connected. Storing packet offline.')
1038
- this._storePacket(packet, cb, cbStorePut)
1039
- return
1040
- }
1041
-
1042
- // When sending a packet, reschedule the ping timer
1043
- this._shiftPingInterval()
1044
-
1045
- switch (packet.cmd) {
1046
- case 'publish':
1047
- break
1048
- case 'pubrel':
1049
- storeAndSend(this, packet, cb, cbStorePut)
1050
- return
1051
- default:
1052
- sendPacket(this, packet, cb)
1053
- return
1054
- }
1055
-
1056
- switch (packet.qos) {
1057
- case 2:
1058
- case 1:
1059
- storeAndSend(this, packet, cb, cbStorePut)
1060
- break
1061
- /**
1062
- * no need of case here since it will be caught by default
1063
- * and jshint comply that before default it must be a break
1064
- * anyway it will result in -1 evaluation
1065
- */
1066
- case 0:
1067
- /* falls through */
1068
- default:
1069
- sendPacket(this, packet, cb)
1070
- break
1071
- }
1072
- debug('_sendPacket :: (%s) :: end', this.options.clientId)
1073
- }
1074
-
1075
- /**
1076
- * _storePacket - queue a packet
1077
- * @param {Object} packet - packet options
1078
- * @param {Function} cb - callback when the packet is sent
1079
- * @param {Function} cbStorePut - called when message is put into outgoingStore
1080
- * @api private
1081
- */
1082
- MqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {
1083
- debug('_storePacket :: packet: %o', packet)
1084
- debug('_storePacket :: cb? %s', !!cb)
1085
- cbStorePut = cbStorePut || nop
1086
-
1087
- // check that the packet is not a qos of 0, or that the command is not a publish
1088
- if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
1089
- this.queue.push({ packet: packet, cb: cb })
1090
- } else if (packet.qos > 0) {
1091
- cb = this.outgoing[packet.messageId] ? this.outgoing[packet.messageId].cb : null
1092
- this.outgoingStore.put(packet, function (err) {
1093
- if (err) {
1094
- return cb && cb(err)
1095
- }
1096
- cbStorePut()
1097
- })
1098
- } else if (cb) {
1099
- cb(new Error('No connection to broker'))
1100
- }
1101
- }
1102
-
1103
- /**
1104
- * _setupPingTimer - setup the ping timer
1105
- *
1106
- * @api private
1107
- */
1108
- MqttClient.prototype._setupPingTimer = function () {
1109
- debug('_setupPingTimer :: keepalive %d (seconds)', this.options.keepalive)
1110
- var that = this
1111
-
1112
- if (!this.pingTimer && this.options.keepalive) {
1113
- this.pingResp = true
1114
- this.pingTimer = reInterval(function () {
1115
- that._checkPing()
1116
- }, this.options.keepalive * 1000)
1117
- }
1118
- }
1119
-
1120
- /**
1121
- * _shiftPingInterval - reschedule the ping interval
1122
- *
1123
- * @api private
1124
- */
1125
- MqttClient.prototype._shiftPingInterval = function () {
1126
- if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
1127
- this.pingTimer.reschedule(this.options.keepalive * 1000)
1128
- }
1129
- }
1130
- /**
1131
- * _checkPing - check if a pingresp has come back, and ping the server again
1132
- *
1133
- * @api private
1134
- */
1135
- MqttClient.prototype._checkPing = function () {
1136
- debug('_checkPing :: checking ping...')
1137
- if (this.pingResp) {
1138
- debug('_checkPing :: ping response received. Clearing flag and sending `pingreq`')
1139
- this.pingResp = false
1140
- this._sendPacket({ cmd: 'pingreq' })
1141
- } else {
1142
- // do a forced cleanup since socket will be in bad shape
1143
- debug('_checkPing :: calling _cleanUp with force true')
1144
- this._cleanUp(true)
1145
- }
1146
- }
1147
-
1148
- /**
1149
- * _handlePingresp - handle a pingresp
1150
- *
1151
- * @api private
1152
- */
1153
- MqttClient.prototype._handlePingresp = function () {
1154
- this.pingResp = true
1155
- }
1156
-
1157
- /**
1158
- * _handleConnack
1159
- *
1160
- * @param {Object} packet
1161
- * @api private
1162
- */
1163
- MqttClient.prototype._handleConnack = function (packet) {
1164
- debug('_handleConnack')
1165
- var options = this.options
1166
- var version = options.protocolVersion
1167
- var rc = version === 5 ? packet.reasonCode : packet.returnCode
1168
-
1169
- clearTimeout(this.connackTimer)
1170
-
1171
- if (packet.properties) {
1172
- if (packet.properties.topicAliasMaximum) {
1173
- if (!options.properties) { options.properties = {} }
1174
- options.properties.topicAliasMaximum = packet.properties.topicAliasMaximum
1175
- }
1176
- if (packet.properties.serverKeepAlive && options.keepalive) {
1177
- options.keepalive = packet.properties.serverKeepAlive
1178
- this._shiftPingInterval()
1179
- }
1180
- if (packet.properties.maximumPacketSize) {
1181
- if (!options.properties) { options.properties = {} }
1182
- options.properties.maximumPacketSize = packet.properties.maximumPacketSize
1183
- }
1184
- }
1185
-
1186
- if (rc === 0) {
1187
- this.reconnecting = false
1188
- this._onConnect(packet)
1189
- } else if (rc > 0) {
1190
- var err = new Error('Connection refused: ' + errors[rc])
1191
- err.code = rc
1192
- this.emit('error', err)
1193
- }
1194
- }
1195
-
1196
- /**
1197
- * _handlePublish
1198
- *
1199
- * @param {Object} packet
1200
- * @api private
1201
- */
1202
- /*
1203
- those late 2 case should be rewrite to comply with coding style:
1204
-
1205
- case 1:
1206
- case 0:
1207
- // do not wait sending a puback
1208
- // no callback passed
1209
- if (1 === qos) {
1210
- this._sendPacket({
1211
- cmd: 'puback',
1212
- messageId: messageId
1213
- });
1214
- }
1215
- // emit the message event for both qos 1 and 0
1216
- this.emit('message', topic, message, packet);
1217
- this.handleMessage(packet, done);
1218
- break;
1219
- default:
1220
- // do nothing but every switch mus have a default
1221
- // log or throw an error about unknown qos
1222
- break;
1223
-
1224
- for now i just suppressed the warnings
1225
- */
1226
- MqttClient.prototype._handlePublish = function (packet, done) {
1227
- debug('_handlePublish: packet %o', packet)
1228
- done = typeof done !== 'undefined' ? done : nop
1229
- var topic = packet.topic.toString()
1230
- var message = packet.payload
1231
- var qos = packet.qos
1232
- var messageId = packet.messageId
1233
- var that = this
1234
- var options = this.options
1235
- var validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
1236
- debug('_handlePublish: qos %d', qos)
1237
- switch (qos) {
1238
- case 2: {
1239
- options.customHandleAcks(topic, message, packet, function (error, code) {
1240
- if (!(error instanceof Error)) {
1241
- code = error
1242
- error = null
1243
- }
1244
- if (error) { return that.emit('error', error) }
1245
- if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }
1246
- if (code) {
1247
- that._sendPacket({cmd: 'pubrec', messageId: messageId, reasonCode: code}, done)
1248
- } else {
1249
- that.incomingStore.put(packet, function () {
1250
- that._sendPacket({cmd: 'pubrec', messageId: messageId}, done)
1251
- })
1252
- }
1253
- })
1254
- break
1255
- }
1256
- case 1: {
1257
- // emit the message event
1258
- options.customHandleAcks(topic, message, packet, function (error, code) {
1259
- if (!(error instanceof Error)) {
1260
- code = error
1261
- error = null
1262
- }
1263
- if (error) { return that.emit('error', error) }
1264
- if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }
1265
- if (!code) { that.emit('message', topic, message, packet) }
1266
- that.handleMessage(packet, function (err) {
1267
- if (err) {
1268
- return done && done(err)
1269
- }
1270
- that._sendPacket({cmd: 'puback', messageId: messageId, reasonCode: code}, done)
1271
- })
1272
- })
1273
- break
1274
- }
1275
- case 0:
1276
- // emit the message event
1277
- this.emit('message', topic, message, packet)
1278
- this.handleMessage(packet, done)
1279
- break
1280
- default:
1281
- // do nothing
1282
- debug('_handlePublish: unknown QoS. Doing nothing.')
1283
- // log or throw an error about unknown qos
1284
- break
1285
- }
1286
- }
1287
-
1288
- /**
1289
- * Handle messages with backpressure support, one at a time.
1290
- * Override at will.
1291
- *
1292
- * @param Packet packet the packet
1293
- * @param Function callback call when finished
1294
- * @api public
1295
- */
1296
- MqttClient.prototype.handleMessage = function (packet, callback) {
1297
- callback()
1298
- }
1299
-
1300
- /**
1301
- * _handleAck
1302
- *
1303
- * @param {Object} packet
1304
- * @api private
1305
- */
1306
-
1307
- MqttClient.prototype._handleAck = function (packet) {
1308
- /* eslint no-fallthrough: "off" */
1309
- var messageId = packet.messageId
1310
- var type = packet.cmd
1311
- var response = null
1312
- var cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
1313
- var that = this
1314
- var err
1315
-
1316
- if (!cb) {
1317
- debug('_handleAck :: Server sent an ack in error. Ignoring.')
1318
- // Server sent an ack in error, ignore it.
1319
- return
1320
- }
1321
-
1322
- // Process
1323
- debug('_handleAck :: packet type', type)
1324
- switch (type) {
1325
- case 'pubcomp':
1326
- // same thing as puback for QoS 2
1327
- case 'puback':
1328
- var pubackRC = packet.reasonCode
1329
- // Callback - we're done
1330
- if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
1331
- err = new Error('Publish error: ' + errors[pubackRC])
1332
- err.code = pubackRC
1333
- cb(err, packet)
1334
- }
1335
- delete this.outgoing[messageId]
1336
- this.outgoingStore.del(packet, cb)
1337
- break
1338
- case 'pubrec':
1339
- response = {
1340
- cmd: 'pubrel',
1341
- qos: 2,
1342
- messageId: messageId
1343
- }
1344
- var pubrecRC = packet.reasonCode
1345
-
1346
- if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
1347
- err = new Error('Publish error: ' + errors[pubrecRC])
1348
- err.code = pubrecRC
1349
- cb(err, packet)
1350
- } else {
1351
- this._sendPacket(response)
1352
- }
1353
- break
1354
- case 'suback':
1355
- delete this.outgoing[messageId]
1356
- for (var grantedI = 0; grantedI < packet.granted.length; grantedI++) {
1357
- if ((packet.granted[grantedI] & 0x80) !== 0) {
1358
- // suback with Failure status
1359
- var topics = this.messageIdToTopic[messageId]
1360
- if (topics) {
1361
- topics.forEach(function (topic) {
1362
- delete that._resubscribeTopics[topic]
1363
- })
1364
- }
1365
- }
1366
- }
1367
- cb(null, packet)
1368
- break
1369
- case 'unsuback':
1370
- delete this.outgoing[messageId]
1371
- cb(null)
1372
- break
1373
- default:
1374
- that.emit('error', new Error('unrecognized packet type'))
1375
- }
1376
-
1377
- if (this.disconnecting &&
1378
- Object.keys(this.outgoing).length === 0) {
1379
- this.emit('outgoingEmpty')
1380
- }
1381
- }
1382
-
1383
- /**
1384
- * _handlePubrel
1385
- *
1386
- * @param {Object} packet
1387
- * @api private
1388
- */
1389
- MqttClient.prototype._handlePubrel = function (packet, callback) {
1390
- debug('handling pubrel packet')
1391
- callback = typeof callback !== 'undefined' ? callback : nop
1392
- var messageId = packet.messageId
1393
- var that = this
1394
-
1395
- var comp = {cmd: 'pubcomp', messageId: messageId}
1396
-
1397
- that.incomingStore.get(packet, function (err, pub) {
1398
- if (!err) {
1399
- that.emit('message', pub.topic, pub.payload, pub)
1400
- that.handleMessage(pub, function (err) {
1401
- if (err) {
1402
- return callback(err)
1403
- }
1404
- that.incomingStore.del(pub, nop)
1405
- that._sendPacket(comp, callback)
1406
- })
1407
- } else {
1408
- that._sendPacket(comp, callback)
1409
- }
1410
- })
1411
- }
1412
-
1413
- /**
1414
- * _handleDisconnect
1415
- *
1416
- * @param {Object} packet
1417
- * @api private
1418
- */
1419
- MqttClient.prototype._handleDisconnect = function (packet) {
1420
- this.emit('disconnect', packet)
1421
- }
1422
-
1423
- /**
1424
- * _nextId
1425
- * @return unsigned int
1426
- */
1427
- MqttClient.prototype._nextId = function () {
1428
- // id becomes current state of this.nextId and increments afterwards
1429
- var id = this.nextId++
1430
- // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
1431
- if (this.nextId === 65536) {
1432
- this.nextId = 1
1433
- }
1434
- return id
1435
- }
1436
-
1437
- /**
1438
- * getLastMessageId
1439
- * @return unsigned int
1440
- */
1441
- MqttClient.prototype.getLastMessageId = function () {
1442
- return (this.nextId === 1) ? 65535 : (this.nextId - 1)
1443
- }
1444
-
1445
- /**
1446
- * _resubscribe
1447
- * @api private
1448
- */
1449
- MqttClient.prototype._resubscribe = function (connack) {
1450
- debug('_resubscribe')
1451
- var _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
1452
- if (!this._firstConnection &&
1453
- (this.options.clean || (this.options.protocolVersion === 5 && !connack.sessionPresent)) &&
1454
- _resubscribeTopicsKeys.length > 0) {
1455
- if (this.options.resubscribe) {
1456
- if (this.options.protocolVersion === 5) {
1457
- debug('_resubscribe: protocolVersion 5')
1458
- for (var topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {
1459
- var resubscribeTopic = {}
1460
- resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]
1461
- resubscribeTopic.resubscribe = true
1462
- this.subscribe(resubscribeTopic, {properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties})
1463
- }
1464
- } else {
1465
- this._resubscribeTopics.resubscribe = true
1466
- this.subscribe(this._resubscribeTopics)
1467
- }
1468
- } else {
1469
- this._resubscribeTopics = {}
1470
- }
1471
- }
1472
-
1473
- this._firstConnection = false
1474
- }
1475
-
1476
- /**
1477
- * _onConnect
1478
- *
1479
- * @api private
1480
- */
1481
- MqttClient.prototype._onConnect = function (packet) {
1482
- if (this.disconnected) {
1483
- this.emit('connect', packet)
1484
- return
1485
- }
1486
-
1487
- var that = this
1488
-
1489
- this._setupPingTimer()
1490
- this._resubscribe(packet)
1491
-
1492
- this.connected = true
1493
-
1494
- function startStreamProcess () {
1495
- var outStore = that.outgoingStore.createStream()
1496
-
1497
- function clearStoreProcessing () {
1498
- that._storeProcessing = false
1499
- that._packetIdsDuringStoreProcessing = {}
1500
- }
1501
-
1502
- that.once('close', remove)
1503
- outStore.on('error', function (err) {
1504
- clearStoreProcessing()
1505
- that.removeListener('close', remove)
1506
- that.emit('error', err)
1507
- })
1508
-
1509
- function remove () {
1510
- outStore.destroy()
1511
- outStore = null
1512
- clearStoreProcessing()
1513
- }
1514
-
1515
- function storeDeliver () {
1516
- // edge case, we wrapped this twice
1517
- if (!outStore) {
1518
- return
1519
- }
1520
- that._storeProcessing = true
1521
-
1522
- var packet = outStore.read(1)
1523
-
1524
- var cb
1525
-
1526
- if (!packet) {
1527
- // read when data is available in the future
1528
- outStore.once('readable', storeDeliver)
1529
- return
1530
- }
1531
-
1532
- // Skip already processed store packets
1533
- if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
1534
- storeDeliver()
1535
- return
1536
- }
1537
-
1538
- // Avoid unnecessary stream read operations when disconnected
1539
- if (!that.disconnecting && !that.reconnectTimer) {
1540
- cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null
1541
- that.outgoing[packet.messageId] = {
1542
- volatile: false,
1543
- cb: function (err, status) {
1544
- // Ensure that the original callback passed in to publish gets invoked
1545
- if (cb) {
1546
- cb(err, status)
1547
- }
1548
-
1549
- storeDeliver()
1550
- }
1551
- }
1552
- that._packetIdsDuringStoreProcessing[packet.messageId] = true
1553
- that._sendPacket(packet)
1554
- } else if (outStore.destroy) {
1555
- outStore.destroy()
1556
- }
1557
- }
1558
-
1559
- outStore.on('end', function () {
1560
- var allProcessed = true
1561
- for (var id in that._packetIdsDuringStoreProcessing) {
1562
- if (!that._packetIdsDuringStoreProcessing[id]) {
1563
- allProcessed = false
1564
- break
1565
- }
1566
- }
1567
- if (allProcessed) {
1568
- clearStoreProcessing()
1569
- that.removeListener('close', remove)
1570
- that.emit('connect', packet)
1571
- } else {
1572
- startStreamProcess()
1573
- }
1574
- })
1575
- storeDeliver()
1576
- }
1577
- // start flowing
1578
- startStreamProcess()
1579
- }
1580
-
1581
- module.exports = MqttClient
1
+ 'use strict'
2
+
3
+ /**
4
+ * Module dependencies
5
+ */
6
+ var EventEmitter = require('events').EventEmitter
7
+ var Store = require('./store')
8
+ var mqttPacket = require('mqtt-packet')
9
+ var Writable = require('readable-stream').Writable
10
+ var inherits = require('inherits')
11
+ var reInterval = require('reinterval')
12
+ var validations = require('./validations')
13
+ var xtend = require('xtend')
14
+ var debug = require('debug')('mqttjs:client')
15
+ var nextTick = process ? process.nextTick : function (callback) { setTimeout(callback, 0) }
16
+ var setImmediate = global.setImmediate || function (callback) {
17
+ // works in node v0.8
18
+ nextTick(callback)
19
+ }
20
+ var defaultConnectOptions = {
21
+ keepalive: 60,
22
+ reschedulePings: true,
23
+ protocolId: 'MQTT',
24
+ protocolVersion: 4,
25
+ reconnectPeriod: 1000,
26
+ connectTimeout: 30 * 1000,
27
+ clean: true,
28
+ resubscribe: true
29
+ }
30
+
31
+ var socketErrors = [
32
+ 'ECONNREFUSED',
33
+ 'EADDRINUSE',
34
+ 'ECONNRESET',
35
+ 'ENOTFOUND'
36
+ ]
37
+
38
+ // Other Socket Errors: EADDRINUSE, ECONNRESET, ENOTFOUND.
39
+
40
+ var errors = {
41
+ 0: '',
42
+ 1: 'Unacceptable protocol version',
43
+ 2: 'Identifier rejected',
44
+ 3: 'Server unavailable',
45
+ 4: 'Bad username or password',
46
+ 5: 'Not authorized',
47
+ 16: 'No matching subscribers',
48
+ 17: 'No subscription existed',
49
+ 128: 'Unspecified error',
50
+ 129: 'Malformed Packet',
51
+ 130: 'Protocol Error',
52
+ 131: 'Implementation specific error',
53
+ 132: 'Unsupported Protocol Version',
54
+ 133: 'Client Identifier not valid',
55
+ 134: 'Bad User Name or Password',
56
+ 135: 'Not authorized',
57
+ 136: 'Server unavailable',
58
+ 137: 'Server busy',
59
+ 138: 'Banned',
60
+ 139: 'Server shutting down',
61
+ 140: 'Bad authentication method',
62
+ 141: 'Keep Alive timeout',
63
+ 142: 'Session taken over',
64
+ 143: 'Topic Filter invalid',
65
+ 144: 'Topic Name invalid',
66
+ 145: 'Packet identifier in use',
67
+ 146: 'Packet Identifier not found',
68
+ 147: 'Receive Maximum exceeded',
69
+ 148: 'Topic Alias invalid',
70
+ 149: 'Packet too large',
71
+ 150: 'Message rate too high',
72
+ 151: 'Quota exceeded',
73
+ 152: 'Administrative action',
74
+ 153: 'Payload format invalid',
75
+ 154: 'Retain not supported',
76
+ 155: 'QoS not supported',
77
+ 156: 'Use another server',
78
+ 157: 'Server moved',
79
+ 158: 'Shared Subscriptions not supported',
80
+ 159: 'Connection rate exceeded',
81
+ 160: 'Maximum connect time',
82
+ 161: 'Subscription Identifiers not supported',
83
+ 162: 'Wildcard Subscriptions not supported'
84
+ }
85
+
86
+ function defaultId () {
87
+ return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
88
+ }
89
+
90
+ function sendPacket (client, packet, cb) {
91
+ debug('sendPacket :: packet: %O', packet)
92
+ debug('sendPacket :: emitting `packetsend`')
93
+ client.emit('packetsend', packet)
94
+
95
+ debug('sendPacket :: writing to stream')
96
+ var result = mqttPacket.writeToStream(packet, client.stream, client.options)
97
+ debug('sendPacket :: writeToStream result %s', result)
98
+ if (!result && cb) {
99
+ debug('sendPacket :: handle events on `drain` once through callback.')
100
+ client.stream.once('drain', cb)
101
+ } else if (cb) {
102
+ debug('sendPacket :: invoking cb')
103
+ cb()
104
+ }
105
+ }
106
+
107
+ function flush (queue) {
108
+ if (queue) {
109
+ debug('flush: queue exists? %b', !!(queue))
110
+ Object.keys(queue).forEach(function (messageId) {
111
+ if (typeof queue[messageId].cb === 'function') {
112
+ queue[messageId].cb(new Error('Connection closed'))
113
+ delete queue[messageId]
114
+ }
115
+ })
116
+ }
117
+ }
118
+
119
+ function flushVolatile (queue) {
120
+ if (queue) {
121
+ debug('flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function')
122
+ Object.keys(queue).forEach(function (messageId) {
123
+ if (queue[messageId].volatile && typeof queue[messageId].cb === 'function') {
124
+ queue[messageId].cb(new Error('Connection closed'))
125
+ delete queue[messageId]
126
+ }
127
+ })
128
+ }
129
+ }
130
+
131
+ function storeAndSend (client, packet, cb, cbStorePut) {
132
+ debug('storeAndSend :: store packet with cmd %s to outgoingStore', packet.cmd)
133
+ client.outgoingStore.put(packet, function storedPacket (err) {
134
+ if (err) {
135
+ return cb && cb(err)
136
+ }
137
+ cbStorePut()
138
+ sendPacket(client, packet, cb)
139
+ })
140
+ }
141
+
142
+ function nop (error) {
143
+ debug('nop ::', error)
144
+ }
145
+
146
+ /**
147
+ * MqttClient constructor
148
+ *
149
+ * @param {Stream} stream - stream
150
+ * @param {Object} [options] - connection options
151
+ * (see Connection#connect)
152
+ */
153
+ function MqttClient (streamBuilder, options) {
154
+ var k
155
+ var that = this
156
+
157
+ if (!(this instanceof MqttClient)) {
158
+ return new MqttClient(streamBuilder, options)
159
+ }
160
+
161
+ this.options = options || {}
162
+
163
+ // Defaults
164
+ for (k in defaultConnectOptions) {
165
+ if (typeof this.options[k] === 'undefined') {
166
+ this.options[k] = defaultConnectOptions[k]
167
+ } else {
168
+ this.options[k] = options[k]
169
+ }
170
+ }
171
+
172
+ debug('MqttClient :: options.protocol', options.protocol)
173
+ debug('MqttClient :: options.protocolVersion', options.protocolVersion)
174
+ debug('MqttClient :: options.username', options.username)
175
+ debug('MqttClient :: options.keepalive', options.keepalive)
176
+ debug('MqttClient :: options.reconnectPeriod', options.reconnectPeriod)
177
+ debug('MqttClient :: options.rejectUnauthorized', options.rejectUnauthorized)
178
+
179
+ this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()
180
+
181
+ debug('MqttClient :: clientId', this.options.clientId)
182
+
183
+ this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }
184
+
185
+ this.streamBuilder = streamBuilder
186
+
187
+ // Inflight message storages
188
+ this.outgoingStore = options.outgoingStore || new Store()
189
+ this.incomingStore = options.incomingStore || new Store()
190
+
191
+ // Should QoS zero messages be queued when the connection is broken?
192
+ this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero
193
+
194
+ // map of subscribed topics to support reconnection
195
+ this._resubscribeTopics = {}
196
+
197
+ // map of a subscribe messageId and a topic
198
+ this.messageIdToTopic = {}
199
+
200
+ // Ping timer, setup in _setupPingTimer
201
+ this.pingTimer = null
202
+ // Is the client connected?
203
+ this.connected = false
204
+ // Are we disconnecting?
205
+ this.disconnecting = false
206
+ // Packet queue
207
+ this.queue = []
208
+ // connack timer
209
+ this.connackTimer = null
210
+ // Reconnect timer
211
+ this.reconnectTimer = null
212
+ // Is processing store?
213
+ this._storeProcessing = false
214
+ // Packet Ids are put into the store during store processing
215
+ this._packetIdsDuringStoreProcessing = {}
216
+ /**
217
+ * MessageIDs starting with 1
218
+ * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
219
+ */
220
+ this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
221
+
222
+ // Inflight callbacks
223
+ this.outgoing = {}
224
+
225
+ // True if connection is first time.
226
+ this._firstConnection = true
227
+
228
+ // Send queued packets
229
+ this.on('connect', function () {
230
+ var queue = this.queue
231
+
232
+ function deliver () {
233
+ var entry = queue.shift()
234
+ debug('deliver :: entry %o', entry)
235
+ var packet = null
236
+
237
+ if (!entry) {
238
+ return
239
+ }
240
+
241
+ packet = entry.packet
242
+ debug('deliver :: call _sendPacket for %o', packet)
243
+ that._sendPacket(
244
+ packet,
245
+ function (err) {
246
+ if (entry.cb) {
247
+ entry.cb(err)
248
+ }
249
+ deliver()
250
+ }
251
+ )
252
+ }
253
+
254
+ debug('connect :: sending queued packets')
255
+ deliver()
256
+ })
257
+
258
+ this.on('close', function () {
259
+ debug('close :: connected set to `false`')
260
+ this.connected = false
261
+
262
+ debug('close :: clearing connackTimer')
263
+ clearTimeout(this.connackTimer)
264
+
265
+ debug('close :: clearing ping timer')
266
+ if (that.pingTimer !== null) {
267
+ that.pingTimer.clear()
268
+ that.pingTimer = null
269
+ }
270
+
271
+ debug('close :: calling _setupReconnect')
272
+ this._setupReconnect()
273
+ })
274
+ EventEmitter.call(this)
275
+
276
+ debug('MqttClient :: setting up stream')
277
+ this._setupStream()
278
+ }
279
+ inherits(MqttClient, EventEmitter)
280
+
281
+ /**
282
+ * setup the event handlers in the inner stream.
283
+ *
284
+ * @api private
285
+ */
286
+ MqttClient.prototype._setupStream = function () {
287
+ var connectPacket
288
+ var that = this
289
+ var writable = new Writable()
290
+ var parser = mqttPacket.parser(this.options)
291
+ var completeParse = null
292
+ var packets = []
293
+
294
+ debug('_setupStream :: calling method to clear reconnect')
295
+ this._clearReconnect()
296
+
297
+ debug('_setupStream :: using streamBuilder provided to client to create stream')
298
+ this.stream = this.streamBuilder(this)
299
+
300
+ parser.on('packet', function (packet) {
301
+ debug('parser :: on packet push to packets array.')
302
+ packets.push(packet)
303
+ })
304
+
305
+ function nextTickWork () {
306
+ if (packets.length) {
307
+ nextTick(work)
308
+ } else {
309
+ var done = completeParse
310
+ completeParse = null
311
+ done()
312
+ }
313
+ }
314
+
315
+ function work () {
316
+ debug('work :: getting next packet in queue')
317
+ var packet = packets.shift()
318
+
319
+ if (packet) {
320
+ debug('work :: packet pulled from queue')
321
+ that._handlePacket(packet, nextTickWork)
322
+ } else {
323
+ debug('work :: no packets in queue')
324
+ var done = completeParse
325
+ completeParse = null
326
+ debug('work :: done flag is %s', !!(done))
327
+ if (done) done()
328
+ }
329
+ }
330
+
331
+ writable._write = function (buf, enc, done) {
332
+ completeParse = done
333
+ debug('writable stream :: parsing buffer')
334
+ parser.parse(buf)
335
+ work()
336
+ }
337
+
338
+ function streamErrorHandler (error) {
339
+ debug('streamErrorHandler :: error', error.message)
340
+ if (socketErrors.includes(error.code)) {
341
+ // handle error
342
+ debug('streamErrorHandler :: emitting error')
343
+ that.emit('error', error)
344
+ } else {
345
+ nop(error)
346
+ }
347
+ }
348
+
349
+ debug('_setupStream :: pipe stream to writable stream')
350
+ this.stream.pipe(writable)
351
+
352
+ // Suppress connection errors
353
+ this.stream.on('error', streamErrorHandler)
354
+
355
+ // Echo stream close
356
+ this.stream.on('close', function () {
357
+ debug('(%s)stream :: on close', that.options.clientId)
358
+ flushVolatile(that.outgoing)
359
+ debug('stream: emit close to MqttClient')
360
+ that.emit('close')
361
+ })
362
+
363
+ // Send a connect packet
364
+ debug('_setupStream: sending packet `connect`')
365
+ connectPacket = Object.create(this.options)
366
+ connectPacket.cmd = 'connect'
367
+ // avoid message queue
368
+ sendPacket(this, connectPacket)
369
+
370
+ // Echo connection errors
371
+ parser.on('error', this.emit.bind(this, 'error'))
372
+
373
+ // auth
374
+ if (this.options.properties) {
375
+ if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {
376
+ that.end(() =>
377
+ this.emit('error', new Error('Packet has no Authentication Method')
378
+ ))
379
+ return this
380
+ }
381
+ if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {
382
+ var authPacket = xtend({cmd: 'auth', reasonCode: 0}, this.options.authPacket)
383
+ sendPacket(this, authPacket)
384
+ }
385
+ }
386
+
387
+ // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
388
+ this.stream.setMaxListeners(1000)
389
+
390
+ clearTimeout(this.connackTimer)
391
+ this.connackTimer = setTimeout(function () {
392
+ debug('!!connectTimeout hit!! Calling _cleanUp with force `true`')
393
+ that._cleanUp(true)
394
+ }, this.options.connectTimeout)
395
+ }
396
+
397
+ MqttClient.prototype._handlePacket = function (packet, done) {
398
+ var options = this.options
399
+
400
+ if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {
401
+ this.emit('error', new Error('exceeding packets size ' + packet.cmd))
402
+ this.end({reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' }})
403
+ return this
404
+ }
405
+ debug('_handlePacket :: emitting packetreceive')
406
+ this.emit('packetreceive', packet)
407
+
408
+ switch (packet.cmd) {
409
+ case 'publish':
410
+ this._handlePublish(packet, done)
411
+ break
412
+ case 'puback':
413
+ case 'pubrec':
414
+ case 'pubcomp':
415
+ case 'suback':
416
+ case 'unsuback':
417
+ this._handleAck(packet)
418
+ done()
419
+ break
420
+ case 'pubrel':
421
+ this._handlePubrel(packet, done)
422
+ break
423
+ case 'connack':
424
+ this._handleConnack(packet)
425
+ done()
426
+ break
427
+ case 'pingresp':
428
+ this._handlePingresp(packet)
429
+ done()
430
+ break
431
+ case 'disconnect':
432
+ this._handleDisconnect(packet)
433
+ done()
434
+ break
435
+ default:
436
+ // do nothing
437
+ // maybe we should do an error handling
438
+ // or just log it
439
+ break
440
+ }
441
+ }
442
+
443
+ MqttClient.prototype._checkDisconnecting = function (callback) {
444
+ if (this.disconnecting) {
445
+ if (callback) {
446
+ callback(new Error('client disconnecting'))
447
+ } else {
448
+ this.emit('error', new Error('client disconnecting'))
449
+ }
450
+ }
451
+ return this.disconnecting
452
+ }
453
+
454
+ /**
455
+ * publish - publish <message> to <topic>
456
+ *
457
+ * @param {String} topic - topic to publish to
458
+ * @param {String, Buffer} message - message to publish
459
+ * @param {Object} [opts] - publish options, includes:
460
+ * {Number} qos - qos level to publish on
461
+ * {Boolean} retain - whether or not to retain the message
462
+ * {Boolean} dup - whether or not mark a message as duplicate
463
+ * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
464
+ * @param {Function} [callback] - function(err){}
465
+ * called when publish succeeds or fails
466
+ * @returns {MqttClient} this - for chaining
467
+ * @api public
468
+ *
469
+ * @example client.publish('topic', 'message');
470
+ * @example
471
+ * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
472
+ * @example client.publish('topic', 'message', console.log);
473
+ */
474
+ MqttClient.prototype.publish = function (topic, message, opts, callback) {
475
+ debug('publish :: message `%s` to topic `%s`', message, topic)
476
+ var packet
477
+ var options = this.options
478
+
479
+ // .publish(topic, payload, cb);
480
+ if (typeof opts === 'function') {
481
+ callback = opts
482
+ opts = null
483
+ }
484
+
485
+ // default opts
486
+ var defaultOpts = {qos: 0, retain: false, dup: false}
487
+ opts = xtend(defaultOpts, opts)
488
+
489
+ if (this._checkDisconnecting(callback)) {
490
+ return this
491
+ }
492
+
493
+ packet = {
494
+ cmd: 'publish',
495
+ topic: topic,
496
+ payload: message,
497
+ qos: opts.qos,
498
+ retain: opts.retain,
499
+ messageId: this._nextId(),
500
+ dup: opts.dup
501
+ }
502
+
503
+ if (options.protocolVersion === 5) {
504
+ packet.properties = opts.properties
505
+ if ((!options.properties && packet.properties && packet.properties.topicAlias) || ((opts.properties && options.properties) &&
506
+ ((opts.properties.topicAlias && options.properties.topicAliasMaximum && opts.properties.topicAlias > options.properties.topicAliasMaximum) ||
507
+ (!options.properties.topicAliasMaximum && opts.properties.topicAlias)))) {
508
+ /*
509
+ if we are don`t setup topic alias or
510
+ topic alias maximum less than topic alias or
511
+ server don`t give topic alias maximum,
512
+ we are removing topic alias from packet
513
+ */
514
+ delete packet.properties.topicAlias
515
+ }
516
+ }
517
+
518
+ debug('publish :: qos', opts.qos)
519
+ switch (opts.qos) {
520
+ case 1:
521
+ case 2:
522
+ // Add to callbacks
523
+ this.outgoing[packet.messageId] = {
524
+ volatile: false,
525
+ cb: callback || nop
526
+ }
527
+ if (this._storeProcessing) {
528
+ debug('_storeProcessing enabled')
529
+ this._packetIdsDuringStoreProcessing[packet.messageId] = false
530
+ this._storePacket(packet, undefined, opts.cbStorePut)
531
+ } else {
532
+ debug('MqttClient:publish: packet cmd: %s', packet.cmd)
533
+ this._sendPacket(packet, undefined, opts.cbStorePut)
534
+ }
535
+ break
536
+ default:
537
+ if (this._storeProcessing) {
538
+ debug('_storeProcessing enabled')
539
+ this._storePacket(packet, callback, opts.cbStorePut)
540
+ } else {
541
+ debug('MqttClient:publish: packet cmd: %s', packet.cmd)
542
+ this._sendPacket(packet, callback, opts.cbStorePut)
543
+ }
544
+ break
545
+ }
546
+
547
+ return this
548
+ }
549
+
550
+ /**
551
+ * subscribe - subscribe to <topic>
552
+ *
553
+ * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
554
+ * @param {Object} [opts] - optional subscription options, includes:
555
+ * {Number} qos - subscribe qos level
556
+ * @param {Function} [callback] - function(err, granted){} where:
557
+ * {Error} err - subscription error (none at the moment!)
558
+ * {Array} granted - array of {topic: 't', qos: 0}
559
+ * @returns {MqttClient} this - for chaining
560
+ * @api public
561
+ * @example client.subscribe('topic');
562
+ * @example client.subscribe('topic', {qos: 1});
563
+ * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
564
+ * @example client.subscribe('topic', console.log);
565
+ */
566
+ MqttClient.prototype.subscribe = function () {
567
+ var packet
568
+ var args = new Array(arguments.length)
569
+ for (var i = 0; i < arguments.length; i++) {
570
+ args[i] = arguments[i]
571
+ }
572
+ var subs = []
573
+ var obj = args.shift()
574
+ var resubscribe = obj.resubscribe
575
+ var callback = args.pop() || nop
576
+ var opts = args.pop()
577
+ var invalidTopic
578
+ var that = this
579
+ var version = this.options.protocolVersion
580
+
581
+ delete obj.resubscribe
582
+
583
+ if (typeof obj === 'string') {
584
+ obj = [obj]
585
+ }
586
+
587
+ if (typeof callback !== 'function') {
588
+ opts = callback
589
+ callback = nop
590
+ }
591
+
592
+ invalidTopic = validations.validateTopics(obj)
593
+ if (invalidTopic !== null) {
594
+ setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
595
+ return this
596
+ }
597
+
598
+ if (this._checkDisconnecting(callback)) {
599
+ debug('subscribe: discconecting true')
600
+ return this
601
+ }
602
+
603
+ var defaultOpts = {
604
+ qos: 0
605
+ }
606
+ if (version === 5) {
607
+ defaultOpts.nl = false
608
+ defaultOpts.rap = false
609
+ defaultOpts.rh = 0
610
+ }
611
+ opts = xtend(defaultOpts, opts)
612
+
613
+ if (Array.isArray(obj)) {
614
+ obj.forEach(function (topic) {
615
+ debug('subscribe: array topic %s', topic)
616
+ if (!that._resubscribeTopics.hasOwnProperty(topic) ||
617
+ that._resubscribeTopics[topic].qos < opts.qos ||
618
+ resubscribe) {
619
+ var currentOpts = {
620
+ topic: topic,
621
+ qos: opts.qos
622
+ }
623
+ if (version === 5) {
624
+ currentOpts.nl = opts.nl
625
+ currentOpts.rap = opts.rap
626
+ currentOpts.rh = opts.rh
627
+ currentOpts.properties = opts.properties
628
+ }
629
+ debug('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos)
630
+ subs.push(currentOpts)
631
+ }
632
+ })
633
+ } else {
634
+ Object
635
+ .keys(obj)
636
+ .forEach(function (k) {
637
+ debug('subscribe: object topic %s', k)
638
+ if (!that._resubscribeTopics.hasOwnProperty(k) ||
639
+ that._resubscribeTopics[k].qos < obj[k].qos ||
640
+ resubscribe) {
641
+ var currentOpts = {
642
+ topic: k,
643
+ qos: obj[k].qos
644
+ }
645
+ if (version === 5) {
646
+ currentOpts.nl = obj[k].nl
647
+ currentOpts.rap = obj[k].rap
648
+ currentOpts.rh = obj[k].rh
649
+ currentOpts.properties = opts.properties
650
+ }
651
+ debug('subscribe: pushing `%s` to subs list', currentOpts)
652
+ subs.push(currentOpts)
653
+ }
654
+ })
655
+ }
656
+
657
+ packet = {
658
+ cmd: 'subscribe',
659
+ subscriptions: subs,
660
+ qos: 1,
661
+ retain: false,
662
+ dup: false,
663
+ messageId: this._nextId()
664
+ }
665
+
666
+ if (opts.properties) {
667
+ packet.properties = opts.properties
668
+ }
669
+
670
+ if (!subs.length) {
671
+ callback(null, [])
672
+ return
673
+ }
674
+
675
+ // subscriptions to resubscribe to in case of disconnect
676
+ if (this.options.resubscribe) {
677
+ debug('subscribe :: resubscribe true')
678
+ var topics = []
679
+ subs.forEach(function (sub) {
680
+ if (that.options.reconnectPeriod > 0) {
681
+ var topic = { qos: sub.qos }
682
+ if (version === 5) {
683
+ topic.nl = sub.nl || false
684
+ topic.rap = sub.rap || false
685
+ topic.rh = sub.rh || 0
686
+ topic.properties = sub.properties
687
+ }
688
+ that._resubscribeTopics[sub.topic] = topic
689
+ topics.push(sub.topic)
690
+ }
691
+ })
692
+ that.messageIdToTopic[packet.messageId] = topics
693
+ }
694
+
695
+ this.outgoing[packet.messageId] = {
696
+ volatile: true,
697
+ cb: function (err, packet) {
698
+ if (!err) {
699
+ var granted = packet.granted
700
+ for (var i = 0; i < granted.length; i += 1) {
701
+ subs[i].qos = granted[i]
702
+ }
703
+ }
704
+
705
+ callback(err, subs)
706
+ }
707
+ }
708
+ debug('subscribe :: call _sendPacket')
709
+ this._sendPacket(packet)
710
+
711
+ return this
712
+ }
713
+
714
+ /**
715
+ * unsubscribe - unsubscribe from topic(s)
716
+ *
717
+ * @param {String, Array} topic - topics to unsubscribe from
718
+ * @param {Object} [opts] - optional subscription options, includes:
719
+ * {Object} properties - properties of unsubscribe packet
720
+ * @param {Function} [callback] - callback fired on unsuback
721
+ * @returns {MqttClient} this - for chaining
722
+ * @api public
723
+ * @example client.unsubscribe('topic');
724
+ * @example client.unsubscribe('topic', console.log);
725
+ */
726
+ MqttClient.prototype.unsubscribe = function () {
727
+ var packet = {
728
+ cmd: 'unsubscribe',
729
+ qos: 1,
730
+ messageId: this._nextId()
731
+ }
732
+ var that = this
733
+ var args = new Array(arguments.length)
734
+ for (var i = 0; i < arguments.length; i++) {
735
+ args[i] = arguments[i]
736
+ }
737
+ var topic = args.shift()
738
+ var callback = args.pop() || nop
739
+ var opts = args.pop()
740
+
741
+ if (typeof topic === 'string') {
742
+ topic = [topic]
743
+ }
744
+
745
+ if (typeof callback !== 'function') {
746
+ opts = callback
747
+ callback = nop
748
+ }
749
+
750
+ if (this._checkDisconnecting(callback)) {
751
+ return this
752
+ }
753
+
754
+ if (typeof topic === 'string') {
755
+ packet.unsubscriptions = [topic]
756
+ } else if (Array.isArray(topic)) {
757
+ packet.unsubscriptions = topic
758
+ }
759
+
760
+ if (this.options.resubscribe) {
761
+ packet.unsubscriptions.forEach(function (topic) {
762
+ delete that._resubscribeTopics[topic]
763
+ })
764
+ }
765
+
766
+ if (typeof opts === 'object' && opts.properties) {
767
+ packet.properties = opts.properties
768
+ }
769
+
770
+ this.outgoing[packet.messageId] = {
771
+ volatile: true,
772
+ cb: callback
773
+ }
774
+
775
+ debug('unsubscribe: call _sendPacket')
776
+ this._sendPacket(packet)
777
+
778
+ return this
779
+ }
780
+
781
+ /**
782
+ * end - close connection
783
+ *
784
+ * @returns {MqttClient} this - for chaining
785
+ * @param {Boolean} force - do not wait for all in-flight messages to be acked
786
+ * @param {Object} opts - added to the disconnect packet
787
+ * @param {Function} cb - called when the client has been closed
788
+ *
789
+ * @api public
790
+ */
791
+ MqttClient.prototype.end = function (force, opts, cb) {
792
+ var that = this
793
+
794
+ debug('end :: (%s)', this.options.clientId)
795
+
796
+ if (force == null || typeof force !== 'boolean') {
797
+ cb = opts || nop
798
+ opts = force
799
+ force = false
800
+ if (typeof opts !== 'object') {
801
+ cb = opts
802
+ opts = null
803
+ if (typeof cb !== 'function') {
804
+ cb = nop
805
+ }
806
+ }
807
+ }
808
+
809
+ if (typeof opts !== 'object') {
810
+ cb = opts
811
+ opts = null
812
+ }
813
+
814
+ debug('end :: cb? %s', !!cb)
815
+ cb = cb || nop
816
+
817
+ function closeStores () {
818
+ debug('end :: closeStores: closing incoming and outgoing stores')
819
+ that.disconnected = true
820
+ that.incomingStore.close(function (e1) {
821
+ that.outgoingStore.close(function (e2) {
822
+ debug('end :: closeStores: emitting end')
823
+ that.emit('end')
824
+ if (cb) {
825
+ let err = e1 || e2
826
+ debug('end :: closeStores: invoking callback with args')
827
+ cb(err)
828
+ }
829
+ })
830
+ })
831
+ if (that._deferredReconnect) {
832
+ that._deferredReconnect()
833
+ }
834
+ }
835
+
836
+ function finish () {
837
+ // defer closesStores of an I/O cycle,
838
+ // just to make sure things are
839
+ // ok for websockets
840
+ debug('end :: (%s) :: finish :: calling _cleanUp with force %s', that.options.clientId, force)
841
+ that._cleanUp(force, () => {
842
+ debug('end :: finish :: calling process.nextTick on closeStores')
843
+ // var boundProcess = nextTick.bind(null, closeStores)
844
+ nextTick(closeStores.bind(that))
845
+ }, opts)
846
+ }
847
+
848
+ if (this.disconnecting) {
849
+ cb()
850
+ return this
851
+ }
852
+
853
+ this._clearReconnect()
854
+
855
+ this.disconnecting = true
856
+
857
+ if (!force && Object.keys(this.outgoing).length > 0) {
858
+ // wait 10ms, just to be sure we received all of it
859
+ debug('end :: (%s) :: calling finish in 10ms once outgoing is empty', that.options.clientId)
860
+ this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
861
+ } else {
862
+ debug('end :: (%s) :: immediately calling finish', that.options.clientId)
863
+ finish()
864
+ }
865
+
866
+ return this
867
+ }
868
+
869
+ /**
870
+ * removeOutgoingMessage - remove a message in outgoing store
871
+ * the outgoing callback will be called withe Error('Message removed') if the message is removed
872
+ *
873
+ * @param {Number} messageId - messageId to remove message
874
+ * @returns {MqttClient} this - for chaining
875
+ * @api public
876
+ *
877
+ * @example client.removeOutgoingMessage(client.getLastMessageId());
878
+ */
879
+ MqttClient.prototype.removeOutgoingMessage = function (messageId) {
880
+ var cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
881
+ delete this.outgoing[messageId]
882
+ this.outgoingStore.del({messageId: messageId}, function () {
883
+ cb(new Error('Message removed'))
884
+ })
885
+ return this
886
+ }
887
+
888
+ /**
889
+ * reconnect - connect again using the same options as connect()
890
+ *
891
+ * @param {Object} [opts] - optional reconnect options, includes:
892
+ * {Store} incomingStore - a store for the incoming packets
893
+ * {Store} outgoingStore - a store for the outgoing packets
894
+ * if opts is not given, current stores are used
895
+ * @returns {MqttClient} this - for chaining
896
+ *
897
+ * @api public
898
+ */
899
+ MqttClient.prototype.reconnect = function (opts) {
900
+ debug('client reconnect')
901
+ var that = this
902
+ var f = function () {
903
+ if (opts) {
904
+ that.options.incomingStore = opts.incomingStore
905
+ that.options.outgoingStore = opts.outgoingStore
906
+ } else {
907
+ that.options.incomingStore = null
908
+ that.options.outgoingStore = null
909
+ }
910
+ that.incomingStore = that.options.incomingStore || new Store()
911
+ that.outgoingStore = that.options.outgoingStore || new Store()
912
+ that.disconnecting = false
913
+ that.disconnected = false
914
+ that._deferredReconnect = null
915
+ that._reconnect()
916
+ }
917
+
918
+ if (this.disconnecting && !this.disconnected) {
919
+ this._deferredReconnect = f
920
+ } else {
921
+ f()
922
+ }
923
+ return this
924
+ }
925
+
926
+ /**
927
+ * _reconnect - implement reconnection
928
+ * @api privateish
929
+ */
930
+ MqttClient.prototype._reconnect = function () {
931
+ debug('_reconnect: emitting reconnect to client')
932
+ this.emit('reconnect')
933
+ if (this.connected) {
934
+ this.end(() => { this._setupStream() })
935
+ debug('client already connected. disconnecting first.')
936
+ } else {
937
+ debug('_reconnect: calling _setupStream')
938
+ this._setupStream()
939
+ }
940
+ }
941
+
942
+ /**
943
+ * _setupReconnect - setup reconnect timer
944
+ */
945
+ MqttClient.prototype._setupReconnect = function () {
946
+ var that = this
947
+
948
+ if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
949
+ if (!this.reconnecting) {
950
+ debug('_setupReconnect :: emit `offline` state')
951
+ this.emit('offline')
952
+ debug('_setupReconnect :: set `reconnecting` to `true`')
953
+ this.reconnecting = true
954
+ }
955
+ debug('_setupReconnect :: setting reconnectTimer for %d ms', that.options.reconnectPeriod)
956
+ that.reconnectTimer = setInterval(function () {
957
+ debug('reconnectTimer :: reconnect triggered!')
958
+ that._reconnect()
959
+ }, that.options.reconnectPeriod)
960
+ } else {
961
+ debug('_setupReconnect :: doing nothing...')
962
+ }
963
+ }
964
+
965
+ /**
966
+ * _clearReconnect - clear the reconnect timer
967
+ */
968
+ MqttClient.prototype._clearReconnect = function () {
969
+ debug('_clearReconnect : clearing reconnect timer')
970
+ if (this.reconnectTimer) {
971
+ clearInterval(this.reconnectTimer)
972
+ this.reconnectTimer = null
973
+ }
974
+ }
975
+
976
+ /**
977
+ * _cleanUp - clean up on connection end
978
+ * @api private
979
+ */
980
+ MqttClient.prototype._cleanUp = function (forced, done) {
981
+ var opts = arguments[2]
982
+ if (done) {
983
+ debug('_cleanUp :: done callback provided for on stream close')
984
+ this.stream.on('close', done)
985
+ }
986
+
987
+ debug('_cleanUp :: forced? %s', forced)
988
+ if (forced) {
989
+ if ((this.options.reconnectPeriod === 0) && this.options.clean) {
990
+ flush(this.outgoing)
991
+ }
992
+ debug('_cleanUp :: (%s) :: destroying stream', this.options.clientId)
993
+ this.stream.destroy()
994
+ } else {
995
+ var packet = xtend({ cmd: 'disconnect' }, opts)
996
+ debug('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId)
997
+ this._sendPacket(
998
+ packet,
999
+ setImmediate.bind(
1000
+ null,
1001
+ this.stream.end.bind(this.stream)
1002
+ )
1003
+ )
1004
+ }
1005
+
1006
+ if (!this.disconnecting) {
1007
+ debug('_cleanUp :: client not disconnecting. Clearing and resetting reconnect.')
1008
+ this._clearReconnect()
1009
+ this._setupReconnect()
1010
+ }
1011
+
1012
+ if (this.pingTimer !== null) {
1013
+ debug('_cleanUp :: clearing pingTimer')
1014
+ this.pingTimer.clear()
1015
+ this.pingTimer = null
1016
+ }
1017
+
1018
+ if (done && !this.connected) {
1019
+ debug('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId)
1020
+ this.stream.removeListener('close', done)
1021
+ done()
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * _sendPacket - send or queue a packet
1027
+ * @param {Object} packet - packet options
1028
+ * @param {Function} cb - callback when the packet is sent
1029
+ * @param {Function} cbStorePut - called when message is put into outgoingStore
1030
+ * @api private
1031
+ */
1032
+ MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {
1033
+ debug('_sendPacket :: (%s) :: start', this.options.clientId)
1034
+ cbStorePut = cbStorePut || nop
1035
+
1036
+ if (!this.connected) {
1037
+ debug('_sendPacket :: client not connected. Storing packet offline.')
1038
+ this._storePacket(packet, cb, cbStorePut)
1039
+ return
1040
+ }
1041
+
1042
+ // When sending a packet, reschedule the ping timer
1043
+ this._shiftPingInterval()
1044
+
1045
+ switch (packet.cmd) {
1046
+ case 'publish':
1047
+ break
1048
+ case 'pubrel':
1049
+ storeAndSend(this, packet, cb, cbStorePut)
1050
+ return
1051
+ default:
1052
+ sendPacket(this, packet, cb)
1053
+ return
1054
+ }
1055
+
1056
+ switch (packet.qos) {
1057
+ case 2:
1058
+ case 1:
1059
+ storeAndSend(this, packet, cb, cbStorePut)
1060
+ break
1061
+ /**
1062
+ * no need of case here since it will be caught by default
1063
+ * and jshint comply that before default it must be a break
1064
+ * anyway it will result in -1 evaluation
1065
+ */
1066
+ case 0:
1067
+ /* falls through */
1068
+ default:
1069
+ sendPacket(this, packet, cb)
1070
+ break
1071
+ }
1072
+ debug('_sendPacket :: (%s) :: end', this.options.clientId)
1073
+ }
1074
+
1075
+ /**
1076
+ * _storePacket - queue a packet
1077
+ * @param {Object} packet - packet options
1078
+ * @param {Function} cb - callback when the packet is sent
1079
+ * @param {Function} cbStorePut - called when message is put into outgoingStore
1080
+ * @api private
1081
+ */
1082
+ MqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {
1083
+ debug('_storePacket :: packet: %o', packet)
1084
+ debug('_storePacket :: cb? %s', !!cb)
1085
+ cbStorePut = cbStorePut || nop
1086
+
1087
+ // check that the packet is not a qos of 0, or that the command is not a publish
1088
+ if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
1089
+ this.queue.push({ packet: packet, cb: cb })
1090
+ } else if (packet.qos > 0) {
1091
+ cb = this.outgoing[packet.messageId] ? this.outgoing[packet.messageId].cb : null
1092
+ this.outgoingStore.put(packet, function (err) {
1093
+ if (err) {
1094
+ return cb && cb(err)
1095
+ }
1096
+ cbStorePut()
1097
+ })
1098
+ } else if (cb) {
1099
+ cb(new Error('No connection to broker'))
1100
+ }
1101
+ }
1102
+
1103
+ /**
1104
+ * _setupPingTimer - setup the ping timer
1105
+ *
1106
+ * @api private
1107
+ */
1108
+ MqttClient.prototype._setupPingTimer = function () {
1109
+ debug('_setupPingTimer :: keepalive %d (seconds)', this.options.keepalive)
1110
+ var that = this
1111
+
1112
+ if (!this.pingTimer && this.options.keepalive) {
1113
+ this.pingResp = true
1114
+ this.pingTimer = reInterval(function () {
1115
+ that._checkPing()
1116
+ }, this.options.keepalive * 1000)
1117
+ }
1118
+ }
1119
+
1120
+ /**
1121
+ * _shiftPingInterval - reschedule the ping interval
1122
+ *
1123
+ * @api private
1124
+ */
1125
+ MqttClient.prototype._shiftPingInterval = function () {
1126
+ if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
1127
+ this.pingTimer.reschedule(this.options.keepalive * 1000)
1128
+ }
1129
+ }
1130
+ /**
1131
+ * _checkPing - check if a pingresp has come back, and ping the server again
1132
+ *
1133
+ * @api private
1134
+ */
1135
+ MqttClient.prototype._checkPing = function () {
1136
+ debug('_checkPing :: checking ping...')
1137
+ if (this.pingResp) {
1138
+ debug('_checkPing :: ping response received. Clearing flag and sending `pingreq`')
1139
+ this.pingResp = false
1140
+ this._sendPacket({ cmd: 'pingreq' })
1141
+ } else {
1142
+ // do a forced cleanup since socket will be in bad shape
1143
+ debug('_checkPing :: calling _cleanUp with force true')
1144
+ this._cleanUp(true)
1145
+ }
1146
+ }
1147
+
1148
+ /**
1149
+ * _handlePingresp - handle a pingresp
1150
+ *
1151
+ * @api private
1152
+ */
1153
+ MqttClient.prototype._handlePingresp = function () {
1154
+ this.pingResp = true
1155
+ }
1156
+
1157
+ /**
1158
+ * _handleConnack
1159
+ *
1160
+ * @param {Object} packet
1161
+ * @api private
1162
+ */
1163
+ MqttClient.prototype._handleConnack = function (packet) {
1164
+ debug('_handleConnack')
1165
+ var options = this.options
1166
+ var version = options.protocolVersion
1167
+ var rc = version === 5 ? packet.reasonCode : packet.returnCode
1168
+
1169
+ clearTimeout(this.connackTimer)
1170
+
1171
+ if (packet.properties) {
1172
+ if (packet.properties.topicAliasMaximum) {
1173
+ if (!options.properties) { options.properties = {} }
1174
+ options.properties.topicAliasMaximum = packet.properties.topicAliasMaximum
1175
+ }
1176
+ if (packet.properties.serverKeepAlive && options.keepalive) {
1177
+ options.keepalive = packet.properties.serverKeepAlive
1178
+ this._shiftPingInterval()
1179
+ }
1180
+ if (packet.properties.maximumPacketSize) {
1181
+ if (!options.properties) { options.properties = {} }
1182
+ options.properties.maximumPacketSize = packet.properties.maximumPacketSize
1183
+ }
1184
+ }
1185
+
1186
+ if (rc === 0) {
1187
+ this.reconnecting = false
1188
+ this._onConnect(packet)
1189
+ } else if (rc > 0) {
1190
+ var err = new Error('Connection refused: ' + errors[rc])
1191
+ err.code = rc
1192
+ this.emit('error', err)
1193
+ }
1194
+ }
1195
+
1196
+ /**
1197
+ * _handlePublish
1198
+ *
1199
+ * @param {Object} packet
1200
+ * @api private
1201
+ */
1202
+ /*
1203
+ those late 2 case should be rewrite to comply with coding style:
1204
+
1205
+ case 1:
1206
+ case 0:
1207
+ // do not wait sending a puback
1208
+ // no callback passed
1209
+ if (1 === qos) {
1210
+ this._sendPacket({
1211
+ cmd: 'puback',
1212
+ messageId: messageId
1213
+ });
1214
+ }
1215
+ // emit the message event for both qos 1 and 0
1216
+ this.emit('message', topic, message, packet);
1217
+ this.handleMessage(packet, done);
1218
+ break;
1219
+ default:
1220
+ // do nothing but every switch mus have a default
1221
+ // log or throw an error about unknown qos
1222
+ break;
1223
+
1224
+ for now i just suppressed the warnings
1225
+ */
1226
+ MqttClient.prototype._handlePublish = function (packet, done) {
1227
+ debug('_handlePublish: packet %o', packet)
1228
+ done = typeof done !== 'undefined' ? done : nop
1229
+ var topic = packet.topic.toString()
1230
+ var message = packet.payload
1231
+ var qos = packet.qos
1232
+ var messageId = packet.messageId
1233
+ var that = this
1234
+ var options = this.options
1235
+ var validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
1236
+ debug('_handlePublish: qos %d', qos)
1237
+ switch (qos) {
1238
+ case 2: {
1239
+ options.customHandleAcks(topic, message, packet, function (error, code) {
1240
+ if (!(error instanceof Error)) {
1241
+ code = error
1242
+ error = null
1243
+ }
1244
+ if (error) { return that.emit('error', error) }
1245
+ if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }
1246
+ if (code) {
1247
+ that._sendPacket({cmd: 'pubrec', messageId: messageId, reasonCode: code}, done)
1248
+ } else {
1249
+ that.incomingStore.put(packet, function () {
1250
+ that._sendPacket({cmd: 'pubrec', messageId: messageId}, done)
1251
+ })
1252
+ }
1253
+ })
1254
+ break
1255
+ }
1256
+ case 1: {
1257
+ // emit the message event
1258
+ options.customHandleAcks(topic, message, packet, function (error, code) {
1259
+ if (!(error instanceof Error)) {
1260
+ code = error
1261
+ error = null
1262
+ }
1263
+ if (error) { return that.emit('error', error) }
1264
+ if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }
1265
+ if (!code) { that.emit('message', topic, message, packet) }
1266
+ that.handleMessage(packet, function (err) {
1267
+ if (err) {
1268
+ return done && done(err)
1269
+ }
1270
+ that._sendPacket({cmd: 'puback', messageId: messageId, reasonCode: code}, done)
1271
+ })
1272
+ })
1273
+ break
1274
+ }
1275
+ case 0:
1276
+ // emit the message event
1277
+ this.emit('message', topic, message, packet)
1278
+ this.handleMessage(packet, done)
1279
+ break
1280
+ default:
1281
+ // do nothing
1282
+ debug('_handlePublish: unknown QoS. Doing nothing.')
1283
+ // log or throw an error about unknown qos
1284
+ break
1285
+ }
1286
+ }
1287
+
1288
+ /**
1289
+ * Handle messages with backpressure support, one at a time.
1290
+ * Override at will.
1291
+ *
1292
+ * @param Packet packet the packet
1293
+ * @param Function callback call when finished
1294
+ * @api public
1295
+ */
1296
+ MqttClient.prototype.handleMessage = function (packet, callback) {
1297
+ callback()
1298
+ }
1299
+
1300
+ /**
1301
+ * _handleAck
1302
+ *
1303
+ * @param {Object} packet
1304
+ * @api private
1305
+ */
1306
+
1307
+ MqttClient.prototype._handleAck = function (packet) {
1308
+ /* eslint no-fallthrough: "off" */
1309
+ var messageId = packet.messageId
1310
+ var type = packet.cmd
1311
+ var response = null
1312
+ var cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
1313
+ var that = this
1314
+ var err
1315
+
1316
+ if (!cb) {
1317
+ debug('_handleAck :: Server sent an ack in error. Ignoring.')
1318
+ // Server sent an ack in error, ignore it.
1319
+ return
1320
+ }
1321
+
1322
+ // Process
1323
+ debug('_handleAck :: packet type', type)
1324
+ switch (type) {
1325
+ case 'pubcomp':
1326
+ // same thing as puback for QoS 2
1327
+ case 'puback':
1328
+ var pubackRC = packet.reasonCode
1329
+ // Callback - we're done
1330
+ if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
1331
+ err = new Error('Publish error: ' + errors[pubackRC])
1332
+ err.code = pubackRC
1333
+ cb(err, packet)
1334
+ }
1335
+ delete this.outgoing[messageId]
1336
+ this.outgoingStore.del(packet, cb)
1337
+ break
1338
+ case 'pubrec':
1339
+ response = {
1340
+ cmd: 'pubrel',
1341
+ qos: 2,
1342
+ messageId: messageId
1343
+ }
1344
+ var pubrecRC = packet.reasonCode
1345
+
1346
+ if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
1347
+ err = new Error('Publish error: ' + errors[pubrecRC])
1348
+ err.code = pubrecRC
1349
+ cb(err, packet)
1350
+ } else {
1351
+ this._sendPacket(response)
1352
+ }
1353
+ break
1354
+ case 'suback':
1355
+ delete this.outgoing[messageId]
1356
+ for (var grantedI = 0; grantedI < packet.granted.length; grantedI++) {
1357
+ if ((packet.granted[grantedI] & 0x80) !== 0) {
1358
+ // suback with Failure status
1359
+ var topics = this.messageIdToTopic[messageId]
1360
+ if (topics) {
1361
+ topics.forEach(function (topic) {
1362
+ delete that._resubscribeTopics[topic]
1363
+ })
1364
+ }
1365
+ }
1366
+ }
1367
+ cb(null, packet)
1368
+ break
1369
+ case 'unsuback':
1370
+ delete this.outgoing[messageId]
1371
+ cb(null)
1372
+ break
1373
+ default:
1374
+ that.emit('error', new Error('unrecognized packet type'))
1375
+ }
1376
+
1377
+ if (this.disconnecting &&
1378
+ Object.keys(this.outgoing).length === 0) {
1379
+ this.emit('outgoingEmpty')
1380
+ }
1381
+ }
1382
+
1383
+ /**
1384
+ * _handlePubrel
1385
+ *
1386
+ * @param {Object} packet
1387
+ * @api private
1388
+ */
1389
+ MqttClient.prototype._handlePubrel = function (packet, callback) {
1390
+ debug('handling pubrel packet')
1391
+ callback = typeof callback !== 'undefined' ? callback : nop
1392
+ var messageId = packet.messageId
1393
+ var that = this
1394
+
1395
+ var comp = {cmd: 'pubcomp', messageId: messageId}
1396
+
1397
+ that.incomingStore.get(packet, function (err, pub) {
1398
+ if (!err) {
1399
+ that.emit('message', pub.topic, pub.payload, pub)
1400
+ that.handleMessage(pub, function (err) {
1401
+ if (err) {
1402
+ return callback(err)
1403
+ }
1404
+ that.incomingStore.del(pub, nop)
1405
+ that._sendPacket(comp, callback)
1406
+ })
1407
+ } else {
1408
+ that._sendPacket(comp, callback)
1409
+ }
1410
+ })
1411
+ }
1412
+
1413
+ /**
1414
+ * _handleDisconnect
1415
+ *
1416
+ * @param {Object} packet
1417
+ * @api private
1418
+ */
1419
+ MqttClient.prototype._handleDisconnect = function (packet) {
1420
+ this.emit('disconnect', packet)
1421
+ }
1422
+
1423
+ /**
1424
+ * _nextId
1425
+ * @return unsigned int
1426
+ */
1427
+ MqttClient.prototype._nextId = function () {
1428
+ // id becomes current state of this.nextId and increments afterwards
1429
+ var id = this.nextId++
1430
+ // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
1431
+ if (this.nextId === 65536) {
1432
+ this.nextId = 1
1433
+ }
1434
+ return id
1435
+ }
1436
+
1437
+ /**
1438
+ * getLastMessageId
1439
+ * @return unsigned int
1440
+ */
1441
+ MqttClient.prototype.getLastMessageId = function () {
1442
+ return (this.nextId === 1) ? 65535 : (this.nextId - 1)
1443
+ }
1444
+
1445
+ /**
1446
+ * _resubscribe
1447
+ * @api private
1448
+ */
1449
+ MqttClient.prototype._resubscribe = function (connack) {
1450
+ debug('_resubscribe')
1451
+ var _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
1452
+ if (!this._firstConnection &&
1453
+ (this.options.clean || (this.options.protocolVersion === 5 && !connack.sessionPresent)) &&
1454
+ _resubscribeTopicsKeys.length > 0) {
1455
+ if (this.options.resubscribe) {
1456
+ if (this.options.protocolVersion === 5) {
1457
+ debug('_resubscribe: protocolVersion 5')
1458
+ for (var topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {
1459
+ var resubscribeTopic = {}
1460
+ resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]
1461
+ resubscribeTopic.resubscribe = true
1462
+ this.subscribe(resubscribeTopic, {properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties})
1463
+ }
1464
+ } else {
1465
+ this._resubscribeTopics.resubscribe = true
1466
+ this.subscribe(this._resubscribeTopics)
1467
+ }
1468
+ } else {
1469
+ this._resubscribeTopics = {}
1470
+ }
1471
+ }
1472
+
1473
+ this._firstConnection = false
1474
+ }
1475
+
1476
+ /**
1477
+ * _onConnect
1478
+ *
1479
+ * @api private
1480
+ */
1481
+ MqttClient.prototype._onConnect = function (packet) {
1482
+ if (this.disconnected) {
1483
+ this.emit('connect', packet)
1484
+ return
1485
+ }
1486
+
1487
+ var that = this
1488
+
1489
+ this._setupPingTimer()
1490
+ this._resubscribe(packet)
1491
+
1492
+ this.connected = true
1493
+
1494
+ function startStreamProcess () {
1495
+ var outStore = that.outgoingStore.createStream()
1496
+
1497
+ function clearStoreProcessing () {
1498
+ that._storeProcessing = false
1499
+ that._packetIdsDuringStoreProcessing = {}
1500
+ }
1501
+
1502
+ that.once('close', remove)
1503
+ outStore.on('error', function (err) {
1504
+ clearStoreProcessing()
1505
+ that.removeListener('close', remove)
1506
+ that.emit('error', err)
1507
+ })
1508
+
1509
+ function remove () {
1510
+ outStore.destroy()
1511
+ outStore = null
1512
+ clearStoreProcessing()
1513
+ }
1514
+
1515
+ function storeDeliver () {
1516
+ // edge case, we wrapped this twice
1517
+ if (!outStore) {
1518
+ return
1519
+ }
1520
+ that._storeProcessing = true
1521
+
1522
+ var packet = outStore.read(1)
1523
+
1524
+ var cb
1525
+
1526
+ if (!packet) {
1527
+ // read when data is available in the future
1528
+ outStore.once('readable', storeDeliver)
1529
+ return
1530
+ }
1531
+
1532
+ // Skip already processed store packets
1533
+ if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
1534
+ storeDeliver()
1535
+ return
1536
+ }
1537
+
1538
+ // Avoid unnecessary stream read operations when disconnected
1539
+ if (!that.disconnecting && !that.reconnectTimer) {
1540
+ cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null
1541
+ that.outgoing[packet.messageId] = {
1542
+ volatile: false,
1543
+ cb: function (err, status) {
1544
+ // Ensure that the original callback passed in to publish gets invoked
1545
+ if (cb) {
1546
+ cb(err, status)
1547
+ }
1548
+
1549
+ storeDeliver()
1550
+ }
1551
+ }
1552
+ that._packetIdsDuringStoreProcessing[packet.messageId] = true
1553
+ that._sendPacket(packet)
1554
+ } else if (outStore.destroy) {
1555
+ outStore.destroy()
1556
+ }
1557
+ }
1558
+
1559
+ outStore.on('end', function () {
1560
+ var allProcessed = true
1561
+ for (var id in that._packetIdsDuringStoreProcessing) {
1562
+ if (!that._packetIdsDuringStoreProcessing[id]) {
1563
+ allProcessed = false
1564
+ break
1565
+ }
1566
+ }
1567
+ if (allProcessed) {
1568
+ clearStoreProcessing()
1569
+ that.removeListener('close', remove)
1570
+ that.emit('connect', packet)
1571
+ } else {
1572
+ startStreamProcess()
1573
+ }
1574
+ })
1575
+ storeDeliver()
1576
+ }
1577
+ // start flowing
1578
+ startStreamProcess()
1579
+ }
1580
+
1581
+ module.exports = MqttClient