mqtt 4.3.4 → 4.3.7

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