mqtt 4.3.4 → 4.3.7

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