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.
- package/README.md +48 -28
- package/build/package.json +162 -0
- package/build/src/bin/mqtt.d.ts +2 -0
- package/build/src/bin/mqtt.js +27 -0
- package/build/src/bin/mqtt.js.map +1 -0
- package/build/src/bin/pub.d.ts +2 -0
- package/build/src/bin/pub.js +146 -0
- package/build/src/bin/pub.js.map +1 -0
- package/build/src/bin/sub.d.ts +2 -0
- package/build/src/bin/sub.js +121 -0
- package/build/src/bin/sub.js.map +1 -0
- package/build/src/lib/TypedEmitter.d.ts +11 -0
- package/build/src/lib/TypedEmitter.js +13 -0
- package/build/src/lib/TypedEmitter.js.map +1 -0
- package/build/src/lib/client.d.ts +266 -0
- package/build/src/lib/client.js +1147 -0
- package/build/src/lib/client.js.map +1 -0
- package/build/src/lib/connect/ali.d.ts +3 -0
- package/build/src/lib/connect/ali.js +113 -0
- package/build/src/lib/connect/ali.js.map +1 -0
- package/build/src/lib/connect/index.d.ts +5 -0
- package/build/src/lib/connect/index.js +134 -0
- package/build/src/lib/connect/index.js.map +1 -0
- package/build/src/lib/connect/tcp.d.ts +3 -0
- package/build/src/lib/connect/tcp.js +18 -0
- package/build/src/lib/connect/tcp.js.map +1 -0
- package/build/src/lib/connect/tls.d.ts +3 -0
- package/build/src/lib/connect/tls.js +38 -0
- package/build/src/lib/connect/tls.js.map +1 -0
- package/build/src/lib/connect/ws.d.ts +3 -0
- package/build/src/lib/connect/ws.js +212 -0
- package/build/src/lib/connect/ws.js.map +1 -0
- package/build/src/lib/connect/wx.d.ts +3 -0
- package/build/src/lib/connect/wx.js +117 -0
- package/build/src/lib/connect/wx.js.map +1 -0
- package/build/src/lib/default-message-id-provider.d.ts +16 -0
- package/build/src/lib/default-message-id-provider.js +24 -0
- package/build/src/lib/default-message-id-provider.js.map +1 -0
- package/build/src/lib/handlers/ack.d.ts +48 -0
- package/build/src/lib/handlers/ack.js +129 -0
- package/build/src/lib/handlers/ack.js.map +1 -0
- package/build/src/lib/handlers/auth.d.ts +3 -0
- package/build/src/lib/handlers/auth.js +30 -0
- package/build/src/lib/handlers/auth.js.map +1 -0
- package/build/src/lib/handlers/connack.d.ts +3 -0
- package/build/src/lib/handlers/connack.js +48 -0
- package/build/src/lib/handlers/connack.js.map +1 -0
- package/build/src/lib/handlers/index.d.ts +3 -0
- package/build/src/lib/handlers/index.js +64 -0
- package/build/src/lib/handlers/index.js.map +1 -0
- package/build/src/lib/handlers/publish.d.ts +3 -0
- package/build/src/lib/handlers/publish.js +106 -0
- package/build/src/lib/handlers/publish.js.map +1 -0
- package/build/src/lib/handlers/pubrel.d.ts +3 -0
- package/build/src/lib/handlers/pubrel.js +25 -0
- package/build/src/lib/handlers/pubrel.js.map +1 -0
- package/build/src/lib/is-browser.d.ts +2 -0
- package/build/src/lib/is-browser.js +8 -0
- package/build/src/lib/is-browser.js.map +1 -0
- package/build/src/lib/shared.d.ts +17 -0
- package/build/src/lib/shared.js +35 -0
- package/build/src/lib/shared.js.map +1 -0
- package/build/src/lib/store.d.ts +24 -0
- package/build/src/lib/store.js +80 -0
- package/build/src/lib/store.js.map +1 -0
- package/build/src/lib/topic-alias-recv.d.ts +9 -0
- package/build/src/lib/topic-alias-recv.js +24 -0
- package/build/src/lib/topic-alias-recv.js.map +1 -0
- package/build/src/lib/topic-alias-send.d.ts +13 -0
- package/build/src/lib/topic-alias-send.js +56 -0
- package/build/src/lib/topic-alias-send.js.map +1 -0
- package/build/src/lib/unique-message-id-provider.d.ts +10 -0
- package/build/src/lib/unique-message-id-provider.js +26 -0
- package/build/src/lib/unique-message-id-provider.js.map +1 -0
- package/build/src/lib/validations.d.ts +2 -0
- package/build/src/lib/validations.js +32 -0
- package/build/src/lib/validations.js.map +1 -0
- package/build/src/mqtt.d.ts +8 -0
- package/build/src/mqtt.js +33 -0
- package/build/src/mqtt.js.map +1 -0
- package/build/tsconfig.build.tsbuildinfo +1 -0
- package/dist/mqtt.js +4987 -5249
- package/dist/mqtt.min.js +4 -4
- package/package.json +84 -66
- package/src/bin/mqtt.ts +32 -0
- package/src/bin/pub.ts +171 -0
- package/src/bin/sub.ts +146 -0
- package/src/lib/TypedEmitter.ts +45 -0
- package/src/lib/client.ts +2279 -0
- package/src/lib/connect/ali.ts +128 -0
- package/src/lib/connect/index.ts +180 -0
- package/src/lib/connect/tcp.ts +23 -0
- package/src/lib/connect/tls.ts +56 -0
- package/src/lib/connect/ws.ts +282 -0
- package/src/lib/connect/wx.ts +141 -0
- package/src/lib/default-message-id-provider.ts +99 -0
- package/src/lib/handlers/ack.ts +151 -0
- package/src/lib/handlers/auth.ts +44 -0
- package/src/lib/handlers/connack.ts +55 -0
- package/src/lib/handlers/index.ts +67 -0
- package/src/lib/handlers/publish.ts +183 -0
- package/src/lib/handlers/pubrel.ts +27 -0
- package/src/lib/is-browser.ts +12 -0
- package/src/lib/shared.ts +73 -0
- package/src/lib/store.ts +166 -0
- package/src/lib/topic-alias-recv.ts +48 -0
- package/src/lib/topic-alias-send.ts +96 -0
- package/src/lib/unique-message-id-provider.ts +63 -0
- package/src/lib/validations.ts +46 -0
- package/src/mqtt.ts +23 -0
- package/bin/mqtt.js +0 -27
- package/bin/pub.js +0 -146
- package/bin/sub.js +0 -123
- package/lib/client.js +0 -1918
- package/lib/connect/ali.js +0 -129
- package/lib/connect/index.js +0 -169
- package/lib/connect/tcp.js +0 -20
- package/lib/connect/tls.js +0 -48
- package/lib/connect/ws.js +0 -257
- package/lib/connect/wx.js +0 -133
- package/lib/default-message-id-provider.js +0 -69
- package/lib/is-browser.js +0 -11
- package/lib/store.js +0 -128
- package/lib/topic-alias-recv.js +0 -47
- package/lib/topic-alias-send.js +0 -91
- package/lib/unique-message-id-provider.js +0 -65
- package/lib/validations.js +0 -52
- package/mqtt.js +0 -21
- package/types/index.d.ts +0 -30
- package/types/lib/client-options.d.ts +0 -208
- package/types/lib/client.d.ts +0 -261
- package/types/lib/connect/index.d.ts +0 -19
- package/types/lib/default-message-id-provider.d.ts +0 -49
- package/types/lib/message-id-provider.d.ts +0 -40
- package/types/lib/store-options.d.ts +0 -6
- package/types/lib/store.d.ts +0 -46
- package/types/lib/unique-message-id-provider.d.ts +0 -48
|
@@ -0,0 +1,2279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Module dependencies
|
|
3
|
+
*/
|
|
4
|
+
import TopicAliasRecv from './topic-alias-recv'
|
|
5
|
+
import mqttPacket, {
|
|
6
|
+
IAuthPacket,
|
|
7
|
+
IConnackPacket,
|
|
8
|
+
IDisconnectPacket,
|
|
9
|
+
IPublishPacket,
|
|
10
|
+
ISubscribePacket,
|
|
11
|
+
ISubscription,
|
|
12
|
+
IUnsubscribePacket,
|
|
13
|
+
Packet,
|
|
14
|
+
QoS,
|
|
15
|
+
UserProperties,
|
|
16
|
+
ISubackPacket,
|
|
17
|
+
IConnectPacket,
|
|
18
|
+
} from 'mqtt-packet'
|
|
19
|
+
import DefaultMessageIdProvider, {
|
|
20
|
+
IMessageIdProvider,
|
|
21
|
+
} from './default-message-id-provider'
|
|
22
|
+
import { DuplexOptions, Writable } from 'readable-stream'
|
|
23
|
+
import reInterval from 'reinterval'
|
|
24
|
+
import clone from 'rfdc/default'
|
|
25
|
+
import * as validations from './validations'
|
|
26
|
+
import _debug from 'debug'
|
|
27
|
+
import Store from './store'
|
|
28
|
+
import handlePacket from './handlers'
|
|
29
|
+
import { ClientOptions } from 'ws'
|
|
30
|
+
import { ClientRequestArgs } from 'http'
|
|
31
|
+
import {
|
|
32
|
+
DoneCallback,
|
|
33
|
+
ErrorWithReasonCode,
|
|
34
|
+
GenericCallback,
|
|
35
|
+
IStream,
|
|
36
|
+
StreamBuilder,
|
|
37
|
+
VoidCallback,
|
|
38
|
+
} from './shared'
|
|
39
|
+
import TopicAliasSend from './topic-alias-send'
|
|
40
|
+
import { TypedEventEmitter } from './TypedEmitter'
|
|
41
|
+
|
|
42
|
+
const nextTick = process
|
|
43
|
+
? process.nextTick
|
|
44
|
+
: (callback: () => void) => {
|
|
45
|
+
setTimeout(callback, 0)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const setImmediate =
|
|
49
|
+
global.setImmediate ||
|
|
50
|
+
((...args: any[]) => {
|
|
51
|
+
const callback = args.shift()
|
|
52
|
+
nextTick(() => {
|
|
53
|
+
callback(...args)
|
|
54
|
+
})
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
const defaultConnectOptions = {
|
|
58
|
+
keepalive: 60,
|
|
59
|
+
reschedulePings: true,
|
|
60
|
+
protocolId: 'MQTT',
|
|
61
|
+
protocolVersion: 4,
|
|
62
|
+
reconnectPeriod: 1000,
|
|
63
|
+
connectTimeout: 30 * 1000,
|
|
64
|
+
clean: true,
|
|
65
|
+
resubscribe: true,
|
|
66
|
+
writeCache: true,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const socketErrors = [
|
|
70
|
+
'ECONNREFUSED',
|
|
71
|
+
'EADDRINUSE',
|
|
72
|
+
'ECONNRESET',
|
|
73
|
+
'ENOTFOUND',
|
|
74
|
+
'ETIMEDOUT',
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
export type MqttProtocol =
|
|
78
|
+
| 'wss'
|
|
79
|
+
| 'ws'
|
|
80
|
+
| 'mqtt'
|
|
81
|
+
| 'mqtts'
|
|
82
|
+
| 'tcp'
|
|
83
|
+
| 'ssl'
|
|
84
|
+
| 'wx'
|
|
85
|
+
| 'wxs'
|
|
86
|
+
| 'ali'
|
|
87
|
+
| 'alis'
|
|
88
|
+
|
|
89
|
+
export type StorePutCallback = () => void
|
|
90
|
+
|
|
91
|
+
export interface ISecureClientOptions {
|
|
92
|
+
/**
|
|
93
|
+
* optional private keys in PEM format
|
|
94
|
+
*/
|
|
95
|
+
key?: string | string[] | Buffer | Buffer[] | any[]
|
|
96
|
+
keyPath?: string
|
|
97
|
+
/**
|
|
98
|
+
* optional cert chains in PEM format
|
|
99
|
+
*/
|
|
100
|
+
cert?: string | string[] | Buffer | Buffer[]
|
|
101
|
+
certPath?: string
|
|
102
|
+
/**
|
|
103
|
+
* Optionally override the trusted CA certificates in PEM format
|
|
104
|
+
*/
|
|
105
|
+
ca?: string | string[] | Buffer | Buffer[]
|
|
106
|
+
caPaths?: string | string[]
|
|
107
|
+
|
|
108
|
+
rejectUnauthorized?: boolean
|
|
109
|
+
/**
|
|
110
|
+
* optional alpn's
|
|
111
|
+
*/
|
|
112
|
+
ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export type AckHandler = (
|
|
116
|
+
topic: string,
|
|
117
|
+
message: Buffer,
|
|
118
|
+
packet: any,
|
|
119
|
+
cb: (error?: Error, code?: number) => void,
|
|
120
|
+
) => void
|
|
121
|
+
|
|
122
|
+
export interface IClientOptions extends ISecureClientOptions {
|
|
123
|
+
/** Encoding to use. Example 'binary' */
|
|
124
|
+
encoding?: BufferEncoding
|
|
125
|
+
/** Set browser buffer size. Default to 512KB */
|
|
126
|
+
browserBufferSize?: number
|
|
127
|
+
/** used in ws protocol to set `objectMode` */
|
|
128
|
+
binary?: boolean
|
|
129
|
+
/** Used on ali protocol */
|
|
130
|
+
my?: any
|
|
131
|
+
/** Manually call `connect` after creating client instance */
|
|
132
|
+
manualConnect?: any
|
|
133
|
+
/** Custom auth packet properties */
|
|
134
|
+
authPacket?: Partial<IAuthPacket>
|
|
135
|
+
/** Disable/Enable writeToStream.cacheNumbers */
|
|
136
|
+
writeCache?: boolean
|
|
137
|
+
|
|
138
|
+
servername?: string
|
|
139
|
+
defaultProtocol?: MqttProtocol
|
|
140
|
+
/** Support clientId passed in the query string of the url */
|
|
141
|
+
query?: Record<string, string>
|
|
142
|
+
/** Auth string in the format <username>:<password> */
|
|
143
|
+
auth?: string
|
|
144
|
+
/** Custom ack handler */
|
|
145
|
+
customHandleAcks?: AckHandler
|
|
146
|
+
/** Broker port */
|
|
147
|
+
port?: number
|
|
148
|
+
/** Broker host. Does NOT include port */
|
|
149
|
+
host?: string
|
|
150
|
+
/** @deprecated use `host instead */
|
|
151
|
+
hostname?: string
|
|
152
|
+
/** Websocket `path` added as suffix */
|
|
153
|
+
path?: string
|
|
154
|
+
/** The `MqttProtocol` to use */
|
|
155
|
+
protocol?: MqttProtocol
|
|
156
|
+
|
|
157
|
+
/** Websocket options */
|
|
158
|
+
wsOptions?: ClientOptions | ClientRequestArgs | DuplexOptions
|
|
159
|
+
/**
|
|
160
|
+
* 10 seconds, set to 0 to disable
|
|
161
|
+
*/
|
|
162
|
+
keepalive?: number
|
|
163
|
+
/**
|
|
164
|
+
* 'mqttjs_' + Math.random().toString(16).substr(2, 8)
|
|
165
|
+
*/
|
|
166
|
+
clientId?: string
|
|
167
|
+
/**
|
|
168
|
+
* 'MQTT'
|
|
169
|
+
*/
|
|
170
|
+
protocolId?: string
|
|
171
|
+
/**
|
|
172
|
+
* 4
|
|
173
|
+
*/
|
|
174
|
+
protocolVersion?: number
|
|
175
|
+
/**
|
|
176
|
+
* true, set to false to receive QoS 1 and 2 messages while offline
|
|
177
|
+
*/
|
|
178
|
+
clean?: boolean
|
|
179
|
+
/**
|
|
180
|
+
* 1000 milliseconds, interval between two reconnections
|
|
181
|
+
*/
|
|
182
|
+
reconnectPeriod?: number
|
|
183
|
+
/**
|
|
184
|
+
* 30 * 1000 milliseconds, time to wait before a CONNACK is received
|
|
185
|
+
*/
|
|
186
|
+
connectTimeout?: number
|
|
187
|
+
/**
|
|
188
|
+
* the username required by your broker, if any
|
|
189
|
+
*/
|
|
190
|
+
username?: string
|
|
191
|
+
/**
|
|
192
|
+
* the password required by your broker, if any
|
|
193
|
+
*/
|
|
194
|
+
password?: Buffer | string
|
|
195
|
+
/**
|
|
196
|
+
* a Store for the incoming packets
|
|
197
|
+
*/
|
|
198
|
+
incomingStore?: Store
|
|
199
|
+
/**
|
|
200
|
+
* a Store for the outgoing packets
|
|
201
|
+
*/
|
|
202
|
+
outgoingStore?: Store
|
|
203
|
+
|
|
204
|
+
/** Enable/Disable queue for QoS 0 packets */
|
|
205
|
+
queueQoSZero?: boolean
|
|
206
|
+
|
|
207
|
+
/** Custom log function, default uses `debug` */
|
|
208
|
+
log?: (...args: any[]) => void
|
|
209
|
+
|
|
210
|
+
autoUseTopicAlias?: boolean
|
|
211
|
+
autoAssignTopicAlias?: boolean
|
|
212
|
+
|
|
213
|
+
reschedulePings?: boolean
|
|
214
|
+
servers?: Array<{
|
|
215
|
+
host: string
|
|
216
|
+
port: number
|
|
217
|
+
protocol?:
|
|
218
|
+
| 'wss'
|
|
219
|
+
| 'ws'
|
|
220
|
+
| 'mqtt'
|
|
221
|
+
| 'mqtts'
|
|
222
|
+
| 'tcp'
|
|
223
|
+
| 'ssl'
|
|
224
|
+
| 'wx'
|
|
225
|
+
| 'wxs'
|
|
226
|
+
}>
|
|
227
|
+
/**
|
|
228
|
+
* true, set to false to disable re-subscribe functionality
|
|
229
|
+
*/
|
|
230
|
+
resubscribe?: boolean
|
|
231
|
+
/**
|
|
232
|
+
* a message that will sent by the broker automatically when the client disconnect badly.
|
|
233
|
+
*/
|
|
234
|
+
will?: {
|
|
235
|
+
/**
|
|
236
|
+
* the topic to publish
|
|
237
|
+
*/
|
|
238
|
+
topic: string
|
|
239
|
+
/**
|
|
240
|
+
* the message to publish
|
|
241
|
+
*/
|
|
242
|
+
payload: Buffer | string
|
|
243
|
+
/**
|
|
244
|
+
* the QoS
|
|
245
|
+
*/
|
|
246
|
+
qos: QoS
|
|
247
|
+
/**
|
|
248
|
+
* the retain flag
|
|
249
|
+
*/
|
|
250
|
+
retain: boolean
|
|
251
|
+
/*
|
|
252
|
+
* properies object of will
|
|
253
|
+
* */
|
|
254
|
+
properties?: {
|
|
255
|
+
willDelayInterval?: number
|
|
256
|
+
payloadFormatIndicator?: boolean
|
|
257
|
+
messageExpiryInterval?: number
|
|
258
|
+
contentType?: string
|
|
259
|
+
responseTopic?: string
|
|
260
|
+
correlationData?: Buffer
|
|
261
|
+
userProperties?: UserProperties
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
authPacket?: any
|
|
265
|
+
|
|
266
|
+
/** Prevent to call `connect` in constructor */
|
|
267
|
+
manualConnect?: boolean
|
|
268
|
+
}
|
|
269
|
+
transformWsUrl?: (
|
|
270
|
+
url: string,
|
|
271
|
+
options: IClientOptions,
|
|
272
|
+
client: MqttClient,
|
|
273
|
+
) => string
|
|
274
|
+
properties?: {
|
|
275
|
+
sessionExpiryInterval?: number
|
|
276
|
+
receiveMaximum?: number
|
|
277
|
+
maximumPacketSize?: number
|
|
278
|
+
topicAliasMaximum?: number
|
|
279
|
+
requestResponseInformation?: boolean
|
|
280
|
+
requestProblemInformation?: boolean
|
|
281
|
+
userProperties?: UserProperties
|
|
282
|
+
authenticationMethod?: string
|
|
283
|
+
authenticationData?: Buffer
|
|
284
|
+
}
|
|
285
|
+
messageIdProvider?: IMessageIdProvider
|
|
286
|
+
|
|
287
|
+
browserBufferTimeout?: number
|
|
288
|
+
|
|
289
|
+
objectMode?: boolean
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export interface IClientPublishOptions {
|
|
293
|
+
/**
|
|
294
|
+
* the QoS
|
|
295
|
+
*/
|
|
296
|
+
qos?: QoS
|
|
297
|
+
/**
|
|
298
|
+
* the retain flag
|
|
299
|
+
*/
|
|
300
|
+
retain?: boolean
|
|
301
|
+
/**
|
|
302
|
+
* whether or not mark a message as duplicate
|
|
303
|
+
*/
|
|
304
|
+
dup?: boolean
|
|
305
|
+
/*
|
|
306
|
+
* MQTT 5.0 properties object
|
|
307
|
+
*/
|
|
308
|
+
properties?: {
|
|
309
|
+
payloadFormatIndicator?: boolean
|
|
310
|
+
messageExpiryInterval?: number
|
|
311
|
+
topicAlias?: number
|
|
312
|
+
responseTopic?: string
|
|
313
|
+
correlationData?: Buffer
|
|
314
|
+
userProperties?: UserProperties
|
|
315
|
+
subscriptionIdentifier?: number
|
|
316
|
+
contentType?: string
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* callback called when message is put into `outgoingStore`
|
|
320
|
+
*/
|
|
321
|
+
cbStorePut?: StorePutCallback
|
|
322
|
+
}
|
|
323
|
+
export interface IClientSubscribeOptions {
|
|
324
|
+
/**
|
|
325
|
+
* the QoS
|
|
326
|
+
*/
|
|
327
|
+
qos: QoS
|
|
328
|
+
/*
|
|
329
|
+
* no local flag
|
|
330
|
+
* */
|
|
331
|
+
nl?: boolean
|
|
332
|
+
/*
|
|
333
|
+
* Retain As Published flag
|
|
334
|
+
* */
|
|
335
|
+
rap?: boolean
|
|
336
|
+
/*
|
|
337
|
+
* Retain Handling option
|
|
338
|
+
* */
|
|
339
|
+
rh?: number
|
|
340
|
+
/*
|
|
341
|
+
* MQTT 5.0 properies object of subscribe
|
|
342
|
+
* */
|
|
343
|
+
properties?: {
|
|
344
|
+
subscriptionIdentifier?: number
|
|
345
|
+
userProperties?: UserProperties
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
export interface IClientSubscribeProperties {
|
|
349
|
+
/*
|
|
350
|
+
* MQTT 5.0 properies object of subscribe
|
|
351
|
+
* */
|
|
352
|
+
properties?: {
|
|
353
|
+
subscriptionIdentifier?: number
|
|
354
|
+
userProperties?: UserProperties
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
export interface IClientReconnectOptions {
|
|
358
|
+
/**
|
|
359
|
+
* a Store for the incoming packets
|
|
360
|
+
*/
|
|
361
|
+
incomingStore?: Store
|
|
362
|
+
/**
|
|
363
|
+
* a Store for the outgoing packets
|
|
364
|
+
*/
|
|
365
|
+
outgoingStore?: Store
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export interface ISubscriptionGrant {
|
|
369
|
+
/**
|
|
370
|
+
* is a subscribed to topic
|
|
371
|
+
*/
|
|
372
|
+
topic: string
|
|
373
|
+
/**
|
|
374
|
+
* is the granted qos level on it, may return 128 on error
|
|
375
|
+
*/
|
|
376
|
+
qos: QoS | number
|
|
377
|
+
/*
|
|
378
|
+
* no local flag
|
|
379
|
+
* */
|
|
380
|
+
nl?: boolean
|
|
381
|
+
/*
|
|
382
|
+
* Retain As Published flag
|
|
383
|
+
* */
|
|
384
|
+
rap?: boolean
|
|
385
|
+
/*
|
|
386
|
+
* Retain Handling option
|
|
387
|
+
* */
|
|
388
|
+
rh?: number
|
|
389
|
+
}
|
|
390
|
+
export interface ISubscriptionRequest extends IClientSubscribeProperties {
|
|
391
|
+
/**
|
|
392
|
+
* is a subscribed to topic
|
|
393
|
+
*/
|
|
394
|
+
topic: string
|
|
395
|
+
/**
|
|
396
|
+
* is the granted qos level on it
|
|
397
|
+
*/
|
|
398
|
+
qos: QoS
|
|
399
|
+
/*
|
|
400
|
+
* no local flag
|
|
401
|
+
* */
|
|
402
|
+
nl?: boolean
|
|
403
|
+
/*
|
|
404
|
+
* Retain As Published flag
|
|
405
|
+
* */
|
|
406
|
+
rap?: boolean
|
|
407
|
+
/*
|
|
408
|
+
* Retain Handling option
|
|
409
|
+
* */
|
|
410
|
+
rh?: number
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export interface ISubscriptioOptions extends IClientSubscribeProperties {
|
|
414
|
+
qos: QoS
|
|
415
|
+
nl?: boolean
|
|
416
|
+
rap?: boolean
|
|
417
|
+
rh?: number
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
export type ISubscriptionMap = {
|
|
421
|
+
/**
|
|
422
|
+
* object which has topic names as object keys and as value the options, like {'test1': {qos: 0}, 'test2': {qos: 2}}.
|
|
423
|
+
*/
|
|
424
|
+
[topic: string]: ISubscriptioOptions
|
|
425
|
+
} & {
|
|
426
|
+
resubscribe?: boolean
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export type OnConnectCallback = (packet: IConnackPacket) => void
|
|
430
|
+
export type OnDisconnectCallback = (packet: IDisconnectPacket) => void
|
|
431
|
+
export type ClientSubscribeCallback = (
|
|
432
|
+
err: Error | null,
|
|
433
|
+
granted: ISubscriptionGrant[],
|
|
434
|
+
) => void
|
|
435
|
+
export type OnMessageCallback = (
|
|
436
|
+
topic: string,
|
|
437
|
+
payload: Buffer,
|
|
438
|
+
packet: IPublishPacket,
|
|
439
|
+
) => void
|
|
440
|
+
export type OnPacketCallback = (packet: Packet) => void
|
|
441
|
+
export type OnCloseCallback = () => void
|
|
442
|
+
export type OnErrorCallback = (error: Error | ErrorWithReasonCode) => void
|
|
443
|
+
export type PacketCallback = (error?: Error, packet?: Packet) => any
|
|
444
|
+
export type CloseCallback = (error?: Error) => void
|
|
445
|
+
|
|
446
|
+
export interface MqttClientEventCallbacks {
|
|
447
|
+
connect: OnConnectCallback
|
|
448
|
+
message: OnMessageCallback
|
|
449
|
+
packetsend: OnPacketCallback
|
|
450
|
+
packetreceive: OnPacketCallback
|
|
451
|
+
disconnect: OnDisconnectCallback
|
|
452
|
+
error: OnErrorCallback
|
|
453
|
+
close: OnCloseCallback
|
|
454
|
+
end: VoidCallback
|
|
455
|
+
reconnect: VoidCallback
|
|
456
|
+
offline: VoidCallback
|
|
457
|
+
outgoingEmpty: VoidCallback
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* MqttClient constructor
|
|
462
|
+
*
|
|
463
|
+
* @param {Stream} stream - stream
|
|
464
|
+
* @param {Object} [options] - connection options
|
|
465
|
+
* (see Connection#connect)
|
|
466
|
+
*/
|
|
467
|
+
export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbacks> {
|
|
468
|
+
/** Public fields */
|
|
469
|
+
|
|
470
|
+
/** It's true when client is connected to broker */
|
|
471
|
+
public connected: boolean
|
|
472
|
+
|
|
473
|
+
public disconnecting: boolean
|
|
474
|
+
|
|
475
|
+
public disconnected: boolean
|
|
476
|
+
|
|
477
|
+
public reconnecting: boolean
|
|
478
|
+
|
|
479
|
+
public incomingStore: Store
|
|
480
|
+
|
|
481
|
+
public outgoingStore: Store
|
|
482
|
+
|
|
483
|
+
public options: IClientOptions
|
|
484
|
+
|
|
485
|
+
public queueQoSZero: boolean
|
|
486
|
+
|
|
487
|
+
public _reconnectCount: number
|
|
488
|
+
|
|
489
|
+
public log: (...args: any[]) => void
|
|
490
|
+
|
|
491
|
+
public messageIdProvider: IMessageIdProvider
|
|
492
|
+
|
|
493
|
+
public pingResp: boolean
|
|
494
|
+
|
|
495
|
+
public outgoing: Record<
|
|
496
|
+
number,
|
|
497
|
+
{ volatile: boolean; cb: (err: Error, packet?: Packet) => void }
|
|
498
|
+
>
|
|
499
|
+
|
|
500
|
+
public messageIdToTopic: Record<number, string[]>
|
|
501
|
+
|
|
502
|
+
public noop: (error?: any) => void
|
|
503
|
+
|
|
504
|
+
public pingTimer: any
|
|
505
|
+
|
|
506
|
+
public stream: IStream
|
|
507
|
+
|
|
508
|
+
public queue: { packet: Packet; cb: PacketCallback }[]
|
|
509
|
+
|
|
510
|
+
/* Private fields */
|
|
511
|
+
|
|
512
|
+
/** Function used to build the stream */
|
|
513
|
+
private streamBuilder: StreamBuilder
|
|
514
|
+
|
|
515
|
+
private _resubscribeTopics: ISubscriptionMap
|
|
516
|
+
|
|
517
|
+
private connackTimer: NodeJS.Timeout
|
|
518
|
+
|
|
519
|
+
private reconnectTimer: NodeJS.Timeout
|
|
520
|
+
|
|
521
|
+
private _storeProcessing: boolean
|
|
522
|
+
|
|
523
|
+
/** keep a reference of packets that have been successfully processed from outgoing store */
|
|
524
|
+
private _packetIdsDuringStoreProcessing: Record<number, boolean>
|
|
525
|
+
|
|
526
|
+
private _storeProcessingQueue: {
|
|
527
|
+
invoke: () => any
|
|
528
|
+
cbStorePut?: DoneCallback
|
|
529
|
+
callback: GenericCallback<any>
|
|
530
|
+
}[]
|
|
531
|
+
|
|
532
|
+
private _firstConnection: boolean
|
|
533
|
+
|
|
534
|
+
private topicAliasRecv: TopicAliasRecv
|
|
535
|
+
|
|
536
|
+
private topicAliasSend: TopicAliasSend
|
|
537
|
+
|
|
538
|
+
private _deferredReconnect: () => void
|
|
539
|
+
|
|
540
|
+
private connackPacket: IConnackPacket
|
|
541
|
+
|
|
542
|
+
public static defaultId() {
|
|
543
|
+
return `mqttjs_${Math.random().toString(16).substr(2, 8)}`
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
constructor(streamBuilder: StreamBuilder, options: IClientOptions) {
|
|
547
|
+
super()
|
|
548
|
+
|
|
549
|
+
this.options = options || {}
|
|
550
|
+
|
|
551
|
+
// Defaults
|
|
552
|
+
for (const k in defaultConnectOptions) {
|
|
553
|
+
if (typeof this.options[k] === 'undefined') {
|
|
554
|
+
this.options[k] = defaultConnectOptions[k]
|
|
555
|
+
} else {
|
|
556
|
+
this.options[k] = options[k]
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
this.log = this.options.log || _debug('mqttjs:client')
|
|
561
|
+
this.noop = this._noop.bind(this)
|
|
562
|
+
|
|
563
|
+
this.log('MqttClient :: options.protocol', options.protocol)
|
|
564
|
+
this.log(
|
|
565
|
+
'MqttClient :: options.protocolVersion',
|
|
566
|
+
options.protocolVersion,
|
|
567
|
+
)
|
|
568
|
+
this.log('MqttClient :: options.username', options.username)
|
|
569
|
+
this.log('MqttClient :: options.keepalive', options.keepalive)
|
|
570
|
+
this.log(
|
|
571
|
+
'MqttClient :: options.reconnectPeriod',
|
|
572
|
+
options.reconnectPeriod,
|
|
573
|
+
)
|
|
574
|
+
this.log(
|
|
575
|
+
'MqttClient :: options.rejectUnauthorized',
|
|
576
|
+
options.rejectUnauthorized,
|
|
577
|
+
)
|
|
578
|
+
this.log(
|
|
579
|
+
'MqttClient :: options.properties.topicAliasMaximum',
|
|
580
|
+
options.properties
|
|
581
|
+
? options.properties.topicAliasMaximum
|
|
582
|
+
: undefined,
|
|
583
|
+
)
|
|
584
|
+
|
|
585
|
+
this.options.clientId =
|
|
586
|
+
typeof options.clientId === 'string'
|
|
587
|
+
? options.clientId
|
|
588
|
+
: MqttClient.defaultId()
|
|
589
|
+
|
|
590
|
+
this.log('MqttClient :: clientId', this.options.clientId)
|
|
591
|
+
|
|
592
|
+
this.options.customHandleAcks =
|
|
593
|
+
options.protocolVersion === 5 && options.customHandleAcks
|
|
594
|
+
? options.customHandleAcks
|
|
595
|
+
: (...args) => {
|
|
596
|
+
args[3](null, 0)
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// Disable pre-generated write cache if requested. Will allocate buffers on-the-fly instead. WARNING: This can affect write performance
|
|
600
|
+
if (!this.options.writeCache) {
|
|
601
|
+
mqttPacket.writeToStream.cacheNumbers = false
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
this.streamBuilder = streamBuilder
|
|
605
|
+
|
|
606
|
+
this.messageIdProvider =
|
|
607
|
+
typeof this.options.messageIdProvider === 'undefined'
|
|
608
|
+
? new DefaultMessageIdProvider()
|
|
609
|
+
: this.options.messageIdProvider
|
|
610
|
+
|
|
611
|
+
// Inflight message storages
|
|
612
|
+
this.outgoingStore = options.outgoingStore || new Store()
|
|
613
|
+
this.incomingStore = options.incomingStore || new Store()
|
|
614
|
+
|
|
615
|
+
// Should QoS zero messages be queued when the connection is broken?
|
|
616
|
+
this.queueQoSZero =
|
|
617
|
+
options.queueQoSZero === undefined ? true : options.queueQoSZero
|
|
618
|
+
|
|
619
|
+
// map of subscribed topics to support reconnection
|
|
620
|
+
this._resubscribeTopics = {}
|
|
621
|
+
|
|
622
|
+
// map of a subscribe messageId and a topic
|
|
623
|
+
this.messageIdToTopic = {}
|
|
624
|
+
|
|
625
|
+
// Ping timer, setup in _setupPingTimer
|
|
626
|
+
this.pingTimer = null
|
|
627
|
+
// Is the client connected?
|
|
628
|
+
this.connected = false
|
|
629
|
+
// Are we disconnecting?
|
|
630
|
+
this.disconnecting = false
|
|
631
|
+
// Packet queue
|
|
632
|
+
this.queue = []
|
|
633
|
+
// connack timer
|
|
634
|
+
this.connackTimer = null
|
|
635
|
+
// Reconnect timer
|
|
636
|
+
this.reconnectTimer = null
|
|
637
|
+
// Is processing store?
|
|
638
|
+
this._storeProcessing = false
|
|
639
|
+
// Packet Ids are put into the store during store processing
|
|
640
|
+
this._packetIdsDuringStoreProcessing = {}
|
|
641
|
+
// Store processing queue
|
|
642
|
+
this._storeProcessingQueue = []
|
|
643
|
+
|
|
644
|
+
// Inflight callbacks
|
|
645
|
+
this.outgoing = {}
|
|
646
|
+
|
|
647
|
+
// True if connection is first time.
|
|
648
|
+
this._firstConnection = true
|
|
649
|
+
|
|
650
|
+
if (options.properties && options.properties.topicAliasMaximum > 0) {
|
|
651
|
+
if (options.properties.topicAliasMaximum > 0xffff) {
|
|
652
|
+
this.log(
|
|
653
|
+
'MqttClient :: options.properties.topicAliasMaximum is out of range',
|
|
654
|
+
)
|
|
655
|
+
} else {
|
|
656
|
+
this.topicAliasRecv = new TopicAliasRecv(
|
|
657
|
+
options.properties.topicAliasMaximum,
|
|
658
|
+
)
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// Send queued packets
|
|
663
|
+
this.on('connect', () => {
|
|
664
|
+
const { queue } = this
|
|
665
|
+
|
|
666
|
+
const deliver = () => {
|
|
667
|
+
const entry = queue.shift()
|
|
668
|
+
this.log('deliver :: entry %o', entry)
|
|
669
|
+
let packet = null
|
|
670
|
+
|
|
671
|
+
if (!entry) {
|
|
672
|
+
this._resubscribe()
|
|
673
|
+
return
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
packet = entry.packet
|
|
677
|
+
this.log('deliver :: call _sendPacket for %o', packet)
|
|
678
|
+
let send = true
|
|
679
|
+
if (packet.messageId && packet.messageId !== 0) {
|
|
680
|
+
if (!this.messageIdProvider.register(packet.messageId)) {
|
|
681
|
+
send = false
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
if (send) {
|
|
685
|
+
this._sendPacket(packet, (err) => {
|
|
686
|
+
if (entry.cb) {
|
|
687
|
+
entry.cb(err)
|
|
688
|
+
}
|
|
689
|
+
deliver()
|
|
690
|
+
})
|
|
691
|
+
} else {
|
|
692
|
+
this.log(
|
|
693
|
+
'messageId: %d has already used. The message is skipped and removed.',
|
|
694
|
+
packet.messageId,
|
|
695
|
+
)
|
|
696
|
+
deliver()
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
this.log('connect :: sending queued packets')
|
|
701
|
+
deliver()
|
|
702
|
+
})
|
|
703
|
+
|
|
704
|
+
this.on('close', () => {
|
|
705
|
+
this.log('close :: connected set to `false`')
|
|
706
|
+
this.connected = false
|
|
707
|
+
|
|
708
|
+
this.log('close :: clearing connackTimer')
|
|
709
|
+
clearTimeout(this.connackTimer)
|
|
710
|
+
|
|
711
|
+
this.log('close :: clearing ping timer')
|
|
712
|
+
if (this.pingTimer !== null) {
|
|
713
|
+
this.pingTimer.clear()
|
|
714
|
+
this.pingTimer = null
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
if (this.topicAliasRecv) {
|
|
718
|
+
this.topicAliasRecv.clear()
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
this.log('close :: calling _setupReconnect')
|
|
722
|
+
this._setupReconnect()
|
|
723
|
+
})
|
|
724
|
+
|
|
725
|
+
if (!this.options.manualConnect) {
|
|
726
|
+
this.log('MqttClient :: setting up stream')
|
|
727
|
+
this.connect()
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* @param packet the packet received by the broker
|
|
733
|
+
* @return the auth packet to be returned to the broker
|
|
734
|
+
* @api public
|
|
735
|
+
*/
|
|
736
|
+
public handleAuth(packet: IAuthPacket, callback: PacketCallback) {
|
|
737
|
+
callback()
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/**
|
|
741
|
+
* Handle messages with backpressure support, one at a time.
|
|
742
|
+
* Override at will.
|
|
743
|
+
*
|
|
744
|
+
* @param Packet packet the packet
|
|
745
|
+
* @param Function callback call when finished
|
|
746
|
+
* @api public
|
|
747
|
+
*/
|
|
748
|
+
public handleMessage(packet: IPublishPacket, callback: DoneCallback) {
|
|
749
|
+
callback()
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* _nextId
|
|
754
|
+
* @return unsigned int
|
|
755
|
+
*/
|
|
756
|
+
private _nextId() {
|
|
757
|
+
return this.messageIdProvider.allocate()
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* getLastMessageId
|
|
762
|
+
* @return unsigned int
|
|
763
|
+
*/
|
|
764
|
+
public getLastMessageId() {
|
|
765
|
+
return this.messageIdProvider.getLastAllocated()
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* Setup the event handlers in the inner stream, sends `connect` and `auth` packets
|
|
770
|
+
*/
|
|
771
|
+
public connect() {
|
|
772
|
+
const writable = new Writable()
|
|
773
|
+
const parser = mqttPacket.parser(this.options)
|
|
774
|
+
let completeParse = null
|
|
775
|
+
const packets = []
|
|
776
|
+
|
|
777
|
+
this.log('connect :: calling method to clear reconnect')
|
|
778
|
+
this._clearReconnect()
|
|
779
|
+
|
|
780
|
+
this.log(
|
|
781
|
+
'connect :: using streamBuilder provided to client to create stream',
|
|
782
|
+
)
|
|
783
|
+
this.stream = this.streamBuilder(this)
|
|
784
|
+
|
|
785
|
+
parser.on('packet', (packet) => {
|
|
786
|
+
this.log('parser :: on packet push to packets array.')
|
|
787
|
+
packets.push(packet)
|
|
788
|
+
})
|
|
789
|
+
|
|
790
|
+
const work = () => {
|
|
791
|
+
this.log('work :: getting next packet in queue')
|
|
792
|
+
const packet = packets.shift()
|
|
793
|
+
|
|
794
|
+
if (packet) {
|
|
795
|
+
this.log('work :: packet pulled from queue')
|
|
796
|
+
handlePacket(this, packet, nextTickWork)
|
|
797
|
+
} else {
|
|
798
|
+
this.log('work :: no packets in queue')
|
|
799
|
+
const done = completeParse
|
|
800
|
+
completeParse = null
|
|
801
|
+
this.log('work :: done flag is %s', !!done)
|
|
802
|
+
if (done) done()
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
const nextTickWork = () => {
|
|
807
|
+
if (packets.length) {
|
|
808
|
+
nextTick(work)
|
|
809
|
+
} else {
|
|
810
|
+
const done = completeParse
|
|
811
|
+
completeParse = null
|
|
812
|
+
done()
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
writable._write = (buf, enc, done) => {
|
|
817
|
+
completeParse = done
|
|
818
|
+
this.log('writable stream :: parsing buffer')
|
|
819
|
+
parser.parse(buf)
|
|
820
|
+
work()
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
const streamErrorHandler = (error) => {
|
|
824
|
+
this.log('streamErrorHandler :: error', error.message)
|
|
825
|
+
if (socketErrors.includes(error.code)) {
|
|
826
|
+
// handle error
|
|
827
|
+
this.log('streamErrorHandler :: emitting error')
|
|
828
|
+
this.emit('error', error)
|
|
829
|
+
} else {
|
|
830
|
+
this.noop(error)
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
this.log('connect :: pipe stream to writable stream')
|
|
835
|
+
this.stream.pipe(writable)
|
|
836
|
+
|
|
837
|
+
// Suppress connection errors
|
|
838
|
+
this.stream.on('error', streamErrorHandler)
|
|
839
|
+
|
|
840
|
+
// Echo stream close
|
|
841
|
+
this.stream.on('close', () => {
|
|
842
|
+
this.log('(%s)stream :: on close', this.options.clientId)
|
|
843
|
+
this._flushVolatile()
|
|
844
|
+
this.log('stream: emit close to MqttClient')
|
|
845
|
+
this.emit('close')
|
|
846
|
+
})
|
|
847
|
+
|
|
848
|
+
// Send a connect packet
|
|
849
|
+
this.log('connect: sending packet `connect`')
|
|
850
|
+
const connectPacket: IConnectPacket = Object.create(this.options)
|
|
851
|
+
connectPacket.cmd = 'connect'
|
|
852
|
+
if (this.topicAliasRecv) {
|
|
853
|
+
if (!connectPacket.properties) {
|
|
854
|
+
connectPacket.properties = {}
|
|
855
|
+
}
|
|
856
|
+
if (this.topicAliasRecv) {
|
|
857
|
+
connectPacket.properties.topicAliasMaximum =
|
|
858
|
+
this.topicAliasRecv.max
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
// avoid message queue
|
|
862
|
+
this._writePacket(connectPacket)
|
|
863
|
+
|
|
864
|
+
// Echo connection errors
|
|
865
|
+
parser.on('error', this.emit.bind(this, 'error'))
|
|
866
|
+
|
|
867
|
+
// auth
|
|
868
|
+
if (this.options.properties) {
|
|
869
|
+
if (
|
|
870
|
+
!this.options.properties.authenticationMethod &&
|
|
871
|
+
this.options.properties.authenticationData
|
|
872
|
+
) {
|
|
873
|
+
this.end(() =>
|
|
874
|
+
this.emit(
|
|
875
|
+
'error',
|
|
876
|
+
new Error('Packet has no Authentication Method'),
|
|
877
|
+
),
|
|
878
|
+
)
|
|
879
|
+
return this
|
|
880
|
+
}
|
|
881
|
+
if (
|
|
882
|
+
this.options.properties.authenticationMethod &&
|
|
883
|
+
this.options.authPacket &&
|
|
884
|
+
typeof this.options.authPacket === 'object'
|
|
885
|
+
) {
|
|
886
|
+
const authPacket: IAuthPacket = {
|
|
887
|
+
cmd: 'auth',
|
|
888
|
+
reasonCode: 0,
|
|
889
|
+
...this.options.authPacket,
|
|
890
|
+
}
|
|
891
|
+
this._writePacket(authPacket)
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// many drain listeners are needed for qos 1 callbacks if the connection is intermittent
|
|
896
|
+
this.stream.setMaxListeners(1000)
|
|
897
|
+
|
|
898
|
+
clearTimeout(this.connackTimer)
|
|
899
|
+
this.connackTimer = setTimeout(() => {
|
|
900
|
+
this.log(
|
|
901
|
+
'!!connectTimeout hit!! Calling _cleanUp with force `true`',
|
|
902
|
+
)
|
|
903
|
+
this._cleanUp(true)
|
|
904
|
+
}, this.options.connectTimeout)
|
|
905
|
+
|
|
906
|
+
return this
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* publish - publish <message> to <topic>
|
|
911
|
+
*
|
|
912
|
+
* @param {String} topic - topic to publish to
|
|
913
|
+
* @param {String, Buffer} message - message to publish
|
|
914
|
+
* @param {Object} [opts] - publish options, includes:
|
|
915
|
+
* {Number} qos - qos level to publish on
|
|
916
|
+
* {Boolean} retain - whether or not to retain the message
|
|
917
|
+
* {Boolean} dup - whether or not mark a message as duplicate
|
|
918
|
+
* {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
|
|
919
|
+
* @param {Function} [callback] - function(err){}
|
|
920
|
+
* called when publish succeeds or fails
|
|
921
|
+
* @returns {MqttClient} this - for chaining
|
|
922
|
+
* @api public
|
|
923
|
+
*
|
|
924
|
+
* @example client.publish('topic', 'message');
|
|
925
|
+
* @example
|
|
926
|
+
* client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
|
|
927
|
+
* @example client.publish('topic', 'message', console.log);
|
|
928
|
+
*/
|
|
929
|
+
public publish(topic: string, message: string | Buffer): MqttClient
|
|
930
|
+
public publish(
|
|
931
|
+
topic: string,
|
|
932
|
+
message: string | Buffer,
|
|
933
|
+
callback?: DoneCallback,
|
|
934
|
+
): MqttClient
|
|
935
|
+
public publish(
|
|
936
|
+
topic: string,
|
|
937
|
+
message: string | Buffer,
|
|
938
|
+
opts?: IClientPublishOptions,
|
|
939
|
+
callback?: DoneCallback,
|
|
940
|
+
): MqttClient
|
|
941
|
+
public publish(
|
|
942
|
+
topic: string,
|
|
943
|
+
message: string | Buffer,
|
|
944
|
+
opts?: IClientPublishOptions | DoneCallback,
|
|
945
|
+
callback?: DoneCallback,
|
|
946
|
+
): MqttClient {
|
|
947
|
+
this.log('publish :: message `%s` to topic `%s`', message, topic)
|
|
948
|
+
const { options } = this
|
|
949
|
+
|
|
950
|
+
// .publish(topic, payload, cb);
|
|
951
|
+
if (typeof opts === 'function') {
|
|
952
|
+
callback = opts as DoneCallback
|
|
953
|
+
opts = {} as IClientPublishOptions
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
// default opts
|
|
957
|
+
const defaultOpts: IClientPublishOptions = {
|
|
958
|
+
qos: 0,
|
|
959
|
+
retain: false,
|
|
960
|
+
dup: false,
|
|
961
|
+
}
|
|
962
|
+
opts = { ...defaultOpts, ...opts }
|
|
963
|
+
|
|
964
|
+
const { qos, retain, dup, properties, cbStorePut } = opts
|
|
965
|
+
|
|
966
|
+
if (this._checkDisconnecting(callback)) {
|
|
967
|
+
return this
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
const publishProc = () => {
|
|
971
|
+
let messageId = 0
|
|
972
|
+
if (qos === 1 || qos === 2) {
|
|
973
|
+
messageId = this._nextId()
|
|
974
|
+
if (messageId === null) {
|
|
975
|
+
this.log('No messageId left')
|
|
976
|
+
return false
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
const packet: IPublishPacket = {
|
|
980
|
+
cmd: 'publish',
|
|
981
|
+
topic,
|
|
982
|
+
payload: message,
|
|
983
|
+
qos,
|
|
984
|
+
retain,
|
|
985
|
+
messageId,
|
|
986
|
+
dup,
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
if (options.protocolVersion === 5) {
|
|
990
|
+
packet.properties = properties
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
this.log('publish :: qos', qos)
|
|
994
|
+
switch (qos) {
|
|
995
|
+
case 1:
|
|
996
|
+
case 2:
|
|
997
|
+
// Add to callbacks
|
|
998
|
+
this.outgoing[packet.messageId] = {
|
|
999
|
+
volatile: false,
|
|
1000
|
+
cb: callback || this.noop,
|
|
1001
|
+
}
|
|
1002
|
+
this.log('MqttClient:publish: packet cmd: %s', packet.cmd)
|
|
1003
|
+
this._sendPacket(packet, undefined, cbStorePut)
|
|
1004
|
+
break
|
|
1005
|
+
default:
|
|
1006
|
+
this.log('MqttClient:publish: packet cmd: %s', packet.cmd)
|
|
1007
|
+
this._sendPacket(packet, callback, cbStorePut)
|
|
1008
|
+
break
|
|
1009
|
+
}
|
|
1010
|
+
return true
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
if (
|
|
1014
|
+
this._storeProcessing ||
|
|
1015
|
+
this._storeProcessingQueue.length > 0 ||
|
|
1016
|
+
!publishProc()
|
|
1017
|
+
) {
|
|
1018
|
+
this._storeProcessingQueue.push({
|
|
1019
|
+
invoke: publishProc,
|
|
1020
|
+
cbStorePut: opts.cbStorePut,
|
|
1021
|
+
callback,
|
|
1022
|
+
})
|
|
1023
|
+
}
|
|
1024
|
+
return this
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
/**
|
|
1028
|
+
* subscribe - subscribe to <topic>
|
|
1029
|
+
*
|
|
1030
|
+
* @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
|
|
1031
|
+
* @param {Object} [opts] - optional subscription options, includes:
|
|
1032
|
+
* {Number} qos - subscribe qos level
|
|
1033
|
+
* @param {Function} [callback] - function(err, granted){} where:
|
|
1034
|
+
* {Error} err - subscription error (none at the moment!)
|
|
1035
|
+
* {Array} granted - array of {topic: 't', qos: 0}
|
|
1036
|
+
* @returns {MqttClient} this - for chaining
|
|
1037
|
+
* @api public
|
|
1038
|
+
* @example client.subscribe('topic');
|
|
1039
|
+
* @example client.subscribe('topic', {qos: 1});
|
|
1040
|
+
* @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
|
|
1041
|
+
* @example client.subscribe('topic', console.log);
|
|
1042
|
+
*/
|
|
1043
|
+
public subscribe(
|
|
1044
|
+
topicObject: string | string[] | ISubscriptionMap,
|
|
1045
|
+
): MqttClient
|
|
1046
|
+
public subscribe(
|
|
1047
|
+
topicObject: string | string[] | ISubscriptionMap,
|
|
1048
|
+
callback?: ClientSubscribeCallback,
|
|
1049
|
+
): MqttClient
|
|
1050
|
+
public subscribe(
|
|
1051
|
+
topicObject: string | string[] | ISubscriptionMap,
|
|
1052
|
+
opts?: IClientSubscribeOptions | IClientSubscribeProperties,
|
|
1053
|
+
): MqttClient
|
|
1054
|
+
public subscribe(
|
|
1055
|
+
topicObject: string | string[] | ISubscriptionMap,
|
|
1056
|
+
opts?: IClientSubscribeOptions | IClientSubscribeProperties,
|
|
1057
|
+
callback?: ClientSubscribeCallback,
|
|
1058
|
+
): MqttClient
|
|
1059
|
+
public subscribe(
|
|
1060
|
+
topicObject: string | string[] | ISubscriptionMap,
|
|
1061
|
+
opts?:
|
|
1062
|
+
| IClientSubscribeOptions
|
|
1063
|
+
| IClientSubscribeProperties
|
|
1064
|
+
| ClientSubscribeCallback,
|
|
1065
|
+
callback?: ClientSubscribeCallback,
|
|
1066
|
+
): MqttClient {
|
|
1067
|
+
const version = this.options.protocolVersion
|
|
1068
|
+
|
|
1069
|
+
if (typeof opts === 'function') {
|
|
1070
|
+
callback = opts
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
callback = callback || this.noop
|
|
1074
|
+
|
|
1075
|
+
// force re-subscribe on reconnect. This is only true
|
|
1076
|
+
// when provided `topicObject` is `this._resubscribeTopics`
|
|
1077
|
+
let resubscribe = false
|
|
1078
|
+
let topicsList = []
|
|
1079
|
+
|
|
1080
|
+
if (typeof topicObject === 'string') {
|
|
1081
|
+
topicObject = [topicObject]
|
|
1082
|
+
topicsList = topicObject
|
|
1083
|
+
} else if (Array.isArray(topicObject)) {
|
|
1084
|
+
topicsList = topicObject
|
|
1085
|
+
} else if (typeof topicObject === 'object') {
|
|
1086
|
+
resubscribe = topicObject.resubscribe
|
|
1087
|
+
delete topicObject.resubscribe
|
|
1088
|
+
topicsList = Object.keys(topicObject)
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// validate topics
|
|
1092
|
+
const invalidTopic = validations.validateTopics(topicsList)
|
|
1093
|
+
if (invalidTopic !== null) {
|
|
1094
|
+
setImmediate(callback, new Error(`Invalid topic ${invalidTopic}`))
|
|
1095
|
+
return this
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
if (this._checkDisconnecting(callback)) {
|
|
1099
|
+
this.log('subscribe: discconecting true')
|
|
1100
|
+
return this
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
const defaultOpts: Partial<IClientSubscribeOptions> = {
|
|
1104
|
+
qos: 0,
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
if (version === 5) {
|
|
1108
|
+
defaultOpts.nl = false
|
|
1109
|
+
defaultOpts.rap = false
|
|
1110
|
+
defaultOpts.rh = 0
|
|
1111
|
+
}
|
|
1112
|
+
opts = { ...defaultOpts, ...opts } as IClientSubscribeOptions
|
|
1113
|
+
|
|
1114
|
+
const properties = opts.properties
|
|
1115
|
+
|
|
1116
|
+
const subs: ISubscriptionRequest[] = []
|
|
1117
|
+
|
|
1118
|
+
const parseSub = (
|
|
1119
|
+
topic: string,
|
|
1120
|
+
subOptions?: IClientSubscribeOptions,
|
|
1121
|
+
) => {
|
|
1122
|
+
// subOptions is defined only when providing a subs map, use opts otherwise
|
|
1123
|
+
subOptions = (subOptions || opts) as IClientSubscribeOptions
|
|
1124
|
+
if (
|
|
1125
|
+
!Object.prototype.hasOwnProperty.call(
|
|
1126
|
+
this._resubscribeTopics,
|
|
1127
|
+
topic,
|
|
1128
|
+
) ||
|
|
1129
|
+
this._resubscribeTopics[topic].qos < subOptions.qos ||
|
|
1130
|
+
resubscribe
|
|
1131
|
+
) {
|
|
1132
|
+
const currentOpts: ISubscription & IClientSubscribeProperties =
|
|
1133
|
+
{
|
|
1134
|
+
topic,
|
|
1135
|
+
qos: subOptions.qos,
|
|
1136
|
+
}
|
|
1137
|
+
if (version === 5) {
|
|
1138
|
+
currentOpts.nl = subOptions.nl
|
|
1139
|
+
currentOpts.rap = subOptions.rap
|
|
1140
|
+
currentOpts.rh = subOptions.rh
|
|
1141
|
+
// use opts.properties
|
|
1142
|
+
currentOpts.properties = properties
|
|
1143
|
+
}
|
|
1144
|
+
this.log(
|
|
1145
|
+
'subscribe: pushing topic `%s` and qos `%s` to subs list',
|
|
1146
|
+
currentOpts.topic,
|
|
1147
|
+
currentOpts.qos,
|
|
1148
|
+
)
|
|
1149
|
+
subs.push(currentOpts)
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
if (Array.isArray(topicObject)) {
|
|
1154
|
+
// array of topics
|
|
1155
|
+
topicObject.forEach((topic) => {
|
|
1156
|
+
this.log('subscribe: array topic %s', topic)
|
|
1157
|
+
parseSub(topic)
|
|
1158
|
+
})
|
|
1159
|
+
} else {
|
|
1160
|
+
// object topic --> subOptions (no properties)
|
|
1161
|
+
Object.keys(topicObject).forEach((topic) => {
|
|
1162
|
+
this.log(
|
|
1163
|
+
'subscribe: object topic %s, %o',
|
|
1164
|
+
topic,
|
|
1165
|
+
topicObject[topic],
|
|
1166
|
+
)
|
|
1167
|
+
parseSub(topic, topicObject[topic])
|
|
1168
|
+
})
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
if (!subs.length) {
|
|
1172
|
+
callback(null, [])
|
|
1173
|
+
return this
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
const subscribeProc = () => {
|
|
1177
|
+
const messageId = this._nextId()
|
|
1178
|
+
if (messageId === null) {
|
|
1179
|
+
this.log('No messageId left')
|
|
1180
|
+
return false
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
const packet: ISubscribePacket = {
|
|
1184
|
+
cmd: 'subscribe',
|
|
1185
|
+
subscriptions: subs,
|
|
1186
|
+
// qos: 1,
|
|
1187
|
+
// retain: false,
|
|
1188
|
+
// dup: false,
|
|
1189
|
+
messageId,
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
if (properties) {
|
|
1193
|
+
packet.properties = properties
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
// subscriptions to resubscribe to in case of disconnect
|
|
1197
|
+
if (this.options.resubscribe) {
|
|
1198
|
+
this.log('subscribe :: resubscribe true')
|
|
1199
|
+
const topics = []
|
|
1200
|
+
subs.forEach((sub) => {
|
|
1201
|
+
if (this.options.reconnectPeriod > 0) {
|
|
1202
|
+
const topic: ISubscriptioOptions = { qos: sub.qos }
|
|
1203
|
+
if (version === 5) {
|
|
1204
|
+
topic.nl = sub.nl || false
|
|
1205
|
+
topic.rap = sub.rap || false
|
|
1206
|
+
topic.rh = sub.rh || 0
|
|
1207
|
+
topic.properties = sub.properties
|
|
1208
|
+
}
|
|
1209
|
+
this._resubscribeTopics[sub.topic] = topic
|
|
1210
|
+
topics.push(sub.topic)
|
|
1211
|
+
}
|
|
1212
|
+
})
|
|
1213
|
+
this.messageIdToTopic[packet.messageId] = topics
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
this.outgoing[packet.messageId] = {
|
|
1217
|
+
volatile: true,
|
|
1218
|
+
cb(err, packet2: ISubackPacket) {
|
|
1219
|
+
if (!err) {
|
|
1220
|
+
const { granted } = packet2
|
|
1221
|
+
for (let i = 0; i < granted.length; i += 1) {
|
|
1222
|
+
subs[i].qos = granted[i] as QoS
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
callback(err, subs)
|
|
1227
|
+
},
|
|
1228
|
+
}
|
|
1229
|
+
this.log('subscribe :: call _sendPacket')
|
|
1230
|
+
this._sendPacket(packet)
|
|
1231
|
+
return true
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
if (
|
|
1235
|
+
this._storeProcessing ||
|
|
1236
|
+
this._storeProcessingQueue.length > 0 ||
|
|
1237
|
+
!subscribeProc()
|
|
1238
|
+
) {
|
|
1239
|
+
this._storeProcessingQueue.push({
|
|
1240
|
+
invoke: subscribeProc,
|
|
1241
|
+
callback,
|
|
1242
|
+
})
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
return this
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
/**
|
|
1249
|
+
* unsubscribe - unsubscribe from topic(s)
|
|
1250
|
+
*
|
|
1251
|
+
* @param {String, Array} topic - topics to unsubscribe from
|
|
1252
|
+
* @param {Object} [opts] - optional subscription options, includes:
|
|
1253
|
+
* {Object} properties - properties of unsubscribe packet
|
|
1254
|
+
* @param {Function} [callback] - callback fired on unsuback
|
|
1255
|
+
* @returns {MqttClient} this - for chaining
|
|
1256
|
+
* @api public
|
|
1257
|
+
* @example client.unsubscribe('topic');
|
|
1258
|
+
* @example client.unsubscribe('topic', console.log);
|
|
1259
|
+
*/
|
|
1260
|
+
public unsubscribe(topic: string | string[]): MqttClient
|
|
1261
|
+
public unsubscribe(
|
|
1262
|
+
topic: string | string[],
|
|
1263
|
+
opts?: IClientSubscribeOptions,
|
|
1264
|
+
): MqttClient
|
|
1265
|
+
public unsubscribe(
|
|
1266
|
+
topic: string | string[],
|
|
1267
|
+
callback?: PacketCallback,
|
|
1268
|
+
): MqttClient
|
|
1269
|
+
public unsubscribe(
|
|
1270
|
+
topic: string | string[],
|
|
1271
|
+
opts?: IClientSubscribeOptions,
|
|
1272
|
+
callback?: PacketCallback,
|
|
1273
|
+
): MqttClient
|
|
1274
|
+
public unsubscribe(
|
|
1275
|
+
topic: string | string[],
|
|
1276
|
+
opts?: IClientSubscribeOptions | PacketCallback,
|
|
1277
|
+
callback?: PacketCallback,
|
|
1278
|
+
): MqttClient {
|
|
1279
|
+
if (typeof topic === 'string') {
|
|
1280
|
+
topic = [topic]
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
if (typeof opts === 'function') {
|
|
1284
|
+
callback = opts
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
callback = callback || this.noop
|
|
1288
|
+
|
|
1289
|
+
const invalidTopic = validations.validateTopics(topic)
|
|
1290
|
+
if (invalidTopic !== null) {
|
|
1291
|
+
setImmediate(callback, new Error(`Invalid topic ${invalidTopic}`))
|
|
1292
|
+
return this
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
if (this._checkDisconnecting(callback)) {
|
|
1296
|
+
return this
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
const unsubscribeProc = () => {
|
|
1300
|
+
const messageId = this._nextId()
|
|
1301
|
+
if (messageId === null) {
|
|
1302
|
+
this.log('No messageId left')
|
|
1303
|
+
return false
|
|
1304
|
+
}
|
|
1305
|
+
const packet: IUnsubscribePacket = {
|
|
1306
|
+
cmd: 'unsubscribe',
|
|
1307
|
+
// qos: 1,
|
|
1308
|
+
messageId,
|
|
1309
|
+
unsubscriptions: [],
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
if (typeof topic === 'string') {
|
|
1313
|
+
packet.unsubscriptions = [topic]
|
|
1314
|
+
} else if (Array.isArray(topic)) {
|
|
1315
|
+
packet.unsubscriptions = topic
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
if (this.options.resubscribe) {
|
|
1319
|
+
packet.unsubscriptions.forEach((topic2) => {
|
|
1320
|
+
delete this._resubscribeTopics[topic2]
|
|
1321
|
+
})
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
if (typeof opts === 'object' && opts.properties) {
|
|
1325
|
+
packet.properties = opts.properties
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
this.outgoing[packet.messageId] = {
|
|
1329
|
+
volatile: true,
|
|
1330
|
+
cb: callback,
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
this.log('unsubscribe: call _sendPacket')
|
|
1334
|
+
this._sendPacket(packet)
|
|
1335
|
+
|
|
1336
|
+
return true
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
if (
|
|
1340
|
+
this._storeProcessing ||
|
|
1341
|
+
this._storeProcessingQueue.length > 0 ||
|
|
1342
|
+
!unsubscribeProc()
|
|
1343
|
+
) {
|
|
1344
|
+
this._storeProcessingQueue.push({
|
|
1345
|
+
invoke: unsubscribeProc,
|
|
1346
|
+
callback,
|
|
1347
|
+
})
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
return this
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
/**
|
|
1354
|
+
* end - close connection
|
|
1355
|
+
*
|
|
1356
|
+
* @returns {MqttClient} this - for chaining
|
|
1357
|
+
* @param {Boolean} force - do not wait for all in-flight messages to be acked
|
|
1358
|
+
* @param {Object} opts - added to the disconnect packet
|
|
1359
|
+
* @param {Function} cb - called when the client has been closed
|
|
1360
|
+
*
|
|
1361
|
+
* @api public
|
|
1362
|
+
*/
|
|
1363
|
+
public end(cb?: DoneCallback): MqttClient
|
|
1364
|
+
public end(force?: boolean): MqttClient
|
|
1365
|
+
public end(opts?: Partial<IDisconnectPacket>, cb?: DoneCallback): MqttClient
|
|
1366
|
+
public end(force?: boolean, cb?: DoneCallback): MqttClient
|
|
1367
|
+
public end(
|
|
1368
|
+
force?: boolean,
|
|
1369
|
+
opts?: Partial<IDisconnectPacket>,
|
|
1370
|
+
cb?: DoneCallback,
|
|
1371
|
+
): MqttClient
|
|
1372
|
+
public end(
|
|
1373
|
+
force?: boolean | Partial<IDisconnectPacket> | DoneCallback,
|
|
1374
|
+
opts?: Partial<IDisconnectPacket> | DoneCallback,
|
|
1375
|
+
cb?: DoneCallback,
|
|
1376
|
+
): MqttClient {
|
|
1377
|
+
this.log('end :: (%s)', this.options.clientId)
|
|
1378
|
+
|
|
1379
|
+
if (force == null || typeof force !== 'boolean') {
|
|
1380
|
+
cb = (opts || this.noop) as DoneCallback
|
|
1381
|
+
opts = force as Partial<IDisconnectPacket>
|
|
1382
|
+
force = false
|
|
1383
|
+
if (typeof opts !== 'object') {
|
|
1384
|
+
cb = opts
|
|
1385
|
+
opts = null
|
|
1386
|
+
if (typeof cb !== 'function') {
|
|
1387
|
+
cb = this.noop
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
if (typeof opts !== 'object') {
|
|
1393
|
+
cb = opts
|
|
1394
|
+
opts = null
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
this.log('end :: cb? %s', !!cb)
|
|
1398
|
+
cb = cb || this.noop
|
|
1399
|
+
|
|
1400
|
+
const closeStores = () => {
|
|
1401
|
+
this.log('end :: closeStores: closing incoming and outgoing stores')
|
|
1402
|
+
this.disconnected = true
|
|
1403
|
+
this.incomingStore.close((e1) => {
|
|
1404
|
+
this.outgoingStore.close((e2) => {
|
|
1405
|
+
this.log('end :: closeStores: emitting end')
|
|
1406
|
+
this.emit('end')
|
|
1407
|
+
if (cb) {
|
|
1408
|
+
const err = e1 || e2
|
|
1409
|
+
this.log(
|
|
1410
|
+
'end :: closeStores: invoking callback with args',
|
|
1411
|
+
)
|
|
1412
|
+
cb(err)
|
|
1413
|
+
}
|
|
1414
|
+
})
|
|
1415
|
+
})
|
|
1416
|
+
if (this._deferredReconnect) {
|
|
1417
|
+
this._deferredReconnect()
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
const finish = () => {
|
|
1422
|
+
// defer closesStores of an I/O cycle,
|
|
1423
|
+
// just to make sure things are
|
|
1424
|
+
// ok for websockets
|
|
1425
|
+
this.log(
|
|
1426
|
+
'end :: (%s) :: finish :: calling _cleanUp with force %s',
|
|
1427
|
+
this.options.clientId,
|
|
1428
|
+
force,
|
|
1429
|
+
)
|
|
1430
|
+
this._cleanUp(
|
|
1431
|
+
<boolean>force,
|
|
1432
|
+
() => {
|
|
1433
|
+
this.log(
|
|
1434
|
+
'end :: finish :: calling process.nextTick on closeStores',
|
|
1435
|
+
)
|
|
1436
|
+
// const boundProcess = nextTick.bind(null, closeStores)
|
|
1437
|
+
nextTick(closeStores)
|
|
1438
|
+
},
|
|
1439
|
+
opts,
|
|
1440
|
+
)
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
if (this.disconnecting) {
|
|
1444
|
+
cb()
|
|
1445
|
+
return this
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
this._clearReconnect()
|
|
1449
|
+
|
|
1450
|
+
this.disconnecting = true
|
|
1451
|
+
|
|
1452
|
+
if (!force && Object.keys(this.outgoing).length > 0) {
|
|
1453
|
+
// wait 10ms, just to be sure we received all of it
|
|
1454
|
+
this.log(
|
|
1455
|
+
'end :: (%s) :: calling finish in 10ms once outgoing is empty',
|
|
1456
|
+
this.options.clientId,
|
|
1457
|
+
)
|
|
1458
|
+
this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
|
|
1459
|
+
} else {
|
|
1460
|
+
this.log(
|
|
1461
|
+
'end :: (%s) :: immediately calling finish',
|
|
1462
|
+
this.options.clientId,
|
|
1463
|
+
)
|
|
1464
|
+
finish()
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
return this
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
/**
|
|
1471
|
+
* removeOutgoingMessage - remove a message in outgoing store
|
|
1472
|
+
* the outgoing callback will be called withe Error('Message removed') if the message is removed
|
|
1473
|
+
*
|
|
1474
|
+
* @param {Number} messageId - messageId to remove message
|
|
1475
|
+
* @returns {MqttClient} this - for chaining
|
|
1476
|
+
* @api public
|
|
1477
|
+
*
|
|
1478
|
+
* @example client.removeOutgoingMessage(client.getLastAllocated());
|
|
1479
|
+
*/
|
|
1480
|
+
public removeOutgoingMessage(messageId: number): MqttClient {
|
|
1481
|
+
if (this.outgoing[messageId]) {
|
|
1482
|
+
const { cb } = this.outgoing[messageId]
|
|
1483
|
+
this._removeOutgoingAndStoreMessage(messageId, () => {
|
|
1484
|
+
cb(new Error('Message removed'))
|
|
1485
|
+
})
|
|
1486
|
+
}
|
|
1487
|
+
return this
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
/**
|
|
1491
|
+
* reconnect - connect again using the same options as connect()
|
|
1492
|
+
*
|
|
1493
|
+
* @param {Object} [opts] - optional reconnect options, includes:
|
|
1494
|
+
* {Store} incomingStore - a store for the incoming packets
|
|
1495
|
+
* {Store} outgoingStore - a store for the outgoing packets
|
|
1496
|
+
* if opts is not given, current stores are used
|
|
1497
|
+
* @returns {MqttClient} this - for chaining
|
|
1498
|
+
*
|
|
1499
|
+
* @api public
|
|
1500
|
+
*/
|
|
1501
|
+
public reconnect(
|
|
1502
|
+
opts?: Pick<IClientOptions, 'incomingStore' | 'outgoingStore'>,
|
|
1503
|
+
): MqttClient {
|
|
1504
|
+
this.log('client reconnect')
|
|
1505
|
+
const f = () => {
|
|
1506
|
+
if (opts) {
|
|
1507
|
+
this.options.incomingStore = opts.incomingStore
|
|
1508
|
+
this.options.outgoingStore = opts.outgoingStore
|
|
1509
|
+
} else {
|
|
1510
|
+
this.options.incomingStore = null
|
|
1511
|
+
this.options.outgoingStore = null
|
|
1512
|
+
}
|
|
1513
|
+
this.incomingStore = this.options.incomingStore || new Store()
|
|
1514
|
+
this.outgoingStore = this.options.outgoingStore || new Store()
|
|
1515
|
+
this.disconnecting = false
|
|
1516
|
+
this.disconnected = false
|
|
1517
|
+
this._deferredReconnect = null
|
|
1518
|
+
this._reconnect()
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
if (this.disconnecting && !this.disconnected) {
|
|
1522
|
+
this._deferredReconnect = f
|
|
1523
|
+
} else {
|
|
1524
|
+
f()
|
|
1525
|
+
}
|
|
1526
|
+
return this
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
/**
|
|
1530
|
+
* PRIVATE METHODS
|
|
1531
|
+
* =====================
|
|
1532
|
+
* */
|
|
1533
|
+
|
|
1534
|
+
/**
|
|
1535
|
+
* Flush all outgoing messages marked as `volatile` in `outgoing` queue. Volatile messages
|
|
1536
|
+
* typically are subscription and unsubscription requests.
|
|
1537
|
+
*/
|
|
1538
|
+
private _flushVolatile() {
|
|
1539
|
+
if (this.outgoing) {
|
|
1540
|
+
this.log(
|
|
1541
|
+
'_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function',
|
|
1542
|
+
)
|
|
1543
|
+
Object.keys(this.outgoing).forEach((messageId) => {
|
|
1544
|
+
if (
|
|
1545
|
+
this.outgoing[messageId].volatile &&
|
|
1546
|
+
typeof this.outgoing[messageId].cb === 'function'
|
|
1547
|
+
) {
|
|
1548
|
+
this.outgoing[messageId].cb(new Error('Connection closed'))
|
|
1549
|
+
delete this.outgoing[messageId]
|
|
1550
|
+
}
|
|
1551
|
+
})
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
/**
|
|
1556
|
+
* Flush all outgoing messages
|
|
1557
|
+
*/
|
|
1558
|
+
private _flush() {
|
|
1559
|
+
if (this.outgoing) {
|
|
1560
|
+
this.log('_flush: queue exists? %b', !!this.outgoing)
|
|
1561
|
+
Object.keys(this.outgoing).forEach((messageId) => {
|
|
1562
|
+
if (typeof this.outgoing[messageId].cb === 'function') {
|
|
1563
|
+
this.outgoing[messageId].cb(new Error('Connection closed'))
|
|
1564
|
+
// This is suspicious. Why do we only delete this if we have a callback?
|
|
1565
|
+
// If this is by-design, then adding no as callback would cause this to get deleted unintentionally.
|
|
1566
|
+
delete this.outgoing[messageId]
|
|
1567
|
+
}
|
|
1568
|
+
})
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
private _removeTopicAliasAndRecoverTopicName(packet: IPublishPacket) {
|
|
1573
|
+
let alias: number | undefined
|
|
1574
|
+
|
|
1575
|
+
if (packet.properties) {
|
|
1576
|
+
alias = packet.properties.topicAlias
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
let topic = packet.topic.toString()
|
|
1580
|
+
|
|
1581
|
+
this.log(
|
|
1582
|
+
'_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o',
|
|
1583
|
+
alias,
|
|
1584
|
+
topic,
|
|
1585
|
+
)
|
|
1586
|
+
|
|
1587
|
+
if (topic.length === 0) {
|
|
1588
|
+
// restore topic from alias
|
|
1589
|
+
if (typeof alias === 'undefined') {
|
|
1590
|
+
return new Error('Unregistered Topic Alias')
|
|
1591
|
+
}
|
|
1592
|
+
topic = this.topicAliasSend.getTopicByAlias(alias)
|
|
1593
|
+
if (typeof topic === 'undefined') {
|
|
1594
|
+
return new Error('Unregistered Topic Alias')
|
|
1595
|
+
}
|
|
1596
|
+
packet.topic = topic
|
|
1597
|
+
}
|
|
1598
|
+
if (alias) {
|
|
1599
|
+
delete packet.properties.topicAlias
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
private _checkDisconnecting(callback: GenericCallback<any>) {
|
|
1604
|
+
if (this.disconnecting) {
|
|
1605
|
+
if (callback && callback !== this.noop) {
|
|
1606
|
+
callback(new Error('client disconnecting'))
|
|
1607
|
+
} else {
|
|
1608
|
+
this.emit('error', new Error('client disconnecting'))
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
return this.disconnecting
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
/**
|
|
1615
|
+
* _reconnect - implement reconnection
|
|
1616
|
+
* @api private
|
|
1617
|
+
*/
|
|
1618
|
+
private _reconnect() {
|
|
1619
|
+
this.log('_reconnect: emitting reconnect to client')
|
|
1620
|
+
this.emit('reconnect')
|
|
1621
|
+
if (this.connected) {
|
|
1622
|
+
this.end(() => {
|
|
1623
|
+
this.connect()
|
|
1624
|
+
})
|
|
1625
|
+
this.log('client already connected. disconnecting first.')
|
|
1626
|
+
} else {
|
|
1627
|
+
this.log('_reconnect: calling connect')
|
|
1628
|
+
this.connect()
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
|
|
1632
|
+
/**
|
|
1633
|
+
* _setupReconnect - setup reconnect timer
|
|
1634
|
+
*/
|
|
1635
|
+
private _setupReconnect() {
|
|
1636
|
+
if (
|
|
1637
|
+
!this.disconnecting &&
|
|
1638
|
+
!this.reconnectTimer &&
|
|
1639
|
+
this.options.reconnectPeriod > 0
|
|
1640
|
+
) {
|
|
1641
|
+
if (!this.reconnecting) {
|
|
1642
|
+
this.log('_setupReconnect :: emit `offline` state')
|
|
1643
|
+
this.emit('offline')
|
|
1644
|
+
this.log('_setupReconnect :: set `reconnecting` to `true`')
|
|
1645
|
+
this.reconnecting = true
|
|
1646
|
+
}
|
|
1647
|
+
this.log(
|
|
1648
|
+
'_setupReconnect :: setting reconnectTimer for %d ms',
|
|
1649
|
+
this.options.reconnectPeriod,
|
|
1650
|
+
)
|
|
1651
|
+
this.reconnectTimer = setInterval(() => {
|
|
1652
|
+
this.log('reconnectTimer :: reconnect triggered!')
|
|
1653
|
+
this._reconnect()
|
|
1654
|
+
}, this.options.reconnectPeriod)
|
|
1655
|
+
} else {
|
|
1656
|
+
this.log('_setupReconnect :: doing nothing...')
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
/**
|
|
1661
|
+
* _clearReconnect - clear the reconnect timer
|
|
1662
|
+
*/
|
|
1663
|
+
private _clearReconnect() {
|
|
1664
|
+
this.log('_clearReconnect : clearing reconnect timer')
|
|
1665
|
+
if (this.reconnectTimer) {
|
|
1666
|
+
clearInterval(this.reconnectTimer)
|
|
1667
|
+
this.reconnectTimer = null
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
/**
|
|
1672
|
+
* _cleanUp - clean up on connection end
|
|
1673
|
+
* @api private
|
|
1674
|
+
*/
|
|
1675
|
+
private _cleanUp(forced: boolean, done?: DoneCallback, opts = {}) {
|
|
1676
|
+
if (done) {
|
|
1677
|
+
this.log('_cleanUp :: done callback provided for on stream close')
|
|
1678
|
+
this.stream.on('close', done)
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
this.log('_cleanUp :: forced? %s', forced)
|
|
1682
|
+
if (forced) {
|
|
1683
|
+
if (this.options.reconnectPeriod === 0 && this.options.clean) {
|
|
1684
|
+
this._flush()
|
|
1685
|
+
}
|
|
1686
|
+
this.log(
|
|
1687
|
+
'_cleanUp :: (%s) :: destroying stream',
|
|
1688
|
+
this.options.clientId,
|
|
1689
|
+
)
|
|
1690
|
+
this.stream.destroy()
|
|
1691
|
+
} else {
|
|
1692
|
+
const packet: IDisconnectPacket = { cmd: 'disconnect', ...opts }
|
|
1693
|
+
this.log(
|
|
1694
|
+
'_cleanUp :: (%s) :: call _sendPacket with disconnect packet',
|
|
1695
|
+
this.options.clientId,
|
|
1696
|
+
)
|
|
1697
|
+
this._sendPacket(packet, () => {
|
|
1698
|
+
this.log(
|
|
1699
|
+
'_cleanUp :: (%s) :: destroying stream',
|
|
1700
|
+
this.options.clientId,
|
|
1701
|
+
)
|
|
1702
|
+
setImmediate(() => {
|
|
1703
|
+
this.stream.end(() => {
|
|
1704
|
+
this.log(
|
|
1705
|
+
'_cleanUp :: (%s) :: stream destroyed',
|
|
1706
|
+
this.options.clientId,
|
|
1707
|
+
)
|
|
1708
|
+
// once stream is closed the 'close' event will fire and that will
|
|
1709
|
+
// emit client `close` event and call `done` callback if done is provided
|
|
1710
|
+
})
|
|
1711
|
+
})
|
|
1712
|
+
})
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
if (!this.disconnecting) {
|
|
1716
|
+
this.log(
|
|
1717
|
+
'_cleanUp :: client not disconnecting. Clearing and resetting reconnect.',
|
|
1718
|
+
)
|
|
1719
|
+
this._clearReconnect()
|
|
1720
|
+
this._setupReconnect()
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1723
|
+
if (this.pingTimer !== null) {
|
|
1724
|
+
this.log('_cleanUp :: clearing pingTimer')
|
|
1725
|
+
this.pingTimer.clear()
|
|
1726
|
+
this.pingTimer = null
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
if (done && !this.connected) {
|
|
1730
|
+
this.log(
|
|
1731
|
+
'_cleanUp :: (%s) :: removing stream `done` callback `close` listener',
|
|
1732
|
+
this.options.clientId,
|
|
1733
|
+
)
|
|
1734
|
+
this.stream.removeListener('close', done)
|
|
1735
|
+
done()
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
private _storeAndSend(
|
|
1740
|
+
packet: Packet,
|
|
1741
|
+
cb: DoneCallback,
|
|
1742
|
+
cbStorePut: DoneCallback,
|
|
1743
|
+
) {
|
|
1744
|
+
this.log(
|
|
1745
|
+
'storeAndSend :: store packet with cmd %s to outgoingStore',
|
|
1746
|
+
packet.cmd,
|
|
1747
|
+
)
|
|
1748
|
+
let storePacket = packet
|
|
1749
|
+
let err: Error | undefined
|
|
1750
|
+
if (storePacket.cmd === 'publish') {
|
|
1751
|
+
// The original packet is for sending.
|
|
1752
|
+
// The cloned storePacket is for storing to resend on reconnect.
|
|
1753
|
+
// Topic Alias must not be used after disconnected.
|
|
1754
|
+
storePacket = clone(packet)
|
|
1755
|
+
err = this._removeTopicAliasAndRecoverTopicName(
|
|
1756
|
+
storePacket as IPublishPacket,
|
|
1757
|
+
)
|
|
1758
|
+
if (err) {
|
|
1759
|
+
return cb && cb(err)
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
this.outgoingStore.put(storePacket, (err2) => {
|
|
1763
|
+
if (err2) {
|
|
1764
|
+
return cb && cb(err2)
|
|
1765
|
+
}
|
|
1766
|
+
cbStorePut()
|
|
1767
|
+
this._writePacket(packet, cb)
|
|
1768
|
+
})
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
private _applyTopicAlias(packet: Packet) {
|
|
1772
|
+
if (this.options.protocolVersion === 5) {
|
|
1773
|
+
if (packet.cmd === 'publish') {
|
|
1774
|
+
let alias: number
|
|
1775
|
+
if (packet.properties) {
|
|
1776
|
+
alias = packet.properties.topicAlias
|
|
1777
|
+
}
|
|
1778
|
+
const topic = packet.topic.toString()
|
|
1779
|
+
if (this.topicAliasSend) {
|
|
1780
|
+
if (alias) {
|
|
1781
|
+
if (topic.length !== 0) {
|
|
1782
|
+
// register topic alias
|
|
1783
|
+
this.log(
|
|
1784
|
+
'applyTopicAlias :: register topic: %s - alias: %d',
|
|
1785
|
+
topic,
|
|
1786
|
+
alias,
|
|
1787
|
+
)
|
|
1788
|
+
if (!this.topicAliasSend.put(topic, alias)) {
|
|
1789
|
+
this.log(
|
|
1790
|
+
'applyTopicAlias :: error out of range. topic: %s - alias: %d',
|
|
1791
|
+
topic,
|
|
1792
|
+
alias,
|
|
1793
|
+
)
|
|
1794
|
+
return new Error(
|
|
1795
|
+
'Sending Topic Alias out of range',
|
|
1796
|
+
)
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
} else if (topic.length !== 0) {
|
|
1800
|
+
if (this.options.autoAssignTopicAlias) {
|
|
1801
|
+
alias = this.topicAliasSend.getAliasByTopic(topic)
|
|
1802
|
+
if (alias) {
|
|
1803
|
+
packet.topic = ''
|
|
1804
|
+
packet.properties = {
|
|
1805
|
+
...packet.properties,
|
|
1806
|
+
topicAlias: alias,
|
|
1807
|
+
}
|
|
1808
|
+
this.log(
|
|
1809
|
+
'applyTopicAlias :: auto assign(use) topic: %s - alias: %d',
|
|
1810
|
+
topic,
|
|
1811
|
+
alias,
|
|
1812
|
+
)
|
|
1813
|
+
} else {
|
|
1814
|
+
alias = this.topicAliasSend.getLruAlias()
|
|
1815
|
+
this.topicAliasSend.put(topic, alias)
|
|
1816
|
+
packet.properties = {
|
|
1817
|
+
...packet.properties,
|
|
1818
|
+
topicAlias: alias,
|
|
1819
|
+
}
|
|
1820
|
+
this.log(
|
|
1821
|
+
'applyTopicAlias :: auto assign topic: %s - alias: %d',
|
|
1822
|
+
topic,
|
|
1823
|
+
alias,
|
|
1824
|
+
)
|
|
1825
|
+
}
|
|
1826
|
+
} else if (this.options.autoUseTopicAlias) {
|
|
1827
|
+
alias = this.topicAliasSend.getAliasByTopic(topic)
|
|
1828
|
+
if (alias) {
|
|
1829
|
+
packet.topic = ''
|
|
1830
|
+
packet.properties = {
|
|
1831
|
+
...packet.properties,
|
|
1832
|
+
topicAlias: alias,
|
|
1833
|
+
}
|
|
1834
|
+
this.log(
|
|
1835
|
+
'applyTopicAlias :: auto use topic: %s - alias: %d',
|
|
1836
|
+
topic,
|
|
1837
|
+
alias,
|
|
1838
|
+
)
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
} else if (alias) {
|
|
1843
|
+
this.log(
|
|
1844
|
+
'applyTopicAlias :: error out of range. topic: %s - alias: %d',
|
|
1845
|
+
topic,
|
|
1846
|
+
alias,
|
|
1847
|
+
)
|
|
1848
|
+
return new Error('Sending Topic Alias out of range')
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
private _noop(err?: Error) {
|
|
1855
|
+
this.log('noop ::', err)
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
/** Writes the packet to stream and emits events */
|
|
1859
|
+
private _writePacket(packet: Packet, cb?: DoneCallback) {
|
|
1860
|
+
this.log('_writePacket :: packet: %O', packet)
|
|
1861
|
+
this.log('_writePacket :: emitting `packetsend`')
|
|
1862
|
+
|
|
1863
|
+
this.emit('packetsend', packet)
|
|
1864
|
+
|
|
1865
|
+
// When writing a packet, reschedule the ping timer
|
|
1866
|
+
this._shiftPingInterval()
|
|
1867
|
+
|
|
1868
|
+
this.log('_writePacket :: writing to stream')
|
|
1869
|
+
const result = mqttPacket.writeToStream(
|
|
1870
|
+
packet,
|
|
1871
|
+
this.stream,
|
|
1872
|
+
this.options,
|
|
1873
|
+
)
|
|
1874
|
+
this.log('_writePacket :: writeToStream result %s', result)
|
|
1875
|
+
if (!result && cb && cb !== this.noop) {
|
|
1876
|
+
this.log(
|
|
1877
|
+
'_writePacket :: handle events on `drain` once through callback.',
|
|
1878
|
+
)
|
|
1879
|
+
this.stream.once('drain', cb)
|
|
1880
|
+
} else if (cb) {
|
|
1881
|
+
this.log('_writePacket :: invoking cb')
|
|
1882
|
+
cb()
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
/**
|
|
1887
|
+
* _sendPacket - send or queue a packet
|
|
1888
|
+
* @param {Object} packet - packet options
|
|
1889
|
+
* @param {Function} cb - callback when the packet is sent
|
|
1890
|
+
* @param {Function} cbStorePut - called when message is put into outgoingStore
|
|
1891
|
+
* @param {Boolean} noStore - send without put to the store
|
|
1892
|
+
* @api private
|
|
1893
|
+
*/
|
|
1894
|
+
private _sendPacket(
|
|
1895
|
+
packet: Packet,
|
|
1896
|
+
cb?: DoneCallback,
|
|
1897
|
+
cbStorePut?: DoneCallback,
|
|
1898
|
+
noStore?: boolean,
|
|
1899
|
+
) {
|
|
1900
|
+
this.log('_sendPacket :: (%s) :: start', this.options.clientId)
|
|
1901
|
+
cbStorePut = cbStorePut || this.noop
|
|
1902
|
+
cb = cb || this.noop
|
|
1903
|
+
|
|
1904
|
+
const err = this._applyTopicAlias(packet)
|
|
1905
|
+
if (err) {
|
|
1906
|
+
cb(err)
|
|
1907
|
+
return
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
if (!this.connected) {
|
|
1911
|
+
// allow auth packets to be sent while authenticating with the broker (mqtt5 enhanced auth)
|
|
1912
|
+
if (packet.cmd === 'auth') {
|
|
1913
|
+
this._writePacket(packet, cb)
|
|
1914
|
+
return
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
this.log(
|
|
1918
|
+
'_sendPacket :: client not connected. Storing packet offline.',
|
|
1919
|
+
)
|
|
1920
|
+
this._storePacket(packet, cb, cbStorePut)
|
|
1921
|
+
return
|
|
1922
|
+
}
|
|
1923
|
+
|
|
1924
|
+
// If "noStore" is true, the message is sent without being recorded in the store.
|
|
1925
|
+
// Messages that have not received puback or pubcomp remain in the store after disconnection
|
|
1926
|
+
// and are resent from the store upon reconnection.
|
|
1927
|
+
// For resend upon reconnection, "noStore" is set to true. This is because the message is already stored in the store.
|
|
1928
|
+
// This is to avoid interrupting other processes while recording to the store.
|
|
1929
|
+
if (noStore) {
|
|
1930
|
+
this._writePacket(packet, cb)
|
|
1931
|
+
return
|
|
1932
|
+
}
|
|
1933
|
+
|
|
1934
|
+
switch (packet.cmd) {
|
|
1935
|
+
case 'publish':
|
|
1936
|
+
break
|
|
1937
|
+
case 'pubrel':
|
|
1938
|
+
this._storeAndSend(packet, cb, cbStorePut)
|
|
1939
|
+
return
|
|
1940
|
+
default:
|
|
1941
|
+
this._writePacket(packet, cb)
|
|
1942
|
+
return
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
switch (packet.qos) {
|
|
1946
|
+
case 2:
|
|
1947
|
+
case 1:
|
|
1948
|
+
this._storeAndSend(packet, cb, cbStorePut)
|
|
1949
|
+
break
|
|
1950
|
+
/**
|
|
1951
|
+
* no need of case here since it will be caught by default
|
|
1952
|
+
* and jshint comply that before default it must be a break
|
|
1953
|
+
* anyway it will result in -1 evaluation
|
|
1954
|
+
*/
|
|
1955
|
+
case 0:
|
|
1956
|
+
/* falls through */
|
|
1957
|
+
default:
|
|
1958
|
+
this._writePacket(packet, cb)
|
|
1959
|
+
break
|
|
1960
|
+
}
|
|
1961
|
+
this.log('_sendPacket :: (%s) :: end', this.options.clientId)
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
/**
|
|
1965
|
+
* _storePacket - queue a packet
|
|
1966
|
+
* @param {Object} packet - packet options
|
|
1967
|
+
* @param {Function} cb - callback when the packet is sent
|
|
1968
|
+
* @param {Function} cbStorePut - called when message is put into outgoingStore
|
|
1969
|
+
* @api private
|
|
1970
|
+
*/
|
|
1971
|
+
private _storePacket(
|
|
1972
|
+
packet: Packet,
|
|
1973
|
+
cb: DoneCallback,
|
|
1974
|
+
cbStorePut: DoneCallback,
|
|
1975
|
+
) {
|
|
1976
|
+
this.log('_storePacket :: packet: %o', packet)
|
|
1977
|
+
this.log('_storePacket :: cb? %s', !!cb)
|
|
1978
|
+
cbStorePut = cbStorePut || this.noop
|
|
1979
|
+
|
|
1980
|
+
let storePacket = packet
|
|
1981
|
+
if (storePacket.cmd === 'publish') {
|
|
1982
|
+
// The original packet is for sending.
|
|
1983
|
+
// The cloned storePacket is for storing to resend on reconnect.
|
|
1984
|
+
// Topic Alias must not be used after disconnected.
|
|
1985
|
+
storePacket = clone(packet)
|
|
1986
|
+
const err = this._removeTopicAliasAndRecoverTopicName(
|
|
1987
|
+
storePacket as IPublishPacket,
|
|
1988
|
+
)
|
|
1989
|
+
if (err) {
|
|
1990
|
+
return cb && cb(err)
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1994
|
+
const qos = (storePacket as IPublishPacket).qos || 0
|
|
1995
|
+
// check that the packet is not a qos of 0, or that the command is not a publish
|
|
1996
|
+
if ((qos === 0 && this.queueQoSZero) || storePacket.cmd !== 'publish') {
|
|
1997
|
+
this.queue.push({ packet: storePacket, cb })
|
|
1998
|
+
} else if (qos > 0) {
|
|
1999
|
+
cb = this.outgoing[storePacket.messageId]
|
|
2000
|
+
? this.outgoing[storePacket.messageId].cb
|
|
2001
|
+
: null
|
|
2002
|
+
this.outgoingStore.put(storePacket, (err) => {
|
|
2003
|
+
if (err) {
|
|
2004
|
+
return cb && cb(err)
|
|
2005
|
+
}
|
|
2006
|
+
cbStorePut()
|
|
2007
|
+
})
|
|
2008
|
+
} else if (cb) {
|
|
2009
|
+
cb(new Error('No connection to broker'))
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
/**
|
|
2014
|
+
* _setupPingTimer - setup the ping timer
|
|
2015
|
+
*
|
|
2016
|
+
* @api private
|
|
2017
|
+
*/
|
|
2018
|
+
private _setupPingTimer() {
|
|
2019
|
+
this.log(
|
|
2020
|
+
'_setupPingTimer :: keepalive %d (seconds)',
|
|
2021
|
+
this.options.keepalive,
|
|
2022
|
+
)
|
|
2023
|
+
|
|
2024
|
+
if (!this.pingTimer && this.options.keepalive) {
|
|
2025
|
+
this.pingResp = true
|
|
2026
|
+
this.pingTimer = reInterval(() => {
|
|
2027
|
+
this._checkPing()
|
|
2028
|
+
}, this.options.keepalive * 1000)
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
/**
|
|
2033
|
+
* _shiftPingInterval - reschedule the ping interval
|
|
2034
|
+
*
|
|
2035
|
+
* @api private
|
|
2036
|
+
*/
|
|
2037
|
+
private _shiftPingInterval() {
|
|
2038
|
+
if (
|
|
2039
|
+
this.pingTimer &&
|
|
2040
|
+
this.options.keepalive &&
|
|
2041
|
+
this.options.reschedulePings
|
|
2042
|
+
) {
|
|
2043
|
+
this.pingTimer.reschedule(this.options.keepalive * 1000)
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2047
|
+
/**
|
|
2048
|
+
* _checkPing - check if a pingresp has come back, and ping the server again
|
|
2049
|
+
*
|
|
2050
|
+
* @api private
|
|
2051
|
+
*/
|
|
2052
|
+
private _checkPing() {
|
|
2053
|
+
this.log('_checkPing :: checking ping...')
|
|
2054
|
+
if (this.pingResp) {
|
|
2055
|
+
this.log(
|
|
2056
|
+
'_checkPing :: ping response received. Clearing flag and sending `pingreq`',
|
|
2057
|
+
)
|
|
2058
|
+
this.pingResp = false
|
|
2059
|
+
this._sendPacket({ cmd: 'pingreq' })
|
|
2060
|
+
} else {
|
|
2061
|
+
// do a forced cleanup since socket will be in bad shape
|
|
2062
|
+
this.log('_checkPing :: calling _cleanUp with force true')
|
|
2063
|
+
this._cleanUp(true)
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
/**
|
|
2068
|
+
* _resubscribe
|
|
2069
|
+
* @api private
|
|
2070
|
+
*/
|
|
2071
|
+
private _resubscribe() {
|
|
2072
|
+
this.log('_resubscribe')
|
|
2073
|
+
const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
|
|
2074
|
+
if (
|
|
2075
|
+
!this._firstConnection &&
|
|
2076
|
+
(this.options.clean ||
|
|
2077
|
+
(this.options.protocolVersion === 5 &&
|
|
2078
|
+
!this.connackPacket.sessionPresent)) &&
|
|
2079
|
+
_resubscribeTopicsKeys.length > 0
|
|
2080
|
+
) {
|
|
2081
|
+
if (this.options.resubscribe) {
|
|
2082
|
+
if (this.options.protocolVersion === 5) {
|
|
2083
|
+
this.log('_resubscribe: protocolVersion 5')
|
|
2084
|
+
for (
|
|
2085
|
+
let topicI = 0;
|
|
2086
|
+
topicI < _resubscribeTopicsKeys.length;
|
|
2087
|
+
topicI++
|
|
2088
|
+
) {
|
|
2089
|
+
const resubscribeTopic: ISubscriptionMap = {}
|
|
2090
|
+
resubscribeTopic[_resubscribeTopicsKeys[topicI]] =
|
|
2091
|
+
this._resubscribeTopics[
|
|
2092
|
+
_resubscribeTopicsKeys[topicI]
|
|
2093
|
+
]
|
|
2094
|
+
resubscribeTopic.resubscribe = true
|
|
2095
|
+
this.subscribe(resubscribeTopic, {
|
|
2096
|
+
properties:
|
|
2097
|
+
resubscribeTopic[_resubscribeTopicsKeys[topicI]]
|
|
2098
|
+
.properties,
|
|
2099
|
+
})
|
|
2100
|
+
}
|
|
2101
|
+
} else {
|
|
2102
|
+
this._resubscribeTopics.resubscribe = true
|
|
2103
|
+
this.subscribe(this._resubscribeTopics)
|
|
2104
|
+
}
|
|
2105
|
+
} else {
|
|
2106
|
+
this._resubscribeTopics = {}
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
|
|
2110
|
+
this._firstConnection = false
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
/**
|
|
2114
|
+
* _onConnect
|
|
2115
|
+
*
|
|
2116
|
+
* @api private
|
|
2117
|
+
*/
|
|
2118
|
+
private _onConnect(packet: IConnackPacket) {
|
|
2119
|
+
if (this.disconnected) {
|
|
2120
|
+
this.emit('connect', packet)
|
|
2121
|
+
return
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
this.connackPacket = packet
|
|
2125
|
+
this.messageIdProvider.clear()
|
|
2126
|
+
this._setupPingTimer()
|
|
2127
|
+
|
|
2128
|
+
this.connected = true
|
|
2129
|
+
|
|
2130
|
+
/** check if there are packets in outgoing store and stream them */
|
|
2131
|
+
const startStreamProcess = () => {
|
|
2132
|
+
let outStore = this.outgoingStore.createStream()
|
|
2133
|
+
|
|
2134
|
+
/** destroy the outgoing store stream */
|
|
2135
|
+
const remove = () => {
|
|
2136
|
+
outStore.destroy()
|
|
2137
|
+
outStore = null
|
|
2138
|
+
this._flushStoreProcessingQueue()
|
|
2139
|
+
clearStoreProcessing()
|
|
2140
|
+
}
|
|
2141
|
+
|
|
2142
|
+
/** stop store processing and clear packets id processed */
|
|
2143
|
+
const clearStoreProcessing = () => {
|
|
2144
|
+
this._storeProcessing = false
|
|
2145
|
+
this._packetIdsDuringStoreProcessing = {}
|
|
2146
|
+
}
|
|
2147
|
+
|
|
2148
|
+
this.once('close', remove)
|
|
2149
|
+
outStore.on('error', (err) => {
|
|
2150
|
+
clearStoreProcessing()
|
|
2151
|
+
this._flushStoreProcessingQueue()
|
|
2152
|
+
this.removeListener('close', remove)
|
|
2153
|
+
this.emit('error', err)
|
|
2154
|
+
})
|
|
2155
|
+
|
|
2156
|
+
/** Read next packet in outgoing store and send it */
|
|
2157
|
+
const storeDeliver = () => {
|
|
2158
|
+
// edge case, we wrapped this twice
|
|
2159
|
+
if (!outStore) {
|
|
2160
|
+
return
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
const packet2 = outStore.read(1)
|
|
2164
|
+
|
|
2165
|
+
let cb: PacketCallback
|
|
2166
|
+
|
|
2167
|
+
if (!packet2) {
|
|
2168
|
+
// read when data is available in the future
|
|
2169
|
+
outStore.once('readable', storeDeliver)
|
|
2170
|
+
return
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
this._storeProcessing = true
|
|
2174
|
+
|
|
2175
|
+
// Skip already processed store packets
|
|
2176
|
+
if (this._packetIdsDuringStoreProcessing[packet2.messageId]) {
|
|
2177
|
+
storeDeliver()
|
|
2178
|
+
return
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
// Avoid unnecessary stream read operations when disconnected
|
|
2182
|
+
if (!this.disconnecting && !this.reconnectTimer) {
|
|
2183
|
+
cb = this.outgoing[packet2.messageId]
|
|
2184
|
+
? this.outgoing[packet2.messageId].cb
|
|
2185
|
+
: null
|
|
2186
|
+
this.outgoing[packet2.messageId] = {
|
|
2187
|
+
volatile: false,
|
|
2188
|
+
cb(err, status) {
|
|
2189
|
+
// Ensure that the original callback passed in to publish gets invoked
|
|
2190
|
+
if (cb) {
|
|
2191
|
+
cb(err, status)
|
|
2192
|
+
}
|
|
2193
|
+
|
|
2194
|
+
storeDeliver()
|
|
2195
|
+
},
|
|
2196
|
+
}
|
|
2197
|
+
this._packetIdsDuringStoreProcessing[packet2.messageId] =
|
|
2198
|
+
true
|
|
2199
|
+
if (this.messageIdProvider.register(packet2.messageId)) {
|
|
2200
|
+
this._sendPacket(packet2, undefined, undefined, true)
|
|
2201
|
+
} else {
|
|
2202
|
+
this.log(
|
|
2203
|
+
'messageId: %d has already used.',
|
|
2204
|
+
packet2.messageId,
|
|
2205
|
+
)
|
|
2206
|
+
}
|
|
2207
|
+
} else if (outStore.destroy) {
|
|
2208
|
+
outStore.destroy()
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
outStore.on('end', () => {
|
|
2213
|
+
let allProcessed = true
|
|
2214
|
+
for (const id in this._packetIdsDuringStoreProcessing) {
|
|
2215
|
+
if (!this._packetIdsDuringStoreProcessing[id]) {
|
|
2216
|
+
allProcessed = false
|
|
2217
|
+
break
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
if (allProcessed) {
|
|
2221
|
+
clearStoreProcessing()
|
|
2222
|
+
this.removeListener('close', remove)
|
|
2223
|
+
this._invokeAllStoreProcessingQueue()
|
|
2224
|
+
this.emit('connect', packet)
|
|
2225
|
+
} else {
|
|
2226
|
+
startStreamProcess()
|
|
2227
|
+
}
|
|
2228
|
+
})
|
|
2229
|
+
storeDeliver()
|
|
2230
|
+
}
|
|
2231
|
+
// start flowing
|
|
2232
|
+
startStreamProcess()
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
private _invokeStoreProcessingQueue() {
|
|
2236
|
+
// If _storeProcessing is true, the message is resending.
|
|
2237
|
+
// During resend, processing is skipped to prevent new messages from interrupting. #1635
|
|
2238
|
+
if (!this._storeProcessing && this._storeProcessingQueue.length > 0) {
|
|
2239
|
+
const f = this._storeProcessingQueue[0]
|
|
2240
|
+
if (f && f.invoke()) {
|
|
2241
|
+
this._storeProcessingQueue.shift()
|
|
2242
|
+
return true
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
return false
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
private _invokeAllStoreProcessingQueue() {
|
|
2249
|
+
while (this._invokeStoreProcessingQueue()) {
|
|
2250
|
+
/* empty */
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
|
|
2254
|
+
private _flushStoreProcessingQueue() {
|
|
2255
|
+
for (const f of this._storeProcessingQueue) {
|
|
2256
|
+
if (f.cbStorePut) f.cbStorePut(new Error('Connection closed'))
|
|
2257
|
+
if (f.callback) f.callback(new Error('Connection closed'))
|
|
2258
|
+
}
|
|
2259
|
+
this._storeProcessingQueue.splice(0)
|
|
2260
|
+
}
|
|
2261
|
+
|
|
2262
|
+
/**
|
|
2263
|
+
* _removeOutgoingAndStoreMessage
|
|
2264
|
+
* @param {Number} messageId - messageId to remove message
|
|
2265
|
+
* @param {Function} cb - called when the message removed
|
|
2266
|
+
* @api private
|
|
2267
|
+
*/
|
|
2268
|
+
private _removeOutgoingAndStoreMessage(
|
|
2269
|
+
messageId: number,
|
|
2270
|
+
cb: PacketCallback,
|
|
2271
|
+
) {
|
|
2272
|
+
delete this.outgoing[messageId]
|
|
2273
|
+
this.outgoingStore.del({ messageId }, (err, packet) => {
|
|
2274
|
+
cb(err, packet)
|
|
2275
|
+
this.messageIdProvider.deallocate(messageId)
|
|
2276
|
+
this._invokeStoreProcessingQueue()
|
|
2277
|
+
})
|
|
2278
|
+
}
|
|
2279
|
+
}
|