mqtt 4.2.7 → 4.3.2

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