mqtt 4.3.0 → 4.3.4

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,1890 +1,1884 @@
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
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 || !publishProc()) {
664
+ this._storeProcessingQueue.push(
665
+ {
666
+ invoke: publishProc,
667
+ cbStorePut: opts.cbStorePut,
668
+ callback: callback
669
+ }
670
+ )
671
+ }
672
+ return this
673
+ }
674
+
675
+ /**
676
+ * subscribe - subscribe to <topic>
677
+ *
678
+ * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
679
+ * @param {Object} [opts] - optional subscription options, includes:
680
+ * {Number} qos - subscribe qos level
681
+ * @param {Function} [callback] - function(err, granted){} where:
682
+ * {Error} err - subscription error (none at the moment!)
683
+ * {Array} granted - array of {topic: 't', qos: 0}
684
+ * @returns {MqttClient} this - for chaining
685
+ * @api public
686
+ * @example client.subscribe('topic');
687
+ * @example client.subscribe('topic', {qos: 1});
688
+ * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
689
+ * @example client.subscribe('topic', console.log);
690
+ */
691
+ MqttClient.prototype.subscribe = function () {
692
+ const that = this
693
+ const args = new Array(arguments.length)
694
+ for (let i = 0; i < arguments.length; i++) {
695
+ args[i] = arguments[i]
696
+ }
697
+ const subs = []
698
+ let obj = args.shift()
699
+ const resubscribe = obj.resubscribe
700
+ let callback = args.pop() || nop
701
+ let opts = args.pop()
702
+ const version = this.options.protocolVersion
703
+
704
+ delete obj.resubscribe
705
+
706
+ if (typeof obj === 'string') {
707
+ obj = [obj]
708
+ }
709
+
710
+ if (typeof callback !== 'function') {
711
+ opts = callback
712
+ callback = nop
713
+ }
714
+
715
+ const invalidTopic = validations.validateTopics(obj)
716
+ if (invalidTopic !== null) {
717
+ setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
718
+ return this
719
+ }
720
+
721
+ if (this._checkDisconnecting(callback)) {
722
+ debug('subscribe: discconecting true')
723
+ return this
724
+ }
725
+
726
+ const defaultOpts = {
727
+ qos: 0
728
+ }
729
+ if (version === 5) {
730
+ defaultOpts.nl = false
731
+ defaultOpts.rap = false
732
+ defaultOpts.rh = 0
733
+ }
734
+ opts = xtend(defaultOpts, opts)
735
+
736
+ if (Array.isArray(obj)) {
737
+ obj.forEach(function (topic) {
738
+ debug('subscribe: array topic %s', topic)
739
+ if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, topic) ||
740
+ that._resubscribeTopics[topic].qos < opts.qos ||
741
+ resubscribe) {
742
+ const currentOpts = {
743
+ topic: topic,
744
+ qos: opts.qos
745
+ }
746
+ if (version === 5) {
747
+ currentOpts.nl = opts.nl
748
+ currentOpts.rap = opts.rap
749
+ currentOpts.rh = opts.rh
750
+ currentOpts.properties = opts.properties
751
+ }
752
+ debug('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos)
753
+ subs.push(currentOpts)
754
+ }
755
+ })
756
+ } else {
757
+ Object
758
+ .keys(obj)
759
+ .forEach(function (k) {
760
+ debug('subscribe: object topic %s', k)
761
+ if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, k) ||
762
+ that._resubscribeTopics[k].qos < obj[k].qos ||
763
+ resubscribe) {
764
+ const currentOpts = {
765
+ topic: k,
766
+ qos: obj[k].qos
767
+ }
768
+ if (version === 5) {
769
+ currentOpts.nl = obj[k].nl
770
+ currentOpts.rap = obj[k].rap
771
+ currentOpts.rh = obj[k].rh
772
+ currentOpts.properties = opts.properties
773
+ }
774
+ debug('subscribe: pushing `%s` to subs list', currentOpts)
775
+ subs.push(currentOpts)
776
+ }
777
+ })
778
+ }
779
+
780
+ if (!subs.length) {
781
+ callback(null, [])
782
+ return this
783
+ }
784
+
785
+ const subscribeProc = function () {
786
+ const messageId = that._nextId()
787
+ if (messageId === null) {
788
+ debug('No messageId left')
789
+ return false
790
+ }
791
+
792
+ const packet = {
793
+ cmd: 'subscribe',
794
+ subscriptions: subs,
795
+ qos: 1,
796
+ retain: false,
797
+ dup: false,
798
+ messageId: messageId
799
+ }
800
+
801
+ if (opts.properties) {
802
+ packet.properties = opts.properties
803
+ }
804
+
805
+ // subscriptions to resubscribe to in case of disconnect
806
+ if (that.options.resubscribe) {
807
+ debug('subscribe :: resubscribe true')
808
+ const topics = []
809
+ subs.forEach(function (sub) {
810
+ if (that.options.reconnectPeriod > 0) {
811
+ const topic = { qos: sub.qos }
812
+ if (version === 5) {
813
+ topic.nl = sub.nl || false
814
+ topic.rap = sub.rap || false
815
+ topic.rh = sub.rh || 0
816
+ topic.properties = sub.properties
817
+ }
818
+ that._resubscribeTopics[sub.topic] = topic
819
+ topics.push(sub.topic)
820
+ }
821
+ })
822
+ that.messageIdToTopic[packet.messageId] = topics
823
+ }
824
+
825
+ that.outgoing[packet.messageId] = {
826
+ volatile: true,
827
+ cb: function (err, packet) {
828
+ if (!err) {
829
+ const granted = packet.granted
830
+ for (let i = 0; i < granted.length; i += 1) {
831
+ subs[i].qos = granted[i]
832
+ }
833
+ }
834
+
835
+ callback(err, subs)
836
+ }
837
+ }
838
+ debug('subscribe :: call _sendPacket')
839
+ that._sendPacket(packet)
840
+ return true
841
+ }
842
+
843
+ if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !subscribeProc()) {
844
+ this._storeProcessingQueue.push(
845
+ {
846
+ invoke: subscribeProc,
847
+ callback: callback
848
+ }
849
+ )
850
+ }
851
+
852
+ return this
853
+ }
854
+
855
+ /**
856
+ * unsubscribe - unsubscribe from topic(s)
857
+ *
858
+ * @param {String, Array} topic - topics to unsubscribe from
859
+ * @param {Object} [opts] - optional subscription options, includes:
860
+ * {Object} properties - properties of unsubscribe packet
861
+ * @param {Function} [callback] - callback fired on unsuback
862
+ * @returns {MqttClient} this - for chaining
863
+ * @api public
864
+ * @example client.unsubscribe('topic');
865
+ * @example client.unsubscribe('topic', console.log);
866
+ */
867
+ MqttClient.prototype.unsubscribe = function () {
868
+ const that = this
869
+ const args = new Array(arguments.length)
870
+ for (let i = 0; i < arguments.length; i++) {
871
+ args[i] = arguments[i]
872
+ }
873
+ let topic = args.shift()
874
+ let callback = args.pop() || nop
875
+ let opts = args.pop()
876
+ if (typeof topic === 'string') {
877
+ topic = [topic]
878
+ }
879
+
880
+ if (typeof callback !== 'function') {
881
+ opts = callback
882
+ callback = nop
883
+ }
884
+
885
+ const invalidTopic = validations.validateTopics(topic)
886
+ if (invalidTopic !== null) {
887
+ setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
888
+ return this
889
+ }
890
+
891
+ if (that._checkDisconnecting(callback)) {
892
+ return this
893
+ }
894
+
895
+ const unsubscribeProc = function () {
896
+ const messageId = that._nextId()
897
+ if (messageId === null) {
898
+ debug('No messageId left')
899
+ return false
900
+ }
901
+ const packet = {
902
+ cmd: 'unsubscribe',
903
+ qos: 1,
904
+ messageId: messageId
905
+ }
906
+
907
+ if (typeof topic === 'string') {
908
+ packet.unsubscriptions = [topic]
909
+ } else if (Array.isArray(topic)) {
910
+ packet.unsubscriptions = topic
911
+ }
912
+
913
+ if (that.options.resubscribe) {
914
+ packet.unsubscriptions.forEach(function (topic) {
915
+ delete that._resubscribeTopics[topic]
916
+ })
917
+ }
918
+
919
+ if (typeof opts === 'object' && opts.properties) {
920
+ packet.properties = opts.properties
921
+ }
922
+
923
+ that.outgoing[packet.messageId] = {
924
+ volatile: true,
925
+ cb: callback
926
+ }
927
+
928
+ debug('unsubscribe: call _sendPacket')
929
+ that._sendPacket(packet)
930
+
931
+ return true
932
+ }
933
+
934
+ if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !unsubscribeProc()) {
935
+ this._storeProcessingQueue.push(
936
+ {
937
+ invoke: unsubscribeProc,
938
+ callback: callback
939
+ }
940
+ )
941
+ }
942
+
943
+ return this
944
+ }
945
+
946
+ /**
947
+ * end - close connection
948
+ *
949
+ * @returns {MqttClient} this - for chaining
950
+ * @param {Boolean} force - do not wait for all in-flight messages to be acked
951
+ * @param {Object} opts - added to the disconnect packet
952
+ * @param {Function} cb - called when the client has been closed
953
+ *
954
+ * @api public
955
+ */
956
+ MqttClient.prototype.end = function (force, opts, cb) {
957
+ const that = this
958
+
959
+ debug('end :: (%s)', this.options.clientId)
960
+
961
+ if (force == null || typeof force !== 'boolean') {
962
+ cb = opts || nop
963
+ opts = force
964
+ force = false
965
+ if (typeof opts !== 'object') {
966
+ cb = opts
967
+ opts = null
968
+ if (typeof cb !== 'function') {
969
+ cb = nop
970
+ }
971
+ }
972
+ }
973
+
974
+ if (typeof opts !== 'object') {
975
+ cb = opts
976
+ opts = null
977
+ }
978
+
979
+ debug('end :: cb? %s', !!cb)
980
+ cb = cb || nop
981
+
982
+ function closeStores () {
983
+ debug('end :: closeStores: closing incoming and outgoing stores')
984
+ that.disconnected = true
985
+ that.incomingStore.close(function (e1) {
986
+ that.outgoingStore.close(function (e2) {
987
+ debug('end :: closeStores: emitting end')
988
+ that.emit('end')
989
+ if (cb) {
990
+ const err = e1 || e2
991
+ debug('end :: closeStores: invoking callback with args')
992
+ cb(err)
993
+ }
994
+ })
995
+ })
996
+ if (that._deferredReconnect) {
997
+ that._deferredReconnect()
998
+ }
999
+ }
1000
+
1001
+ function finish () {
1002
+ // defer closesStores of an I/O cycle,
1003
+ // just to make sure things are
1004
+ // ok for websockets
1005
+ debug('end :: (%s) :: finish :: calling _cleanUp with force %s', that.options.clientId, force)
1006
+ that._cleanUp(force, () => {
1007
+ debug('end :: finish :: calling process.nextTick on closeStores')
1008
+ // const boundProcess = nextTick.bind(null, closeStores)
1009
+ nextTick(closeStores.bind(that))
1010
+ }, opts)
1011
+ }
1012
+
1013
+ if (this.disconnecting) {
1014
+ cb()
1015
+ return this
1016
+ }
1017
+
1018
+ this._clearReconnect()
1019
+
1020
+ this.disconnecting = true
1021
+
1022
+ if (!force && Object.keys(this.outgoing).length > 0) {
1023
+ // wait 10ms, just to be sure we received all of it
1024
+ debug('end :: (%s) :: calling finish in 10ms once outgoing is empty', that.options.clientId)
1025
+ this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
1026
+ } else {
1027
+ debug('end :: (%s) :: immediately calling finish', that.options.clientId)
1028
+ finish()
1029
+ }
1030
+
1031
+ return this
1032
+ }
1033
+
1034
+ /**
1035
+ * removeOutgoingMessage - remove a message in outgoing store
1036
+ * the outgoing callback will be called withe Error('Message removed') if the message is removed
1037
+ *
1038
+ * @param {Number} messageId - messageId to remove message
1039
+ * @returns {MqttClient} this - for chaining
1040
+ * @api public
1041
+ *
1042
+ * @example client.removeOutgoingMessage(client.getLastAllocated());
1043
+ */
1044
+ MqttClient.prototype.removeOutgoingMessage = function (messageId) {
1045
+ const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
1046
+ delete this.outgoing[messageId]
1047
+ this.outgoingStore.del({ messageId: messageId }, function () {
1048
+ cb(new Error('Message removed'))
1049
+ })
1050
+ return this
1051
+ }
1052
+
1053
+ /**
1054
+ * reconnect - connect again using the same options as connect()
1055
+ *
1056
+ * @param {Object} [opts] - optional reconnect options, includes:
1057
+ * {Store} incomingStore - a store for the incoming packets
1058
+ * {Store} outgoingStore - a store for the outgoing packets
1059
+ * if opts is not given, current stores are used
1060
+ * @returns {MqttClient} this - for chaining
1061
+ *
1062
+ * @api public
1063
+ */
1064
+ MqttClient.prototype.reconnect = function (opts) {
1065
+ debug('client reconnect')
1066
+ const that = this
1067
+ const f = function () {
1068
+ if (opts) {
1069
+ that.options.incomingStore = opts.incomingStore
1070
+ that.options.outgoingStore = opts.outgoingStore
1071
+ } else {
1072
+ that.options.incomingStore = null
1073
+ that.options.outgoingStore = null
1074
+ }
1075
+ that.incomingStore = that.options.incomingStore || new Store()
1076
+ that.outgoingStore = that.options.outgoingStore || new Store()
1077
+ that.disconnecting = false
1078
+ that.disconnected = false
1079
+ that._deferredReconnect = null
1080
+ that._reconnect()
1081
+ }
1082
+
1083
+ if (this.disconnecting && !this.disconnected) {
1084
+ this._deferredReconnect = f
1085
+ } else {
1086
+ f()
1087
+ }
1088
+ return this
1089
+ }
1090
+
1091
+ /**
1092
+ * _reconnect - implement reconnection
1093
+ * @api privateish
1094
+ */
1095
+ MqttClient.prototype._reconnect = function () {
1096
+ debug('_reconnect: emitting reconnect to client')
1097
+ this.emit('reconnect')
1098
+ if (this.connected) {
1099
+ this.end(() => { this._setupStream() })
1100
+ debug('client already connected. disconnecting first.')
1101
+ } else {
1102
+ debug('_reconnect: calling _setupStream')
1103
+ this._setupStream()
1104
+ }
1105
+ }
1106
+
1107
+ /**
1108
+ * _setupReconnect - setup reconnect timer
1109
+ */
1110
+ MqttClient.prototype._setupReconnect = function () {
1111
+ const that = this
1112
+
1113
+ if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
1114
+ if (!this.reconnecting) {
1115
+ debug('_setupReconnect :: emit `offline` state')
1116
+ this.emit('offline')
1117
+ debug('_setupReconnect :: set `reconnecting` to `true`')
1118
+ this.reconnecting = true
1119
+ }
1120
+ debug('_setupReconnect :: setting reconnectTimer for %d ms', that.options.reconnectPeriod)
1121
+ that.reconnectTimer = setInterval(function () {
1122
+ debug('reconnectTimer :: reconnect triggered!')
1123
+ that._reconnect()
1124
+ }, that.options.reconnectPeriod)
1125
+ } else {
1126
+ debug('_setupReconnect :: doing nothing...')
1127
+ }
1128
+ }
1129
+
1130
+ /**
1131
+ * _clearReconnect - clear the reconnect timer
1132
+ */
1133
+ MqttClient.prototype._clearReconnect = function () {
1134
+ debug('_clearReconnect : clearing reconnect timer')
1135
+ if (this.reconnectTimer) {
1136
+ clearInterval(this.reconnectTimer)
1137
+ this.reconnectTimer = null
1138
+ }
1139
+ }
1140
+
1141
+ /**
1142
+ * _cleanUp - clean up on connection end
1143
+ * @api private
1144
+ */
1145
+ MqttClient.prototype._cleanUp = function (forced, done) {
1146
+ const opts = arguments[2]
1147
+ if (done) {
1148
+ debug('_cleanUp :: done callback provided for on stream close')
1149
+ this.stream.on('close', done)
1150
+ }
1151
+
1152
+ debug('_cleanUp :: forced? %s', forced)
1153
+ if (forced) {
1154
+ if ((this.options.reconnectPeriod === 0) && this.options.clean) {
1155
+ flush(this.outgoing)
1156
+ }
1157
+ debug('_cleanUp :: (%s) :: destroying stream', this.options.clientId)
1158
+ this.stream.destroy()
1159
+ } else {
1160
+ const packet = xtend({ cmd: 'disconnect' }, opts)
1161
+ debug('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId)
1162
+ this._sendPacket(
1163
+ packet,
1164
+ setImmediate.bind(
1165
+ null,
1166
+ this.stream.end.bind(this.stream)
1167
+ )
1168
+ )
1169
+ }
1170
+
1171
+ if (!this.disconnecting) {
1172
+ debug('_cleanUp :: client not disconnecting. Clearing and resetting reconnect.')
1173
+ this._clearReconnect()
1174
+ this._setupReconnect()
1175
+ }
1176
+
1177
+ if (this.pingTimer !== null) {
1178
+ debug('_cleanUp :: clearing pingTimer')
1179
+ this.pingTimer.clear()
1180
+ this.pingTimer = null
1181
+ }
1182
+
1183
+ if (done && !this.connected) {
1184
+ debug('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId)
1185
+ this.stream.removeListener('close', done)
1186
+ done()
1187
+ }
1188
+ }
1189
+
1190
+ /**
1191
+ * _sendPacket - send or queue a packet
1192
+ * @param {Object} packet - packet options
1193
+ * @param {Function} cb - callback when the packet is sent
1194
+ * @param {Function} cbStorePut - called when message is put into outgoingStore
1195
+ * @api private
1196
+ */
1197
+ MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {
1198
+ debug('_sendPacket :: (%s) :: start', this.options.clientId)
1199
+ cbStorePut = cbStorePut || nop
1200
+ cb = cb || nop
1201
+
1202
+ const err = applyTopicAlias(this, packet)
1203
+ if (err) {
1204
+ cb(err)
1205
+ return
1206
+ }
1207
+
1208
+ if (!this.connected) {
1209
+ // allow auth packets to be sent while authenticating with the broker (mqtt5 enhanced auth)
1210
+ if (packet.cmd === 'auth') {
1211
+ this._shiftPingInterval()
1212
+ sendPacket(this, packet, cb)
1213
+ return
1214
+ }
1215
+
1216
+ debug('_sendPacket :: client not connected. Storing packet offline.')
1217
+ this._storePacket(packet, cb, cbStorePut)
1218
+ return
1219
+ }
1220
+
1221
+ // When sending a packet, reschedule the ping timer
1222
+ this._shiftPingInterval()
1223
+
1224
+ switch (packet.cmd) {
1225
+ case 'publish':
1226
+ break
1227
+ case 'pubrel':
1228
+ storeAndSend(this, packet, cb, cbStorePut)
1229
+ return
1230
+ default:
1231
+ sendPacket(this, packet, cb)
1232
+ return
1233
+ }
1234
+
1235
+ switch (packet.qos) {
1236
+ case 2:
1237
+ case 1:
1238
+ storeAndSend(this, packet, cb, cbStorePut)
1239
+ break
1240
+ /**
1241
+ * no need of case here since it will be caught by default
1242
+ * and jshint comply that before default it must be a break
1243
+ * anyway it will result in -1 evaluation
1244
+ */
1245
+ case 0:
1246
+ /* falls through */
1247
+ default:
1248
+ sendPacket(this, packet, cb)
1249
+ break
1250
+ }
1251
+ debug('_sendPacket :: (%s) :: end', this.options.clientId)
1252
+ }
1253
+
1254
+ /**
1255
+ * _storePacket - queue a packet
1256
+ * @param {Object} packet - packet options
1257
+ * @param {Function} cb - callback when the packet is sent
1258
+ * @param {Function} cbStorePut - called when message is put into outgoingStore
1259
+ * @api private
1260
+ */
1261
+ MqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {
1262
+ debug('_storePacket :: packet: %o', packet)
1263
+ debug('_storePacket :: cb? %s', !!cb)
1264
+ cbStorePut = cbStorePut || nop
1265
+
1266
+ let storePacket = packet
1267
+ if (storePacket.cmd === 'publish') {
1268
+ // The original packet is for sending.
1269
+ // The cloned storePacket is for storing to resend on reconnect.
1270
+ // Topic Alias must not be used after disconnected.
1271
+ storePacket = clone(packet)
1272
+ const err = removeTopicAliasAndRecoverTopicName(this, storePacket)
1273
+ if (err) {
1274
+ return cb && cb(err)
1275
+ }
1276
+ }
1277
+ // check that the packet is not a qos of 0, or that the command is not a publish
1278
+ if (((storePacket.qos || 0) === 0 && this.queueQoSZero) || storePacket.cmd !== 'publish') {
1279
+ this.queue.push({ packet: storePacket, cb: cb })
1280
+ } else if (storePacket.qos > 0) {
1281
+ cb = this.outgoing[storePacket.messageId] ? this.outgoing[storePacket.messageId].cb : null
1282
+ this.outgoingStore.put(storePacket, function (err) {
1283
+ if (err) {
1284
+ return cb && cb(err)
1285
+ }
1286
+ cbStorePut()
1287
+ })
1288
+ } else if (cb) {
1289
+ cb(new Error('No connection to broker'))
1290
+ }
1291
+ }
1292
+
1293
+ /**
1294
+ * _setupPingTimer - setup the ping timer
1295
+ *
1296
+ * @api private
1297
+ */
1298
+ MqttClient.prototype._setupPingTimer = function () {
1299
+ debug('_setupPingTimer :: keepalive %d (seconds)', this.options.keepalive)
1300
+ const that = this
1301
+
1302
+ if (!this.pingTimer && this.options.keepalive) {
1303
+ this.pingResp = true
1304
+ this.pingTimer = reInterval(function () {
1305
+ that._checkPing()
1306
+ }, this.options.keepalive * 1000)
1307
+ }
1308
+ }
1309
+
1310
+ /**
1311
+ * _shiftPingInterval - reschedule the ping interval
1312
+ *
1313
+ * @api private
1314
+ */
1315
+ MqttClient.prototype._shiftPingInterval = function () {
1316
+ if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
1317
+ this.pingTimer.reschedule(this.options.keepalive * 1000)
1318
+ }
1319
+ }
1320
+ /**
1321
+ * _checkPing - check if a pingresp has come back, and ping the server again
1322
+ *
1323
+ * @api private
1324
+ */
1325
+ MqttClient.prototype._checkPing = function () {
1326
+ debug('_checkPing :: checking ping...')
1327
+ if (this.pingResp) {
1328
+ debug('_checkPing :: ping response received. Clearing flag and sending `pingreq`')
1329
+ this.pingResp = false
1330
+ this._sendPacket({ cmd: 'pingreq' })
1331
+ } else {
1332
+ // do a forced cleanup since socket will be in bad shape
1333
+ debug('_checkPing :: calling _cleanUp with force true')
1334
+ this._cleanUp(true)
1335
+ }
1336
+ }
1337
+
1338
+ /**
1339
+ * _handlePingresp - handle a pingresp
1340
+ *
1341
+ * @api private
1342
+ */
1343
+ MqttClient.prototype._handlePingresp = function () {
1344
+ this.pingResp = true
1345
+ }
1346
+
1347
+ /**
1348
+ * _handleConnack
1349
+ *
1350
+ * @param {Object} packet
1351
+ * @api private
1352
+ */
1353
+ MqttClient.prototype._handleConnack = function (packet) {
1354
+ debug('_handleConnack')
1355
+ const options = this.options
1356
+ const version = options.protocolVersion
1357
+ const rc = version === 5 ? packet.reasonCode : packet.returnCode
1358
+
1359
+ clearTimeout(this.connackTimer)
1360
+ delete this.topicAliasSend
1361
+
1362
+ if (packet.properties) {
1363
+ if (packet.properties.topicAliasMaximum) {
1364
+ if (packet.properties.topicAliasMaximum > 0xffff) {
1365
+ this.emit('error', new Error('topicAliasMaximum from broker is out of range'))
1366
+ return
1367
+ }
1368
+ if (packet.properties.topicAliasMaximum > 0) {
1369
+ this.topicAliasSend = new TopicAliasSend(packet.properties.topicAliasMaximum)
1370
+ }
1371
+ }
1372
+ if (packet.properties.serverKeepAlive && options.keepalive) {
1373
+ options.keepalive = packet.properties.serverKeepAlive
1374
+ this._shiftPingInterval()
1375
+ }
1376
+ if (packet.properties.maximumPacketSize) {
1377
+ if (!options.properties) { options.properties = {} }
1378
+ options.properties.maximumPacketSize = packet.properties.maximumPacketSize
1379
+ }
1380
+ }
1381
+
1382
+ if (rc === 0) {
1383
+ this.reconnecting = false
1384
+ this._onConnect(packet)
1385
+ } else if (rc > 0) {
1386
+ const err = new Error('Connection refused: ' + errors[rc])
1387
+ err.code = rc
1388
+ this.emit('error', err)
1389
+ }
1390
+ }
1391
+
1392
+ MqttClient.prototype._handleAuth = function (packet) {
1393
+ const options = this.options
1394
+ const version = options.protocolVersion
1395
+ const rc = version === 5 ? packet.reasonCode : packet.returnCode
1396
+
1397
+ if (version !== 5) {
1398
+ const err = new Error('Protocol error: Auth packets are only supported in MQTT 5. Your version:' + version)
1399
+ err.code = rc
1400
+ this.emit('error', err)
1401
+ return
1402
+ }
1403
+
1404
+ const that = this
1405
+ this.handleAuth(packet, function (err, packet) {
1406
+ if (err) {
1407
+ that.emit('error', err)
1408
+ return
1409
+ }
1410
+
1411
+ if (rc === 24) {
1412
+ that.reconnecting = false
1413
+ that._sendPacket(packet)
1414
+ } else {
1415
+ const error = new Error('Connection refused: ' + errors[rc])
1416
+ err.code = rc
1417
+ that.emit('error', error)
1418
+ }
1419
+ })
1420
+ }
1421
+
1422
+ /**
1423
+ * @param packet the packet received by the broker
1424
+ * @return the auth packet to be returned to the broker
1425
+ * @api public
1426
+ */
1427
+ MqttClient.prototype.handleAuth = function (packet, callback) {
1428
+ callback()
1429
+ }
1430
+
1431
+ /**
1432
+ * _handlePublish
1433
+ *
1434
+ * @param {Object} packet
1435
+ * @api private
1436
+ */
1437
+ /*
1438
+ those late 2 case should be rewrite to comply with coding style:
1439
+
1440
+ case 1:
1441
+ case 0:
1442
+ // do not wait sending a puback
1443
+ // no callback passed
1444
+ if (1 === qos) {
1445
+ this._sendPacket({
1446
+ cmd: 'puback',
1447
+ messageId: messageId
1448
+ });
1449
+ }
1450
+ // emit the message event for both qos 1 and 0
1451
+ this.emit('message', topic, message, packet);
1452
+ this.handleMessage(packet, done);
1453
+ break;
1454
+ default:
1455
+ // do nothing but every switch mus have a default
1456
+ // log or throw an error about unknown qos
1457
+ break;
1458
+
1459
+ for now i just suppressed the warnings
1460
+ */
1461
+ MqttClient.prototype._handlePublish = function (packet, done) {
1462
+ debug('_handlePublish: packet %o', packet)
1463
+ done = typeof done !== 'undefined' ? done : nop
1464
+ let topic = packet.topic.toString()
1465
+ const message = packet.payload
1466
+ const qos = packet.qos
1467
+ const messageId = packet.messageId
1468
+ const that = this
1469
+ const options = this.options
1470
+ const validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
1471
+ if (this.options.protocolVersion === 5) {
1472
+ let alias
1473
+ if (packet.properties) {
1474
+ alias = packet.properties.topicAlias
1475
+ }
1476
+ if (typeof alias !== 'undefined') {
1477
+ if (topic.length === 0) {
1478
+ if (alias > 0 && alias <= 0xffff) {
1479
+ const gotTopic = this.topicAliasRecv.getTopicByAlias(alias)
1480
+ if (gotTopic) {
1481
+ topic = gotTopic
1482
+ debug('_handlePublish :: topic complemented by alias. topic: %s - alias: %d', topic, alias)
1483
+ } else {
1484
+ debug('_handlePublish :: unregistered topic alias. alias: %d', alias)
1485
+ this.emit('error', new Error('Received unregistered Topic Alias'))
1486
+ return
1487
+ }
1488
+ } else {
1489
+ debug('_handlePublish :: topic alias out of range. alias: %d', alias)
1490
+ this.emit('error', new Error('Received Topic Alias is out of range'))
1491
+ return
1492
+ }
1493
+ } else {
1494
+ if (this.topicAliasRecv.put(topic, alias)) {
1495
+ debug('_handlePublish :: registered topic: %s - alias: %d', topic, alias)
1496
+ } else {
1497
+ debug('_handlePublish :: topic alias out of range. alias: %d', alias)
1498
+ this.emit('error', new Error('Received Topic Alias is out of range'))
1499
+ return
1500
+ }
1501
+ }
1502
+ }
1503
+ }
1504
+ debug('_handlePublish: qos %d', qos)
1505
+ switch (qos) {
1506
+ case 2: {
1507
+ options.customHandleAcks(topic, message, packet, function (error, code) {
1508
+ if (!(error instanceof Error)) {
1509
+ code = error
1510
+ error = null
1511
+ }
1512
+ if (error) { return that.emit('error', error) }
1513
+ if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }
1514
+ if (code) {
1515
+ that._sendPacket({ cmd: 'pubrec', messageId: messageId, reasonCode: code }, done)
1516
+ } else {
1517
+ that.incomingStore.put(packet, function () {
1518
+ that._sendPacket({ cmd: 'pubrec', messageId: messageId }, done)
1519
+ })
1520
+ }
1521
+ })
1522
+ break
1523
+ }
1524
+ case 1: {
1525
+ // emit the message event
1526
+ options.customHandleAcks(topic, message, packet, function (error, code) {
1527
+ if (!(error instanceof Error)) {
1528
+ code = error
1529
+ error = null
1530
+ }
1531
+ if (error) { return that.emit('error', error) }
1532
+ if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }
1533
+ if (!code) { that.emit('message', topic, message, packet) }
1534
+ that.handleMessage(packet, function (err) {
1535
+ if (err) {
1536
+ return done && done(err)
1537
+ }
1538
+ that._sendPacket({ cmd: 'puback', messageId: messageId, reasonCode: code }, done)
1539
+ })
1540
+ })
1541
+ break
1542
+ }
1543
+ case 0:
1544
+ // emit the message event
1545
+ this.emit('message', topic, message, packet)
1546
+ this.handleMessage(packet, done)
1547
+ break
1548
+ default:
1549
+ // do nothing
1550
+ debug('_handlePublish: unknown QoS. Doing nothing.')
1551
+ // log or throw an error about unknown qos
1552
+ break
1553
+ }
1554
+ }
1555
+
1556
+ /**
1557
+ * Handle messages with backpressure support, one at a time.
1558
+ * Override at will.
1559
+ *
1560
+ * @param Packet packet the packet
1561
+ * @param Function callback call when finished
1562
+ * @api public
1563
+ */
1564
+ MqttClient.prototype.handleMessage = function (packet, callback) {
1565
+ callback()
1566
+ }
1567
+
1568
+ /**
1569
+ * _handleAck
1570
+ *
1571
+ * @param {Object} packet
1572
+ * @api private
1573
+ */
1574
+
1575
+ MqttClient.prototype._handleAck = function (packet) {
1576
+ /* eslint no-fallthrough: "off" */
1577
+ const messageId = packet.messageId
1578
+ const type = packet.cmd
1579
+ let response = null
1580
+ const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
1581
+ const that = this
1582
+ let err
1583
+
1584
+ if (!cb) {
1585
+ debug('_handleAck :: Server sent an ack in error. Ignoring.')
1586
+ // Server sent an ack in error, ignore it.
1587
+ return
1588
+ }
1589
+
1590
+ // Process
1591
+ debug('_handleAck :: packet type', type)
1592
+ switch (type) {
1593
+ case 'pubcomp':
1594
+ // same thing as puback for QoS 2
1595
+ case 'puback': {
1596
+ const pubackRC = packet.reasonCode
1597
+ // Callback - we're done
1598
+ if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
1599
+ err = new Error('Publish error: ' + errors[pubackRC])
1600
+ err.code = pubackRC
1601
+ cb(err, packet)
1602
+ }
1603
+ delete this.outgoing[messageId]
1604
+ this.outgoingStore.del(packet, cb)
1605
+ this.messageIdProvider.deallocate(messageId)
1606
+ this._invokeStoreProcessingQueue()
1607
+ break
1608
+ }
1609
+ case 'pubrec': {
1610
+ response = {
1611
+ cmd: 'pubrel',
1612
+ qos: 2,
1613
+ messageId: messageId
1614
+ }
1615
+ const pubrecRC = packet.reasonCode
1616
+
1617
+ if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
1618
+ err = new Error('Publish error: ' + errors[pubrecRC])
1619
+ err.code = pubrecRC
1620
+ cb(err, packet)
1621
+ } else {
1622
+ this._sendPacket(response)
1623
+ }
1624
+ break
1625
+ }
1626
+ case 'suback': {
1627
+ delete this.outgoing[messageId]
1628
+ this.messageIdProvider.deallocate(messageId)
1629
+ for (let grantedI = 0; grantedI < packet.granted.length; grantedI++) {
1630
+ if ((packet.granted[grantedI] & 0x80) !== 0) {
1631
+ // suback with Failure status
1632
+ const topics = this.messageIdToTopic[messageId]
1633
+ if (topics) {
1634
+ topics.forEach(function (topic) {
1635
+ delete that._resubscribeTopics[topic]
1636
+ })
1637
+ }
1638
+ }
1639
+ }
1640
+ this._invokeStoreProcessingQueue()
1641
+ cb(null, packet)
1642
+ break
1643
+ }
1644
+ case 'unsuback': {
1645
+ delete this.outgoing[messageId]
1646
+ this.messageIdProvider.deallocate(messageId)
1647
+ this._invokeStoreProcessingQueue()
1648
+ cb(null)
1649
+ break
1650
+ }
1651
+ default:
1652
+ that.emit('error', new Error('unrecognized packet type'))
1653
+ }
1654
+
1655
+ if (this.disconnecting &&
1656
+ Object.keys(this.outgoing).length === 0) {
1657
+ this.emit('outgoingEmpty')
1658
+ }
1659
+ }
1660
+
1661
+ /**
1662
+ * _handlePubrel
1663
+ *
1664
+ * @param {Object} packet
1665
+ * @api private
1666
+ */
1667
+ MqttClient.prototype._handlePubrel = function (packet, callback) {
1668
+ debug('handling pubrel packet')
1669
+ callback = typeof callback !== 'undefined' ? callback : nop
1670
+ const messageId = packet.messageId
1671
+ const that = this
1672
+
1673
+ const comp = { cmd: 'pubcomp', messageId: messageId }
1674
+
1675
+ that.incomingStore.get(packet, function (err, pub) {
1676
+ if (!err) {
1677
+ that.emit('message', pub.topic, pub.payload, pub)
1678
+ that.handleMessage(pub, function (err) {
1679
+ if (err) {
1680
+ return callback(err)
1681
+ }
1682
+ that.incomingStore.del(pub, nop)
1683
+ that._sendPacket(comp, callback)
1684
+ })
1685
+ } else {
1686
+ that._sendPacket(comp, callback)
1687
+ }
1688
+ })
1689
+ }
1690
+
1691
+ /**
1692
+ * _handleDisconnect
1693
+ *
1694
+ * @param {Object} packet
1695
+ * @api private
1696
+ */
1697
+ MqttClient.prototype._handleDisconnect = function (packet) {
1698
+ this.emit('disconnect', packet)
1699
+ }
1700
+
1701
+ /**
1702
+ * _nextId
1703
+ * @return unsigned int
1704
+ */
1705
+ MqttClient.prototype._nextId = function () {
1706
+ return this.messageIdProvider.allocate()
1707
+ }
1708
+
1709
+ /**
1710
+ * getLastMessageId
1711
+ * @return unsigned int
1712
+ */
1713
+ MqttClient.prototype.getLastMessageId = function () {
1714
+ return this.messageIdProvider.getLastAllocated()
1715
+ }
1716
+
1717
+ /**
1718
+ * _resubscribe
1719
+ * @api private
1720
+ */
1721
+ MqttClient.prototype._resubscribe = function () {
1722
+ debug('_resubscribe')
1723
+ const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
1724
+ if (!this._firstConnection &&
1725
+ (this.options.clean || (this.options.protocolVersion === 5 && !this.connackPacket.sessionPresent)) &&
1726
+ _resubscribeTopicsKeys.length > 0) {
1727
+ if (this.options.resubscribe) {
1728
+ if (this.options.protocolVersion === 5) {
1729
+ debug('_resubscribe: protocolVersion 5')
1730
+ for (let topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {
1731
+ const resubscribeTopic = {}
1732
+ resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]
1733
+ resubscribeTopic.resubscribe = true
1734
+ this.subscribe(resubscribeTopic, { properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties })
1735
+ }
1736
+ } else {
1737
+ this._resubscribeTopics.resubscribe = true
1738
+ this.subscribe(this._resubscribeTopics)
1739
+ }
1740
+ } else {
1741
+ this._resubscribeTopics = {}
1742
+ }
1743
+ }
1744
+
1745
+ this._firstConnection = false
1746
+ }
1747
+
1748
+ /**
1749
+ * _onConnect
1750
+ *
1751
+ * @api private
1752
+ */
1753
+ MqttClient.prototype._onConnect = function (packet) {
1754
+ if (this.disconnected) {
1755
+ this.emit('connect', packet)
1756
+ return
1757
+ }
1758
+
1759
+ const that = this
1760
+
1761
+ this.connackPacket = packet
1762
+ this.messageIdProvider.clear()
1763
+ this._setupPingTimer()
1764
+
1765
+ this.connected = true
1766
+
1767
+ function startStreamProcess () {
1768
+ let outStore = that.outgoingStore.createStream()
1769
+
1770
+ function clearStoreProcessing () {
1771
+ that._storeProcessing = false
1772
+ that._packetIdsDuringStoreProcessing = {}
1773
+ }
1774
+
1775
+ that.once('close', remove)
1776
+ outStore.on('error', function (err) {
1777
+ clearStoreProcessing()
1778
+ that._flushStoreProcessingQueue()
1779
+ that.removeListener('close', remove)
1780
+ that.emit('error', err)
1781
+ })
1782
+
1783
+ function remove () {
1784
+ outStore.destroy()
1785
+ outStore = null
1786
+ that._flushStoreProcessingQueue()
1787
+ clearStoreProcessing()
1788
+ }
1789
+
1790
+ function storeDeliver () {
1791
+ // edge case, we wrapped this twice
1792
+ if (!outStore) {
1793
+ return
1794
+ }
1795
+ that._storeProcessing = true
1796
+
1797
+ const packet = outStore.read(1)
1798
+
1799
+ let cb
1800
+
1801
+ if (!packet) {
1802
+ // read when data is available in the future
1803
+ outStore.once('readable', storeDeliver)
1804
+ return
1805
+ }
1806
+
1807
+ // Skip already processed store packets
1808
+ if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
1809
+ storeDeliver()
1810
+ return
1811
+ }
1812
+
1813
+ // Avoid unnecessary stream read operations when disconnected
1814
+ if (!that.disconnecting && !that.reconnectTimer) {
1815
+ cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null
1816
+ that.outgoing[packet.messageId] = {
1817
+ volatile: false,
1818
+ cb: function (err, status) {
1819
+ // Ensure that the original callback passed in to publish gets invoked
1820
+ if (cb) {
1821
+ cb(err, status)
1822
+ }
1823
+
1824
+ storeDeliver()
1825
+ }
1826
+ }
1827
+ that._packetIdsDuringStoreProcessing[packet.messageId] = true
1828
+ if (that.messageIdProvider.register(packet.messageId)) {
1829
+ that._sendPacket(packet)
1830
+ } else {
1831
+ debug('messageId: %d has already used.', packet.messageId)
1832
+ }
1833
+ } else if (outStore.destroy) {
1834
+ outStore.destroy()
1835
+ }
1836
+ }
1837
+
1838
+ outStore.on('end', function () {
1839
+ let allProcessed = true
1840
+ for (const id in that._packetIdsDuringStoreProcessing) {
1841
+ if (!that._packetIdsDuringStoreProcessing[id]) {
1842
+ allProcessed = false
1843
+ break
1844
+ }
1845
+ }
1846
+ if (allProcessed) {
1847
+ clearStoreProcessing()
1848
+ that.removeListener('close', remove)
1849
+ that._invokeAllStoreProcessingQueue()
1850
+ that.emit('connect', packet)
1851
+ } else {
1852
+ startStreamProcess()
1853
+ }
1854
+ })
1855
+ storeDeliver()
1856
+ }
1857
+ // start flowing
1858
+ startStreamProcess()
1859
+ }
1860
+
1861
+ MqttClient.prototype._invokeStoreProcessingQueue = function () {
1862
+ if (this._storeProcessingQueue.length > 0) {
1863
+ const f = this._storeProcessingQueue[0]
1864
+ if (f && f.invoke()) {
1865
+ this._storeProcessingQueue.shift()
1866
+ return true
1867
+ }
1868
+ }
1869
+ return false
1870
+ }
1871
+
1872
+ MqttClient.prototype._invokeAllStoreProcessingQueue = function () {
1873
+ while (this._invokeStoreProcessingQueue()) { /* empty */ }
1874
+ }
1875
+
1876
+ MqttClient.prototype._flushStoreProcessingQueue = function () {
1877
+ for (const f of this._storeProcessingQueue) {
1878
+ if (f.cbStorePut) f.cbStorePut(new Error('Connection closed'))
1879
+ if (f.callback) f.callback(new Error('Connection closed'))
1880
+ }
1881
+ this._storeProcessingQueue.splice(0)
1882
+ }
1883
+
1884
+ module.exports = MqttClient