mqtt 5.0.0-beta.2 → 5.0.0-beta.3

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