-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
client.ts
2349 lines (2100 loc) · 57.8 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Module dependencies
*/
import TopicAliasRecv from './topic-alias-recv'
import mqttPacket, {
IAuthPacket,
IConnackPacket,
IDisconnectPacket,
IPublishPacket,
ISubscribePacket,
ISubscription,
IUnsubscribePacket,
Packet,
QoS,
ISubackPacket,
IConnectPacket,
} from 'mqtt-packet'
import DefaultMessageIdProvider, {
IMessageIdProvider,
} from './default-message-id-provider'
import { DuplexOptions, Writable } from 'readable-stream'
import clone from 'rfdc/default'
import * as validations from './validations'
import _debug from 'debug'
import Store, { IStore } from './store'
import handlePacket from './handlers'
import { ClientOptions } from 'ws'
import { ClientRequestArgs } from 'http'
import {
DoneCallback,
ErrorWithReasonCode,
GenericCallback,
IStream,
MQTTJS_VERSION,
StreamBuilder,
TimerVariant,
VoidCallback,
nextTick,
} from './shared'
import TopicAliasSend from './topic-alias-send'
import { TypedEventEmitter } from './TypedEmitter'
import PingTimer from './PingTimer'
import isBrowser, { isWebWorker } from './is-browser'
const setImmediate =
globalThis.setImmediate ||
(((...args: any[]) => {
const callback = args.shift()
nextTick(() => {
callback(...args)
})
}) as typeof globalThis.setImmediate)
const defaultConnectOptions: IClientOptions = {
keepalive: 60,
reschedulePings: true,
protocolId: 'MQTT',
protocolVersion: 4,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
clean: true,
resubscribe: true,
writeCache: true,
timerVariant: 'auto',
}
export type MqttProtocol =
| 'wss'
| 'ws'
| 'mqtt'
| 'mqtts'
| 'tcp'
| 'ssl'
| 'wx'
| 'wxs'
| 'ali'
| 'alis'
export type StorePutCallback = () => void
export interface ISecureClientOptions {
/**
* optional private keys in PEM format
*/
key?: string | string[] | Buffer | Buffer[] | any[]
keyPath?: string
/**
* optional cert chains in PEM format
*/
cert?: string | string[] | Buffer | Buffer[]
certPath?: string
/**
* Optionally override the trusted CA certificates in PEM format
*/
ca?: string | string[] | Buffer | Buffer[]
caPaths?: string | string[]
rejectUnauthorized?: boolean
/**
* optional alpn's
*/
ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array
}
export type AckHandler = (
topic: string,
message: Buffer,
packet: any,
cb: (error: Error | number, code?: number) => void,
) => void
export interface IClientOptions extends ISecureClientOptions {
/** CLIENT PROPERTIES */
/** Encoding to use. Example 'binary' */
encoding?: BufferEncoding
/** Set browser buffer size. Default to 512KB */
browserBufferSize?: number
/** used in ws protocol to set `objectMode` */
binary?: boolean
/** Used on ali protocol */
my?: any
/** Manually call `connect` after creating client instance */
manualConnect?: boolean
/** Custom auth packet properties */
authPacket?: Partial<IAuthPacket>
/** Disable/Enable writeToStream.cacheNumbers */
writeCache?: boolean
/** Should be set to `host` */
servername?: string
/** The default protocol to use when using `servers` and no protocol is specified */
defaultProtocol?: MqttProtocol
/** Support clientId passed in the query string of the url */
query?: Record<string, string>
/** Auth string in the format <username>:<password> */
auth?: string
/** Custom ack handler */
customHandleAcks?: AckHandler
/** Broker port */
port?: number
/** Broker host. Does NOT include port */
host?: string
/** @deprecated use `host instead */
hostname?: string
/** Websocket `path` added as suffix */
path?: string
/** The `MqttProtocol` to use */
protocol?: MqttProtocol
/** Websocket options */
wsOptions?: ClientOptions | ClientRequestArgs | DuplexOptions
/**
* 1000 milliseconds, interval between two reconnections
*/
reconnectPeriod?: number
/**
* 30 * 1000 milliseconds, time to wait before a CONNACK is received
*/
connectTimeout?: number
/**
* a Store for the incoming packets
*/
incomingStore?: IStore
/**
* a Store for the outgoing packets
*/
outgoingStore?: IStore
/** Enable/Disable queue for QoS 0 packets */
queueQoSZero?: boolean
/** Custom log function, default uses `debug` */
log?: (...args: any[]) => void
/** automatically use topic alias */
autoUseTopicAlias?: boolean
/** automatically assign topic alias */
autoAssignTopicAlias?: boolean
/** Set to false to disable ping reschedule. When enabled ping messages are rescheduled on each message sent */
reschedulePings?: boolean
/** List of broker servers. On each reconnect try the next server will be used */
servers?: Array<{
host: string
port: number
protocol?:
| 'wss'
| 'ws'
| 'mqtt'
| 'mqtts'
| 'tcp'
| 'ssl'
| 'wx'
| 'wxs'
}>
/**
* true, set to false to disable re-subscribe functionality
*/
resubscribe?: boolean
/** when defined this function will be called to transform the url string generated by MqttClient from provided options */
transformWsUrl?: (
url: string,
options: IClientOptions,
client: MqttClient,
) => string
/** when defined this function will be called to create the Websocket instance, used to add custom protocols or websocket implementations */
createWebsocket?: (
url: string,
websocketSubProtocols: string[],
options: IClientOptions,
) => any
/** Custom message id provider */
messageIdProvider?: IMessageIdProvider
/** When using websockets, this is the timeout used when writing to socket. Default 1000 (1s) */
browserBufferTimeout?: number
/**
* When using websockets, this sets the `objectMode` option.
* When in objectMode, streams can push Strings and Buffers
* as well as any other JavaScript object.
* Another major difference is that when in objectMode,
* the internal buffering algorithm counts objects rather than bytes.
* This means if we have a Transform stream with the highWaterMark option set to 5,
* the stream will only buffer a maximum of 5 objects internally
*/
objectMode?: boolean
/** CONNECT PACKET PROPERTIES */
/**
* 'mqttjs_' + Math.random().toString(16).substr(2, 8)
*/
clientId?: string
/**
* 3=MQTT 3.1 4=MQTT 3.1.1 5=MQTT 5.0. Defaults to 4
*/
protocolVersion?: IConnectPacket['protocolVersion']
/**
* 'MQTT'
*/
protocolId?: IConnectPacket['protocolId']
/**
* true, set to false to receive QoS 1 and 2 messages while offline
*/
clean?: boolean
/**
* 60 seconds, set to 0 to disable
*/
keepalive?: number
/**
* the username required by your broker, if any
*/
username?: string
/**
* the password required by your broker, if any
*/
password?: Buffer | string
/**
* a message that will sent by the broker automatically when the client disconnect badly.
*/
will?: IConnectPacket['will']
/** see `connect` packet: https://github.com/mqttjs/mqtt-packet/blob/master/types/index.d.ts#L65 */
properties?: IConnectPacket['properties']
/**
* @description 'auto', set to 'native' or 'worker' if you're having issues with 'auto' detection
*/
timerVariant?: TimerVariant
}
export interface IClientPublishOptions {
/**
* the QoS
*/
qos?: QoS
/**
* the retain flag
*/
retain?: boolean
/**
* whether or not mark a message as duplicate
*/
dup?: boolean
/*
* MQTT 5.0 properties object
*/
properties?: IPublishPacket['properties']
/**
* callback called when message is put into `outgoingStore`
*/
cbStorePut?: StorePutCallback
}
export interface IClientReconnectOptions {
/**
* a Store for the incoming packets
*/
incomingStore?: Store
/**
* a Store for the outgoing packets
*/
outgoingStore?: Store
}
export interface IClientSubscribeProperties {
/*
* MQTT 5.0 properies object of subscribe
* */
properties?: ISubscribePacket['properties']
}
export interface IClientSubscribeOptions extends IClientSubscribeProperties {
/**
* the QoS
*/
qos: QoS
/*
* no local flag
* */
nl?: boolean
/*
* Retain As Published flag
* */
rap?: boolean
/*
* Retain Handling option
* */
rh?: number
}
export interface ISubscriptionRequest extends IClientSubscribeOptions {
/**
* is a subscribed to topic
*/
topic: string
}
export interface ISubscriptionGrant
extends Omit<ISubscriptionRequest, 'qos' | 'properties'> {
/**
* is the granted qos level on it, may return 128 on error
*/
qos: QoS | 128
}
export type ISubscriptionMap = {
/**
* object which has topic names as object keys and as value the options, like {'test1': {qos: 0}, 'test2': {qos: 2}}.
*/
[topic: string]: IClientSubscribeOptions
} & {
resubscribe?: boolean
}
export { IConnackPacket, IDisconnectPacket, IPublishPacket, Packet }
export type OnConnectCallback = (packet: IConnackPacket) => void
export type OnDisconnectCallback = (packet: IDisconnectPacket) => void
export type ClientSubscribeCallback = (
err: Error | null,
granted?: ISubscriptionGrant[],
) => void
export type OnMessageCallback = (
topic: string,
payload: Buffer,
packet: IPublishPacket,
) => void
export type OnPacketCallback = (packet: Packet) => void
export type OnCloseCallback = () => void
export type OnErrorCallback = (error: Error | ErrorWithReasonCode) => void
export type PacketCallback = (error?: Error, packet?: Packet) => any
export type CloseCallback = (error?: Error) => void
export interface MqttClientEventCallbacks {
connect: OnConnectCallback
message: OnMessageCallback
packetsend: OnPacketCallback
packetreceive: OnPacketCallback
disconnect: OnDisconnectCallback
error: OnErrorCallback
close: OnCloseCallback
end: VoidCallback
reconnect: VoidCallback
offline: VoidCallback
outgoingEmpty: VoidCallback
}
/**
* MqttClient constructor
*
* @param {Stream} stream - stream
* @param {Object} [options] - connection options
* (see Connection#connect)
*/
export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbacks> {
public static VERSION = MQTTJS_VERSION
/** Public fields */
/** It's true when client is connected to broker */
public connected: boolean
public disconnecting: boolean
public disconnected: boolean
public reconnecting: boolean
public incomingStore: IStore
public outgoingStore: IStore
public options: IClientOptions
public queueQoSZero: boolean
public _reconnectCount: number
public log: (...args: any[]) => void
public messageIdProvider: IMessageIdProvider
public pingResp: boolean
public outgoing: Record<
number,
{ volatile: boolean; cb: (err: Error, packet?: Packet) => void }
>
public messageIdToTopic: Record<number, string[]>
public noop: (error?: any) => void
public pingTimer: PingTimer
/**
* The connection to the Broker. In browsers env this also have `socket` property
* set to the `WebSocket` instance.
*/
public stream: IStream
public queue: { packet: Packet; cb: PacketCallback }[]
/* Private fields */
/** Function used to build the stream */
private streamBuilder: StreamBuilder
private _resubscribeTopics: ISubscriptionMap
private connackTimer: NodeJS.Timeout
private reconnectTimer: NodeJS.Timeout
private _storeProcessing: boolean
/** keep a reference of packets that have been successfully processed from outgoing store */
private _packetIdsDuringStoreProcessing: Record<number, boolean>
private _storeProcessingQueue: {
invoke: () => any
cbStorePut?: DoneCallback
callback: GenericCallback<any>
}[]
private _firstConnection: boolean
private topicAliasRecv: TopicAliasRecv
private topicAliasSend: TopicAliasSend
private _deferredReconnect: () => void
private connackPacket: IConnackPacket
public static defaultId() {
return `mqttjs_${Math.random().toString(16).substr(2, 8)}`
}
constructor(streamBuilder: StreamBuilder, options: IClientOptions) {
super()
this.options = options || {}
// Defaults
for (const k in defaultConnectOptions) {
if (typeof this.options[k] === 'undefined') {
this.options[k] = defaultConnectOptions[k]
} else {
this.options[k] = options[k]
}
}
this.log = this.options.log || _debug('mqttjs:client')
this.noop = this._noop.bind(this)
this.log('MqttClient :: version:', MqttClient.VERSION)
if (isWebWorker) {
this.log('MqttClient :: environment', 'webworker')
} else {
this.log(
'MqttClient :: environment',
isBrowser ? 'browser' : 'node',
)
}
this.log('MqttClient :: options.protocol', options.protocol)
this.log(
'MqttClient :: options.protocolVersion',
options.protocolVersion,
)
this.log('MqttClient :: options.username', options.username)
this.log('MqttClient :: options.keepalive', options.keepalive)
this.log(
'MqttClient :: options.reconnectPeriod',
options.reconnectPeriod,
)
this.log(
'MqttClient :: options.rejectUnauthorized',
options.rejectUnauthorized,
)
this.log(
'MqttClient :: options.properties.topicAliasMaximum',
options.properties
? options.properties.topicAliasMaximum
: undefined,
)
this.options.clientId =
typeof options.clientId === 'string'
? options.clientId
: MqttClient.defaultId()
this.log('MqttClient :: clientId', this.options.clientId)
this.options.customHandleAcks =
options.protocolVersion === 5 && options.customHandleAcks
? options.customHandleAcks
: (...args) => {
args[3](null, 0)
}
// Disable pre-generated write cache if requested. Will allocate buffers on-the-fly instead. WARNING: This can affect write performance
if (!this.options.writeCache) {
mqttPacket.writeToStream.cacheNumbers = false
}
this.streamBuilder = streamBuilder
this.messageIdProvider =
typeof this.options.messageIdProvider === 'undefined'
? new DefaultMessageIdProvider()
: this.options.messageIdProvider
// Inflight message storages
this.outgoingStore = options.outgoingStore || new Store()
this.incomingStore = options.incomingStore || new Store()
// Should QoS zero messages be queued when the connection is broken?
this.queueQoSZero =
options.queueQoSZero === undefined ? true : options.queueQoSZero
// map of subscribed topics to support reconnection
this._resubscribeTopics = {}
// map of a subscribe messageId and a topic
this.messageIdToTopic = {}
// Ping timer, setup in _setupPingTimer
this.pingTimer = null
// Is the client connected?
this.connected = false
// Are we disconnecting?
this.disconnecting = false
// Are we reconnecting?
this.reconnecting = false
// Packet queue
this.queue = []
// connack timer
this.connackTimer = null
// Reconnect timer
this.reconnectTimer = null
// Is processing store?
this._storeProcessing = false
// Packet Ids are put into the store during store processing
this._packetIdsDuringStoreProcessing = {}
// Store processing queue
this._storeProcessingQueue = []
// Inflight callbacks
this.outgoing = {}
// True if connection is first time.
this._firstConnection = true
if (options.properties && options.properties.topicAliasMaximum > 0) {
if (options.properties.topicAliasMaximum > 0xffff) {
this.log(
'MqttClient :: options.properties.topicAliasMaximum is out of range',
)
} else {
this.topicAliasRecv = new TopicAliasRecv(
options.properties.topicAliasMaximum,
)
}
}
// Send queued packets
this.on('connect', () => {
const { queue } = this
const deliver = () => {
const entry = queue.shift()
this.log('deliver :: entry %o', entry)
let packet = null
if (!entry) {
this._resubscribe()
return
}
packet = entry.packet
this.log('deliver :: call _sendPacket for %o', packet)
let send = true
if (packet.messageId && packet.messageId !== 0) {
if (!this.messageIdProvider.register(packet.messageId)) {
send = false
}
}
if (send) {
this._sendPacket(packet, (err) => {
if (entry.cb) {
entry.cb(err)
}
deliver()
})
} else {
this.log(
'messageId: %d has already used. The message is skipped and removed.',
packet.messageId,
)
deliver()
}
}
this.log('connect :: sending queued packets')
deliver()
})
this.on('close', () => {
this.log('close :: connected set to `false`')
this.connected = false
this.log('close :: clearing connackTimer')
clearTimeout(this.connackTimer)
this.log('close :: destroy ping timer')
if (this.pingTimer) {
this.pingTimer.destroy()
this.pingTimer = null
}
if (this.topicAliasRecv) {
this.topicAliasRecv.clear()
}
this.log('close :: calling _setupReconnect')
this._setupReconnect()
})
if (!this.options.manualConnect) {
this.log('MqttClient :: setting up stream')
this.connect()
}
}
/**
* @param packet the packet received by the broker
* @return the auth packet to be returned to the broker
* @api public
*/
public handleAuth(packet: IAuthPacket, callback: PacketCallback) {
callback()
}
/**
* Handle messages with backpressure support, one at a time.
* Override at will.
*
* @param Packet packet the packet
* @param Function callback call when finished
* @api public
*/
public handleMessage(packet: IPublishPacket, callback: DoneCallback) {
callback()
}
/**
* _nextId
* @return unsigned int
*/
private _nextId() {
return this.messageIdProvider.allocate()
}
/**
* getLastMessageId
* @return unsigned int
*/
public getLastMessageId() {
return this.messageIdProvider.getLastAllocated()
}
/**
* Setup the event handlers in the inner stream, sends `connect` and `auth` packets
*/
public connect() {
const writable = new Writable()
const parser = mqttPacket.parser(this.options)
let completeParse = null
const packets = []
this.log('connect :: calling method to clear reconnect')
this._clearReconnect()
this.log(
'connect :: using streamBuilder provided to client to create stream',
)
this.stream = this.streamBuilder(this)
parser.on('packet', (packet) => {
this.log('parser :: on packet push to packets array.')
packets.push(packet)
})
const work = () => {
this.log('work :: getting next packet in queue')
const packet = packets.shift()
if (packet) {
this.log('work :: packet pulled from queue')
handlePacket(this, packet, nextTickWork)
} else {
this.log('work :: no packets in queue')
const done = completeParse
completeParse = null
this.log('work :: done flag is %s', !!done)
if (done) done()
}
}
const nextTickWork = () => {
if (packets.length) {
nextTick(work)
} else {
const done = completeParse
completeParse = null
done()
}
}
writable._write = (buf, enc, done) => {
completeParse = done
this.log('writable stream :: parsing buffer')
parser.parse(buf)
work()
}
const streamErrorHandler = (error) => {
this.log('streamErrorHandler :: error', error.message)
// error.code will only be set on NodeJS env, browser don't allow to detect errors on sockets
// also emitting errors on browsers seems to create issues
if (error.code) {
// handle error
this.log('streamErrorHandler :: emitting error')
this.emit('error', error)
} else {
this.noop(error)
}
}
this.log('connect :: pipe stream to writable stream')
this.stream.pipe(writable)
// Suppress connection errors
this.stream.on('error', streamErrorHandler)
// Echo stream close
this.stream.on('close', () => {
this.log('(%s)stream :: on close', this.options.clientId)
this._flushVolatile()
this.log('stream: emit close to MqttClient')
this.emit('close')
})
// Send a connect packet
this.log('connect: sending packet `connect`')
const connectPacket: IConnectPacket = {
cmd: 'connect',
protocolId: this.options.protocolId,
protocolVersion: this.options.protocolVersion,
clean: this.options.clean,
clientId: this.options.clientId,
keepalive: this.options.keepalive,
username: this.options.username,
password: this.options.password as Buffer,
properties: this.options.properties,
}
if (this.options.will) {
connectPacket.will = {
...this.options.will,
payload: this.options.will?.payload as Buffer,
}
}
if (this.topicAliasRecv) {
if (!connectPacket.properties) {
connectPacket.properties = {}
}
if (this.topicAliasRecv) {
connectPacket.properties.topicAliasMaximum =
this.topicAliasRecv.max
}
}
// avoid message queue
this._writePacket(connectPacket)
// Echo connection errors
parser.on('error', this.emit.bind(this, 'error'))
// auth
if (this.options.properties) {
if (
!this.options.properties.authenticationMethod &&
this.options.properties.authenticationData
) {
this.end(() =>
this.emit(
'error',
new Error('Packet has no Authentication Method'),
),
)
return this
}
if (
this.options.properties.authenticationMethod &&
this.options.authPacket &&
typeof this.options.authPacket === 'object'
) {
const authPacket: IAuthPacket = {
cmd: 'auth',
reasonCode: 0,
...this.options.authPacket,
}
this._writePacket(authPacket)
}
}
// many drain listeners are needed for qos 1 callbacks if the connection is intermittent
this.stream.setMaxListeners(1000)
clearTimeout(this.connackTimer)
this.connackTimer = setTimeout(() => {
this.log(
'!!connectTimeout hit!! Calling _cleanUp with force `true`',
)
this.emit('error', new Error('connack timeout'))
this._cleanUp(true)
}, this.options.connectTimeout)
return this
}
/**
* publish - publish <message> to <topic>
*
* @param {String} topic - topic to publish to
* @param {String, Buffer} message - message to publish
* @param {Object} [opts] - publish options, includes:
* {Number} qos - qos level to publish on
* {Boolean} retain - whether or not to retain the message
* {Boolean} dup - whether or not mark a message as duplicate
* {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
* @param {Function} [callback] - function(err){}
* called when publish succeeds or fails
* @returns {MqttClient} this - for chaining
* @api public
*
* @example client.publish('topic', 'message');
* @example
* client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
* @example client.publish('topic', 'message', console.log);
*/
public publish(topic: string, message: string | Buffer): MqttClient
public publish(
topic: string,
message: string | Buffer,
callback?: PacketCallback,
): MqttClient
public publish(
topic: string,
message: string | Buffer,
opts?: IClientPublishOptions,
callback?: PacketCallback,
): MqttClient
public publish(
topic: string,
message: string | Buffer,
opts?: IClientPublishOptions | DoneCallback,
callback?: PacketCallback,
): MqttClient {
this.log('publish :: message `%s` to topic `%s`', message, topic)
const { options } = this
// .publish(topic, payload, cb);
if (typeof opts === 'function') {
callback = opts as DoneCallback
opts = null
}
opts = opts || {}
// default opts
const defaultOpts: IClientPublishOptions = {
qos: 0,
retain: false,
dup: false,
}
opts = { ...defaultOpts, ...opts }
const { qos, retain, dup, properties, cbStorePut } = opts
if (this._checkDisconnecting(callback)) {
return this
}
const publishProc = () => {
let messageId = 0
if (qos === 1 || qos === 2) {
messageId = this._nextId()
if (messageId === null) {
this.log('No messageId left')
return false
}
}
const packet: IPublishPacket = {
cmd: 'publish',
topic,
payload: message,
qos,
retain,
messageId,
dup,
}
if (options.protocolVersion === 5) {
packet.properties = properties
}
this.log('publish :: qos', qos)
switch (qos) {
case 1:
case 2:
// Add to callbacks
this.outgoing[packet.messageId] = {
volatile: false,
cb: callback || this.noop,
}
this.log('MqttClient:publish: packet cmd: %s', packet.cmd)
this._sendPacket(packet, undefined, cbStorePut)
break
default:
this.log('MqttClient:publish: packet cmd: %s', packet.cmd)
this._sendPacket(packet, callback, cbStorePut)
break
}
return true
}
if (
this._storeProcessing ||
this._storeProcessingQueue.length > 0 ||
!publishProc()
) {
this._storeProcessingQueue.push({
invoke: publishProc,
cbStorePut: opts.cbStorePut,
callback,
})
}
return this
}