mqtt 5.0.0-beta.2 → 5.0.0-beta.4

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