mqtt 5.15.1 → 5.16.0

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 (40) hide show
  1. package/README.md +73 -0
  2. package/build/lib/KeepaliveManager.js +1 -1
  3. package/build/lib/KeepaliveManager.js.map +1 -1
  4. package/build/lib/client.d.ts +16 -1
  5. package/build/lib/client.js +129 -23
  6. package/build/lib/client.js.map +1 -1
  7. package/build/lib/connect/index.js +15 -2
  8. package/build/lib/connect/index.js.map +1 -1
  9. package/build/lib/connect/tls.js +1 -1
  10. package/build/lib/connect/tls.js.map +1 -1
  11. package/build/lib/handlers/ack.d.ts +1 -0
  12. package/build/lib/handlers/ack.js +13 -1
  13. package/build/lib/handlers/ack.js.map +1 -1
  14. package/build/lib/handlers/auth.d.ts +6 -2
  15. package/build/lib/handlers/auth.js +31 -9
  16. package/build/lib/handlers/auth.js.map +1 -1
  17. package/build/lib/handlers/connack.d.ts +4 -2
  18. package/build/lib/handlers/connack.js +24 -14
  19. package/build/lib/handlers/connack.js.map +1 -1
  20. package/build/lib/handlers/index.js +40 -16
  21. package/build/lib/handlers/index.js.map +1 -1
  22. package/build/lib/handlers/publish.js +35 -11
  23. package/build/lib/handlers/publish.js.map +1 -1
  24. package/build/lib/handlers/pubrel.js +1 -0
  25. package/build/lib/handlers/pubrel.js.map +1 -1
  26. package/build/lib/number-allocator.d.ts +12 -0
  27. package/build/lib/number-allocator.js +61 -0
  28. package/build/lib/number-allocator.js.map +1 -0
  29. package/build/lib/shared.d.ts +5 -1
  30. package/build/lib/shared.js.map +1 -1
  31. package/build/lib/topic-alias-send.js +1 -1
  32. package/build/lib/topic-alias-send.js.map +1 -1
  33. package/build/lib/unique-message-id-provider.js +1 -1
  34. package/build/lib/unique-message-id-provider.js.map +1 -1
  35. package/build/mqtt.d.ts +1 -0
  36. package/build/tsconfig.build.tsbuildinfo +1 -1
  37. package/dist/mqtt.esm.js +8 -8
  38. package/dist/mqtt.js +455 -2996
  39. package/dist/mqtt.min.js +8 -8
  40. package/package.json +5 -5
package/README.md CHANGED
@@ -343,6 +343,8 @@ Also user can manually register topic-alias pair using PUBLISH topic:'some', ta:
343
343
  - [`mqtt.Client#reconnect()`](#reconnect)
344
344
  - [`mqtt.Client#handleMessage()`](#handleMessage)
345
345
  - [`mqtt.Client#connected`](#connected)
346
+ - [`mqtt.Client#keepalive`](#keepalive)
347
+ - [`mqtt.Client#serverProperties`](#serverProperties)
346
348
  - [`mqtt.Client#reconnecting`](#reconnecting)
347
349
  - [`mqtt.Client#getLastMessageId()`](#getLastMessageId)
348
350
  - [`mqtt.Store()`](#store)
@@ -760,6 +762,77 @@ Boolean : set to `true` if the client is connected. `false` otherwise.
760
762
 
761
763
  ---
762
764
 
765
+ <a name="keepalive"></a>
766
+
767
+ ### mqtt.Client#keepalive
768
+
769
+ Number : the effective keepalive, in seconds. It is the `Server Keep Alive` the
770
+ broker sent in the CONNACK that opened the current connection when there is one,
771
+ the configured `keepalive` option otherwise, so while the client is not connected
772
+ it is always the configured value.
773
+
774
+ Three cases make the broker value irrelevant:
775
+
776
+ - `keepalive: 0` disables keepalive, and a broker cannot turn it back on.
777
+ - a `Server Keep Alive` of `0` is the broker declining to set one, so the
778
+ configured `keepalive` stays in use.
779
+ - a refused CONNACK opens no connection to keep alive, so its `Server Keep Alive`
780
+ is ignored here. [`client.serverProperties`](#serverProperties) still reports
781
+ it.
782
+
783
+ ---
784
+
785
+ <a name="serverProperties"></a>
786
+
787
+ ### mqtt.Client#serverProperties
788
+
789
+ Object : the MQTT 5.0 properties the broker sent in the CONNACK of the current
790
+ connection, `undefined` when there is none. Read only, and reset both when the
791
+ connection closes and when the next connection attempt starts.
792
+
793
+ A refused CONNACK counts, which is the only place `reasonString` and
794
+ `serverReference` ever appear. With the default `reconnectOnConnackError: false`
795
+ no `close` follows a refusal, so those stay readable until the next connection
796
+ attempt - but they describe a connection that was never opened, which is why
797
+ [`client.keepalive`](#keepalive) ignores their `serverKeepAlive`.
798
+
799
+ Broker values are kept here and are never written back into the options object
800
+ given to `mqtt.connect()`.
801
+
802
+ #### Migrating from 5.x
803
+
804
+ The broker no longer overwrites the options object:
805
+
806
+ - `client.options.keepalive` stays the configured value after connecting. Read
807
+ [`client.keepalive`](#keepalive) for the one in use on the current connection.
808
+ - `client.options.properties.maximumPacketSize` stays the configured value, and
809
+ is the only limit applied to inbound packets. Read
810
+ `client.serverProperties.maximumPacketSize` for the broker's limit.
811
+
812
+ The broker's `maximumPacketSize` is still not applied to outbound packets: it is
813
+ up to the application not to publish more than the broker accepts.
814
+
815
+ Two things changed in how an inbound packet larger than
816
+ `properties.maximumPacketSize` is treated:
817
+
818
+ - the limit now counts the whole packet. The fixed header byte and the bytes
819
+ encoding the Remaining Length count toward it, as MQTT 5.0 requires
820
+ (§3.1.2.11.4 with §2.1.4); 5.x compared the limit against the Remaining
821
+ Length alone. The same configured limit therefore rejects packets 2 to 5 bytes
822
+ smaller than it used to - 2 bytes for packets under 128 bytes, one more for
823
+ every further step of the Remaining Length. A limit set right at the size of
824
+ the largest packet expected needs raising by that much.
825
+ - an oversized packet no longer ends the client. 5.x called
826
+ `end({ reasonCode: 149 })`: it sent a DISCONNECT and stopped the client for
827
+ good. The connection is now dropped like any other failure, no DISCONNECT is
828
+ sent, and the client reconnects. This was deliberate - one oversized packet
829
+ was a kill switch any broker could pull permanently - but it cuts both ways: a
830
+ broker holding a retained message that is always too large becomes a reconnect
831
+ loop where 5.x stopped after the first one. Applications that want the old
832
+ stop can call `end()` from the `error` handler on reason code 149.
833
+
834
+ ---
835
+
763
836
  <a name="getLastMessageId"></a>
764
837
 
765
838
  ### mqtt.Client#getLastMessageId()
@@ -30,7 +30,7 @@ class KeepaliveManager {
30
30
  'clear' in variant
31
31
  ? variant
32
32
  : (0, get_timer_1.default)(variant);
33
- this.setKeepalive(client.options.keepalive);
33
+ this.setKeepalive(client.keepalive);
34
34
  }
35
35
  clear() {
36
36
  if (this.timerId) {
@@ -1 +1 @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@ import { type DuplexOptions } from 'readable-stream';
3
3
  import type { ClientOptions } from 'ws';
4
4
  import { type ClientRequestArgs } from 'http';
5
5
  import Store, { type IStore } from './store';
6
+ import { type PendingCommand } from './handlers/ack';
6
7
  import { type IMessageIdProvider } from './default-message-id-provider';
7
- import { type DoneCallback, type ErrorWithReasonCode, type IStream, type StreamBuilder, type TimerVariant, type VoidCallback } from './shared';
8
+ import { type DoneCallback, ErrorWithReasonCode, type IStream, type StreamBuilder, type TimerVariant, type VoidCallback } from './shared';
8
9
  import { TypedEventEmitter } from './TypedEmitter';
9
10
  import KeepaliveManager from './KeepaliveManager';
10
11
  import { type Timer } from './get-timer';
@@ -151,6 +152,7 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
151
152
  messageIdProvider: IMessageIdProvider;
152
153
  outgoing: Record<number, {
153
154
  volatile: boolean;
155
+ cmd: PendingCommand;
154
156
  cb: (err: Error, packet?: Packet) => void;
155
157
  }>;
156
158
  messageIdToTopic: Record<number, string[]>;
@@ -171,15 +173,26 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
171
173
  private _firstConnection;
172
174
  private topicAliasRecv;
173
175
  private topicAliasSend;
176
+ private _incomingQoS2Ids;
177
+ private _receiveMaximum;
174
178
  private _deferredReconnect;
179
+ private _currentPump;
180
+ private connackReceived;
181
+ private reconnectSuppressed;
182
+ private _authenticationMethod;
175
183
  private connackPacket;
184
+ private _serverProperties;
176
185
  static defaultId(): string;
177
186
  constructor(streamBuilder: StreamBuilder, options: IClientOptions);
178
187
  handleAuth(packet: IAuthPacket, callback: PacketCallback): void;
179
188
  handleMessage(packet: IPublishPacket, callback: DoneCallback): void;
180
189
  private _nextId;
181
190
  getLastMessageId(): number;
191
+ private _trackIncomingQoS2Publish;
192
+ private _releaseIncomingQoS2Publish;
193
+ private _discardIncomingQoS2State;
182
194
  connect(): this;
195
+ private _onConnackTimeout;
183
196
  publish(topic: string, message: string | Buffer): MqttClient;
184
197
  publish(topic: string, message: string | Buffer, callback?: PacketCallback): MqttClient;
185
198
  publish(topic: string, message: string | Buffer, opts?: IClientPublishOptions, callback?: PacketCallback): MqttClient;
@@ -222,6 +235,8 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
222
235
  private _writePacket;
223
236
  private _sendPacket;
224
237
  private _storePacket;
238
+ get serverProperties(): IConnackPacket['properties'];
239
+ get keepalive(): number;
225
240
  private _setupKeepaliveManager;
226
241
  private _destroyKeepaliveManager;
227
242
  reschedulePing(force?: boolean): void;
@@ -43,6 +43,7 @@ const debug_1 = __importDefault(require("debug"));
43
43
  const validations = __importStar(require("./validations"));
44
44
  const store_1 = __importDefault(require("./store"));
45
45
  const handlers_1 = __importDefault(require("./handlers"));
46
+ const ack_1 = require("./handlers/ack");
46
47
  const default_message_id_provider_1 = __importDefault(require("./default-message-id-provider"));
47
48
  const topic_alias_recv_1 = __importDefault(require("./topic-alias-recv"));
48
49
  const shared_1 = require("./shared");
@@ -56,6 +57,8 @@ const setImmediate = globalThis.setImmediate ||
56
57
  callback(...args);
57
58
  });
58
59
  });
60
+ const MAX_RECEIVE_MAXIMUM = 0xffff;
61
+ const RECEIVE_MAXIMUM_EXCEEDED = 147;
59
62
  const defaultConnectOptions = {
60
63
  keepalive: 60,
61
64
  reschedulePings: true,
@@ -98,8 +101,15 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
98
101
  _firstConnection;
99
102
  topicAliasRecv;
100
103
  topicAliasSend;
104
+ _incomingQoS2Ids;
105
+ _receiveMaximum;
101
106
  _deferredReconnect;
107
+ _currentPump;
108
+ connackReceived;
109
+ reconnectSuppressed;
110
+ _authenticationMethod;
102
111
  connackPacket;
112
+ _serverProperties;
103
113
  static defaultId() {
104
114
  return `mqttjs_${Math.random().toString(16).substr(2, 8)}`;
105
115
  }
@@ -153,6 +163,19 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
153
163
  : this.options.messageIdProvider;
154
164
  this.outgoingStore = options.outgoingStore || new store_1.default();
155
165
  this.incomingStore = options.incomingStore || new store_1.default();
166
+ this._incomingQoS2Ids = new Set();
167
+ this._receiveMaximum = MAX_RECEIVE_MAXIMUM;
168
+ const receiveMaximum = options.properties?.receiveMaximum;
169
+ if (receiveMaximum !== undefined) {
170
+ if (Number.isInteger(receiveMaximum) &&
171
+ receiveMaximum >= 1 &&
172
+ receiveMaximum <= MAX_RECEIVE_MAXIMUM) {
173
+ this._receiveMaximum = receiveMaximum;
174
+ }
175
+ else {
176
+ this.log('MqttClient :: options.properties.receiveMaximum %o is not an integer between 1 and %d, enforcing and advertising %d instead', receiveMaximum, MAX_RECEIVE_MAXIMUM, MAX_RECEIVE_MAXIMUM);
177
+ }
178
+ }
156
179
  this.queueQoSZero =
157
180
  options.queueQoSZero === undefined ? true : options.queueQoSZero;
158
181
  this._resubscribeTopics = {};
@@ -163,6 +186,8 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
163
186
  this.reconnecting = false;
164
187
  this.queue = [];
165
188
  this.connackTimer = null;
189
+ this.connackReceived = false;
190
+ this.reconnectSuppressed = false;
166
191
  this.reconnectTimer = null;
167
192
  this._storeProcessing = false;
168
193
  this._packetIdsDuringStoreProcessing = {};
@@ -217,6 +242,7 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
217
242
  this.log('close :: clearing connackTimer');
218
243
  clearTimeout(this.connackTimer);
219
244
  this._destroyKeepaliveManager();
245
+ this._serverProperties = undefined;
220
246
  if (this.topicAliasRecv) {
221
247
  this.topicAliasRecv.clear();
222
248
  }
@@ -240,16 +266,58 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
240
266
  getLastMessageId() {
241
267
  return this.messageIdProvider.getLastAllocated();
242
268
  }
269
+ _trackIncomingQoS2Publish(messageId, done, pump) {
270
+ if (this._incomingQoS2Ids.has(messageId)) {
271
+ return true;
272
+ }
273
+ if (this.options.protocolVersion === 5 &&
274
+ this._incomingQoS2Ids.size >= this._receiveMaximum) {
275
+ this.log('_trackIncomingQoS2Publish :: inbound QoS 2 messages exceeded receiveMaximum %d', this._receiveMaximum);
276
+ pump?.discardParsedPackets();
277
+ if (!pump || pump.isCurrent()) {
278
+ this._cleanUp(true);
279
+ }
280
+ done();
281
+ this.emit('error', new shared_1.ErrorWithReasonCode(`${ack_1.ReasonCodes[RECEIVE_MAXIMUM_EXCEEDED]}: ${this._incomingQoS2Ids.size + 1} inbound QoS 2 messages in flight, receiveMaximum is ${this._receiveMaximum}`, RECEIVE_MAXIMUM_EXCEEDED));
282
+ return false;
283
+ }
284
+ this._incomingQoS2Ids.add(messageId);
285
+ return true;
286
+ }
287
+ _releaseIncomingQoS2Publish(messageId) {
288
+ this._incomingQoS2Ids.delete(messageId);
289
+ }
290
+ _discardIncomingQoS2State() {
291
+ if (this._incomingQoS2Ids.size === 0) {
292
+ return;
293
+ }
294
+ this.log('_discardIncomingQoS2State :: session not resumed, dropping %d inbound QoS 2 message(s)', this._incomingQoS2Ids.size);
295
+ for (const messageId of this._incomingQoS2Ids) {
296
+ this.incomingStore.del({ messageId }, this.noop);
297
+ }
298
+ this._incomingQoS2Ids.clear();
299
+ }
243
300
  connect() {
244
301
  const writable = new readable_stream_1.Writable();
245
302
  const parser = mqtt_packet_1.default.parser(this.options);
246
303
  let completeParse = null;
247
304
  const packets = [];
305
+ const pump = {
306
+ discardParsedPackets: () => {
307
+ packets.length = 0;
308
+ },
309
+ isCurrent: () => this._currentPump === pump,
310
+ };
311
+ this._currentPump = pump;
312
+ this.connackReceived = false;
313
+ this.reconnectSuppressed = false;
248
314
  this.log('connect :: calling method to clear reconnect');
249
315
  this._clearReconnect();
316
+ this._serverProperties = undefined;
250
317
  if (this.disconnected && !this.reconnecting) {
251
318
  this.incomingStore = this.options.incomingStore || new store_1.default();
252
319
  this.outgoingStore = this.options.outgoingStore || new store_1.default();
320
+ this._incomingQoS2Ids.clear();
253
321
  this.disconnecting = false;
254
322
  this.disconnected = false;
255
323
  }
@@ -261,10 +329,14 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
261
329
  });
262
330
  const work = () => {
263
331
  this.log('work :: getting next packet in queue');
332
+ if (this._currentPump !== pump) {
333
+ this.log('work :: pump superseded, dropping %d queued packets', packets.length);
334
+ packets.length = 0;
335
+ }
264
336
  const packet = packets.shift();
265
337
  if (packet) {
266
338
  this.log('work :: packet pulled from queue');
267
- (0, handlers_1.default)(this, packet, nextTickWork);
339
+ (0, handlers_1.default)(this, packet, nextTickWork, pump);
268
340
  }
269
341
  else {
270
342
  this.log('work :: no packets in queue');
@@ -282,7 +354,8 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
282
354
  else {
283
355
  const done = completeParse;
284
356
  completeParse = null;
285
- done();
357
+ if (done)
358
+ done();
286
359
  }
287
360
  };
288
361
  writable._write = (buf, enc, done) => {
@@ -320,8 +393,13 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
320
393
  keepalive: this.options.keepalive,
321
394
  username: this.options.username,
322
395
  password: this.options.password,
323
- properties: this.options.properties,
396
+ properties: this.options.properties
397
+ ? { ...this.options.properties }
398
+ : undefined,
324
399
  };
400
+ if (connectPacket.properties?.receiveMaximum !== undefined) {
401
+ connectPacket.properties.receiveMaximum = this._receiveMaximum;
402
+ }
325
403
  if (this.options.will) {
326
404
  connectPacket.will = {
327
405
  ...this.options.will,
@@ -337,6 +415,8 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
337
415
  this.topicAliasRecv.max;
338
416
  }
339
417
  }
418
+ this._authenticationMethod =
419
+ connectPacket.properties?.authenticationMethod;
340
420
  this._writePacket(connectPacket);
341
421
  parser.on('error', this.emit.bind(this, 'error'));
342
422
  if (this.options.properties) {
@@ -358,13 +438,14 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
358
438
  }
359
439
  this.stream.setMaxListeners(1000);
360
440
  clearTimeout(this.connackTimer);
361
- this.connackTimer = setTimeout(() => {
362
- this.log('!!connectTimeout hit!! Calling _cleanUp with force `true`');
363
- this.emit('error', new Error('connack timeout'));
364
- this._cleanUp(true);
365
- }, this.options.connectTimeout);
441
+ this.connackTimer = setTimeout(() => this._onConnackTimeout(), this.options.connectTimeout);
366
442
  return this;
367
443
  }
444
+ _onConnackTimeout() {
445
+ this.log('!!connectTimeout hit!! Calling _cleanUp with force `true`');
446
+ this._cleanUp(true);
447
+ this.emit('error', new Error('connack timeout'));
448
+ }
368
449
  publish(topic, message, opts, callback) {
369
450
  this.log('publish :: message `%s` to topic `%s`', message, topic);
370
451
  const { options } = this;
@@ -410,6 +491,7 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
410
491
  case 2:
411
492
  this.outgoing[packet.messageId] = {
412
493
  volatile: false,
494
+ cmd: 'publish',
413
495
  cb: callback || this.noop,
414
496
  };
415
497
  this.log('MqttClient:publish: packet cmd: %s', packet.cmd);
@@ -550,19 +632,22 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
550
632
  const promise = new Promise((resolve, reject) => {
551
633
  this.outgoing[packet.messageId] = {
552
634
  volatile: true,
553
- cb(err, packet2) {
554
- if (!err) {
555
- const { granted } = packet2;
556
- for (let grantedI = 0; grantedI < granted.length; grantedI += 1) {
557
- chunkedSubs[grantedI].qos = granted[grantedI];
558
- }
635
+ cmd: 'subscribe',
636
+ cb: (err, packet2) => {
637
+ if (err) {
638
+ reject(new shared_1.ErrorWithSubackPacket(err.message, packet2));
639
+ return;
559
640
  }
560
- if (!err) {
561
- resolve(packet2);
641
+ const { granted } = packet2;
642
+ if (granted.length !== chunkedSubs.length) {
643
+ reject(new shared_1.ErrorWithSubackPacket(`Protocol error: suback granted ${granted.length} reason code(s) for ${chunkedSubs.length} subscription(s)`, packet2));
644
+ this._cleanUp(true);
645
+ return;
562
646
  }
563
- else {
564
- reject(new shared_1.ErrorWithSubackPacket(err.message, packet2));
647
+ for (let grantedI = 0; grantedI < granted.length; grantedI += 1) {
648
+ chunkedSubs[grantedI].qos = granted[grantedI];
565
649
  }
650
+ resolve(packet2);
566
651
  },
567
652
  };
568
653
  });
@@ -656,6 +741,7 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
656
741
  }
657
742
  this.outgoing[packet.messageId] = {
658
743
  volatile: true,
744
+ cmd: 'unsubscribe',
659
745
  cb: callback,
660
746
  };
661
747
  this.log('unsubscribe: call _sendPacket');
@@ -702,6 +788,7 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
702
788
  const closeStores = () => {
703
789
  this.log('end :: closeStores: closing incoming and outgoing stores');
704
790
  this.disconnected = true;
791
+ this._incomingQoS2Ids.clear();
705
792
  this.incomingStore.close((e1) => {
706
793
  this.outgoingStore.close((e2) => {
707
794
  this.log('end :: closeStores: emitting end');
@@ -778,6 +865,7 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
778
865
  }
779
866
  this.incomingStore = this.options.incomingStore || new store_1.default();
780
867
  this.outgoingStore = this.options.outgoingStore || new store_1.default();
868
+ this._incomingQoS2Ids.clear();
781
869
  this.disconnecting = false;
782
870
  this.disconnected = false;
783
871
  this._deferredReconnect = null;
@@ -862,6 +950,7 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
862
950
  }
863
951
  _setupReconnect() {
864
952
  if (!this.disconnecting &&
953
+ !this.reconnectSuppressed &&
865
954
  !this.reconnectTimer &&
866
955
  this.options.reconnectPeriod > 0) {
867
956
  if (!this.reconnecting) {
@@ -1096,9 +1185,20 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
1096
1185
  cb(new Error('No connection to broker'));
1097
1186
  }
1098
1187
  }
1188
+ get serverProperties() {
1189
+ return this._serverProperties;
1190
+ }
1191
+ get keepalive() {
1192
+ const serverKeepAlive = this.connected
1193
+ ? this._serverProperties?.serverKeepAlive
1194
+ : undefined;
1195
+ return serverKeepAlive && this.options.keepalive
1196
+ ? serverKeepAlive
1197
+ : this.options.keepalive;
1198
+ }
1099
1199
  _setupKeepaliveManager() {
1100
- this.log('_setupKeepaliveManager :: keepalive %d (seconds)', this.options.keepalive);
1101
- if (!this.keepaliveManager && this.options.keepalive) {
1200
+ this.log('_setupKeepaliveManager :: keepalive %d (seconds)', this.keepalive);
1201
+ if (!this.keepaliveManager && this.keepalive) {
1102
1202
  this.keepaliveManager = new KeepaliveManager_1.default(this, this.options.timerVariant);
1103
1203
  }
1104
1204
  }
@@ -1111,7 +1211,7 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
1111
1211
  }
1112
1212
  reschedulePing(force = false) {
1113
1213
  if (this.keepaliveManager &&
1114
- this.options.keepalive &&
1214
+ this.keepalive &&
1115
1215
  (force || this.options.reschedulePings)) {
1116
1216
  this._reschedulePing();
1117
1217
  }
@@ -1125,9 +1225,9 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
1125
1225
  this._sendPacket({ cmd: 'pingreq' });
1126
1226
  }
1127
1227
  onKeepaliveTimeout() {
1128
- this.emit('error', new Error('Keepalive timeout'));
1129
1228
  this.log('onKeepaliveTimeout :: calling _cleanUp with force true');
1130
1229
  this._cleanUp(true);
1230
+ this.emit('error', new Error('Keepalive timeout'));
1131
1231
  }
1132
1232
  _resubscribe() {
1133
1233
  this.log('_resubscribe');
@@ -1168,9 +1268,14 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
1168
1268
  return;
1169
1269
  }
1170
1270
  this.connackPacket = packet;
1271
+ const sessionResumed = !this.options.clean &&
1272
+ (this.options.protocolVersion < 4 || packet.sessionPresent === true);
1273
+ if (!sessionResumed) {
1274
+ this._discardIncomingQoS2State();
1275
+ }
1171
1276
  this.messageIdProvider.clear();
1172
- this._setupKeepaliveManager();
1173
1277
  this.connected = true;
1278
+ this._setupKeepaliveManager();
1174
1279
  const startStreamProcess = () => {
1175
1280
  let outStore = this.outgoingStore.createStream();
1176
1281
  const remove = () => {
@@ -1211,6 +1316,7 @@ class MqttClient extends TypedEmitter_1.TypedEventEmitter {
1211
1316
  : null;
1212
1317
  this.outgoing[packet2.messageId] = {
1213
1318
  volatile: false,
1319
+ cmd: packet2.cmd,
1214
1320
  cb(err, status) {
1215
1321
  if (cb) {
1216
1322
  cb(err, status);