-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmqtt-gem.js
More file actions
1568 lines (1484 loc) · 74.8 KB
/
mqtt-gem.js
File metadata and controls
1568 lines (1484 loc) · 74.8 KB
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
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
module.exports = function (RED) {
"use strict";
const { getProxyForUrl } = require('./lib/proxyHelper');
var mqtt = require("mqtt");
var isUtf8 = require('is-utf8');
var HttpsProxyAgent = require('https-proxy-agent');
var url = require('url');
const knownMediaTypes = {
"text/css": "string",
"text/html": "string",
"text/plain": "string",
"application/json": "json",
"application/octet-stream": "buffer",
"application/pdf": "buffer",
"application/x-gtar": "buffer",
"application/x-gzip": "buffer",
"application/x-tar": "buffer",
"application/xml": "string",
"application/zip": "buffer",
"audio/aac": "buffer",
"audio/ac3": "buffer",
"audio/basic": "buffer",
"audio/mp4": "buffer",
"audio/ogg": "buffer",
"image/bmp": "buffer",
"image/gif": "buffer",
"image/jpeg": "buffer",
"image/tiff": "buffer",
"image/png": "buffer",
}
// Helper function to get the effective protocolVersion
function getEffectiveProtocolVersion(node) {
// If there is a valid custom value, use it
if (node.protocolVersionCustom && node.protocolVersionCustom.trim() !== "") {
var customValue = node.protocolVersionCustom.trim();
// Check if it is a valid number (3, 4, 5) or valid string
if (customValue === '3' || customValue === '4' || customValue === '5' ||
customValue === 3 || customValue === 4 || customValue === 5) {
return parseInt(customValue);
}
// If it is not a standard number, return it as a string (it could be an environment variable)
return customValue;
}
// Otherwise use the value from the select
return node.protocolVersion || 4;
}
//#region "Supporting functions"
function matchTopic(ts, t) {
if (ts == "#") {
return true;
}
/* The following allows shared subscriptions (as in MQTT v5)
http://docs.oasis-open.org/mqtt/mqtt/v5.0/cs02/mqtt-v5.0-cs02.html#_Toc514345522
4.8.2 describes shares like:
$share/{ShareName}/{filter}
$share is a literal string that marks the Topic Filter as being a Shared Subscription Topic Filter.
{ShareName} is a character string that does not include "/", "+" or "#"
{filter} The remainder of the string has the same syntax and semantics as a Topic Filter in a non-shared subscription. Refer to section 4.7.
*/
else if (ts.startsWith("$share")) {
ts = ts.replace(/^\$share\/[^#+/]+\/(.*)/g, "$1");
}
var re = new RegExp("^" + ts.replace(/([\[\]\?\(\)\\\\$\^\*\.|])/g, "\\$1").replace(/\+/g, "[^/]+").replace(/\/#$/, "(\/.*)?") + "$");
return re.test(t);
}
/**
* Helper function for setting integer property values in the MQTT V5 properties object
* @param {object} src Source object containing properties
* @param {object} dst Destination object to set/add properties
* @param {string} propName The property name to set in the Destination object
* @param {integer} [minVal] The minimum value. If the src value is less than minVal, it will NOT be set in the destination
* @param {integer} [maxVal] The maximum value. If the src value is greater than maxVal, it will NOT be set in the destination
* @param {integer} [def] An optional default to set in the destination object if prop is NOT present in the soruce object
*/
function setIntProp(src, dst, propName, minVal, maxVal, def) {
if (hasProperty(src, propName)) {
var v = parseInt(src[propName]);
if (isNaN(v)) return;
if (minVal != null) {
if (v < minVal) return;
}
if (maxVal != null) {
if (v > maxVal) return;
}
dst[propName] = v;
} else {
if (def != undefined) dst[propName] = def;
}
}
/**
* Test a topic string is valid for subscription
* @param {string} topic
* @returns `true` if it is a valid topic
*/
function isValidSubscriptionTopic(topic) {
return /^(#$|(\+|[^+#]*)(\/(\+|[^+#]*))*(\/(\+|#|[^+#]*))?$)/.test(topic);
}
/**
* Test a topic string is valid for publishing
* @param {string} topic
* @returns `true` if it is a valid topic
*/
function isValidPublishTopic(topic) {
if (topic.length === 0) return false;
return !/[\+#\b\f\n\r\t\v\0]/.test(topic);
}
/**
* Helper function for setting string property values in the MQTT V5 properties object
* @param {object} src Source object containing properties
* @param {object} dst Destination object to set/add properties
* @param {string} propName The property name to set in the Destination object
* @param {string} [def] An optional default to set in the destination object if prop is NOT present in the soruce object
*/
function setStrProp(src, dst, propName, def) {
if (src[propName] && typeof src[propName] == "string") {
dst[propName] = src[propName];
} else {
if (def != undefined) dst[propName] = def;
}
}
/**
* Helper function for setting boolean property values in the MQTT V5 properties object
* @param {object} src Source object containing properties
* @param {object} dst Destination object to set/add properties
* @param {string} propName The property name to set in the Destination object
* @param {boolean} [def] An optional default to set in the destination object if prop is NOT present in the soruce object
*/
function setBoolProp(src, dst, propName, def) {
if (src[propName] != null) {
if (src[propName] === "true" || src[propName] === true) {
dst[propName] = true;
} else if (src[propName] === "false" || src[propName] === false) {
dst[propName] = false;
}
} else {
if (def != undefined) dst[propName] = def;
}
}
/**
* Helper function for copying the MQTT v5 srcUserProperties object (parameter1) to the properties object (parameter2).
* Any property in srcUserProperties that is NOT a key/string pair will be silently discarded.
* NOTE: if no sutable properties are present, the userProperties object will NOT be added to the properties object
* @param {object} srcUserProperties An object with key/value string pairs
* @param {object} properties A properties object in which userProperties will be copied to
*/
function setUserProperties(srcUserProperties, properties) {
if (srcUserProperties && typeof srcUserProperties == "object") {
let _clone = {};
let count = 0;
let keys = Object.keys(srcUserProperties);
if (!keys || !keys.length) return null;
keys.forEach(key => {
let val = srcUserProperties[key];
if (typeof val === "string") {
count++;
_clone[key] = val;
} else if (val !== undefined && val !== null) {
try {
_clone[key] = JSON.stringify(val)
count++;
} catch (err) {
// Silently drop property
}
}
});
if (count) properties.userProperties = _clone;
}
}
/**
* Helper function for copying the MQTT v5 buffer type properties
* NOTE: if src[propName] is not a buffer, dst[propName] will NOT be assigned a value (unless def is set)
* @param {object} src Source object containing properties
* @param {object} dst Destination object to set/add properties
* @param {string} propName The property name to set in the Destination object
* @param {boolean} [def] An optional default to set in the destination object if prop is NOT present in the Source object
*/
function setBufferProp(src, dst, propName, def) {
if (!dst) return;
if (src && dst) {
var buf = src[propName];
if (buf && typeof Buffer.isBuffer(buf)) {
dst[propName] = Buffer.from(buf);
}
} else {
if (def != undefined) dst[propName] = def;
}
}
/**
* Helper function for applying changes to an objects properties ONLY when the src object actually has the property.
* This avoids setting a `dst` property null/undefined when the `src` object doesnt have the named property.
* @param {object} src Source object containing properties
* @param {object} dst Destination object to set property
* @param {string} propName The property name to set in the Destination object
* @param {boolean} force force the dst property to be updated/created even if src property is empty
*/
function setIfHasProperty(src, dst, propName, force) {
if (src && dst && propName) {
const ok = force || hasProperty(src, propName);
if (ok) {
dst[propName] = src[propName];
}
}
}
/**
* Helper function to test an object has a property
* @param {object} obj Object to test
* @param {string} propName Name of property to find
* @returns true if object has property `propName`
*/
function hasProperty(obj, propName) {
//JavaScript does not protect the property name hasOwnProperty
//Object.prototype.hasOwnProperty.call is the recommended/safer test
return Object.prototype.hasOwnProperty.call(obj, propName);
}
/**
* Handle the payload / packet recieved in MQTT In and MQTT Sub nodes
*/
function subscriptionHandler(node, datatype, topic, payload, packet) {
const msg = { topic: topic, payload: null, qos: packet.qos, retain: packet.retain };
const v5 = (node && node.brokerConn)
? node.brokerConn.v5()
: Object.prototype.hasOwnProperty.call(packet, "properties");
if (v5 && packet.properties) {
setStrProp(packet.properties, msg, "responseTopic");
setBufferProp(packet.properties, msg, "correlationData");
setStrProp(packet.properties, msg, "contentType");
setIntProp(packet.properties, msg, "messageExpiryInterval", 0);
setBoolProp(packet.properties, msg, "payloadFormatIndicator");
setStrProp(packet.properties, msg, "reasonString");
setUserProperties(packet.properties.userProperties, msg);
}
const v5isUtf8 = v5 ? msg.payloadFormatIndicator === true : null;
const v5HasMediaType = v5 ? !!msg.contentType : null;
const v5MediaTypeLC = v5 ? (msg.contentType + "").toLowerCase() : null;
if (datatype === "buffer") {
// payload = payload;
} else if (datatype === "base64") {
payload = payload.toString('base64');
} else if (datatype === "utf8") {
payload = payload.toString('utf8');
} else if (datatype === "json") {
if (v5isUtf8 || isUtf8(payload)) {
try {
payload = JSON.parse(payload.toString());
} catch (e) {
node.error(RED._("mqtt.errors.invalid-json-parse"), { payload: payload, topic: topic, qos: packet.qos, retain: packet.retain }); return;
}
} else {
node.error((RED._("mqtt.errors.invalid-json-string")), { payload: payload, topic: topic, qos: packet.qos, retain: packet.retain }); return;
}
} else {
//"auto" (legacy) or "auto-detect" (new default)
if (v5isUtf8 || v5HasMediaType) {
const outputType = knownMediaTypes[v5MediaTypeLC]
switch (outputType) {
case "string":
payload = payload.toString();
break;
case "buffer":
//no change
break;
case "json":
try {
//since v5 type states this should be JSON, parse it & error out if NOT JSON
payload = payload.toString()
const obj = JSON.parse(payload);
if (datatype === "auto-detect") {
payload = obj; //as mode is "auto-detect", return the parsed JSON
}
} catch (e) {
node.error(RED._("mqtt.errors.invalid-json-parse"), { payload: payload, topic: topic, qos: packet.qos, retain: packet.retain }); return;
}
break;
default:
if (v5isUtf8 || isUtf8(payload)) {
payload = payload.toString(); //auto String
if (datatype === "auto-detect") {
try {
payload = JSON.parse(payload); //auto to parsed object (attempt)
} catch (e) {
/* mute error - it simply isnt JSON, just leave payload as a string */
}
}
}
break;
}
} else if (isUtf8(payload)) {
payload = payload.toString(); //auto String
if (datatype === "auto-detect") {
try {
payload = JSON.parse(payload);
} catch (e) {
/* mute error - it simply isnt JSON, just leave payload as a string */
}
}
} //else {
//leave as buffer
//}
}
msg.payload = payload;
if (node.brokerConn && (node.brokerConn.broker === "localhost" || node.brokerConn.broker === "127.0.0.1")) {
msg._topic = topic;
}
node.send(msg);
}
/**
* Send an mqtt message to broker
* @param {MQTTOutNode} node the owner node
* @param {object} msg The msg to prepare for publishing
* @param {function} done callback when done
*/
function doPublish(node, msg, done) {
try {
done = typeof done == "function" ? done : function noop() { };
let v5 = node.brokerConn.options && node.brokerConn.options.protocolVersion == 5;
const bsp = (node.brokerConn && node.brokerConn.serverProperties) || {};
//Sanitise the `msg` object properties ready for publishing
if (msg.qos) {
msg.qos = parseInt(msg.qos);
if ((msg.qos !== 0) && (msg.qos !== 1) && (msg.qos !== 2)) {
msg.qos = null;
}
}
/* If node properties exists, override/set that to property in msg */
if (node.topic) { msg.topic = node.topic; }
msg.qos = Number(node.qos || msg.qos || 0);
msg.retain = node.retain || msg.retain || false;
msg.retain = ((msg.retain === true) || (msg.retain === "true")) || false;
if (v5) {
if (node.userProperties) {
msg.userProperties = node.userProperties;
}
if (node.responseTopic) {
msg.responseTopic = node.responseTopic;
}
if (node.correlationData) {
msg.correlationData = node.correlationData;
}
if (node.contentType) {
msg.contentType = node.contentType;
}
if (node.messageExpiryInterval) {
msg.messageExpiryInterval = node.messageExpiryInterval;
}
}
if (hasProperty(msg, "payload")) {
// send the message
node.brokerConn.publish(msg, function (err) {
if (err && err.warn) {
node.warn(err);
return;
}
done(err);
});
} else {
done();
}
} catch (error) {
done(error);
}
}
function updateStatus(node, allNodes) {
let setStatus = setStatusDisconnected
if (node.connecting) {
setStatus = setStatusConnecting
} else if (node.connected) {
setStatus = setStatusConnected
}
setStatus(node, allNodes)
}
function setStatusDisconnected(node, allNodes) {
if (allNodes) {
for (var id in node.users) {
if (hasProperty(node.users, id)) {
node.users[id].status({ fill: "red", shape: "ring", text: "node-red:common.status.disconnected" });
}
}
} else {
node.status({ fill: "red", shape: "ring", text: "node-red:common.status.disconnected" });
}
}
function setStatusConnecting(node, allNodes) {
if (allNodes) {
for (var id in node.users) {
if (hasProperty(node.users, id)) {
node.users[id].status({ fill: "yellow", shape: "ring", text: "node-red:common.status.connecting" });
}
}
} else {
node.status({ fill: "yellow", shape: "ring", text: "node-red:common.status.connecting" });
}
}
function setStatusConnected(node, allNodes) {
if (allNodes) {
for (var id in node.users) {
if (hasProperty(node.users, id)) {
node.users[id].status({ fill: "green", shape: "dot", text: "node-red:common.status.connected" });
}
}
} else {
node.status({ fill: "green", shape: "dot", text: "node-red:common.status.connected" });
}
}
/**
* Perform the connect action
* @param {MQTTInNode|MQTTOutNode} node
* @param {Object} msg
* @param {Function} done
*/
function handleConnectAction(node, msg, done) {
let actionData = typeof msg.broker === 'object' ? msg.broker : null;
if (node.brokerConn.canConnect()) {
// Not currently connected/connecting - trigger the connect
if (actionData) {
node.brokerConn.setOptions(actionData);
}
node.brokerConn.connect(function () {
done();
});
} else {
// Already Connected/Connecting
if (!actionData) {
// All is good - already connected and no broker override provided
done()
} else if (actionData.force) {
// The force flag tells us to cycle the connection.
node.brokerConn.disconnect(function () {
node.brokerConn.setOptions(actionData);
node.brokerConn.connect(function () {
done();
});
})
} else {
// Without force flag, we will refuse to cycle an active connection
done(new Error(RED._('mqtt.errors.invalid-action-alreadyconnected')));
}
}
}
/**
* Perform the disconnect action
* @param {MQTTInNode|MQTTOutNode} node
* @param {Function} done
*/
function handleDisconnectAction(node, done) {
node.brokerConn.disconnect(function () {
done();
});
}
const unsubscribeCandidates = {}
//#endregion "Supporting functions"
//#region "Broker node"
function MQTTBrokerNode(n) {
RED.nodes.createNode(this, n);
const node = this;
node.users = {};
// Config node state
node.brokerurl = "";
node.connected = false;
node.connecting = false;
node.closing = false;
node.options = {};
node.queue = [];
node.subscriptions = {};
node.clientListeners = []
/** @type {mqtt.MqttClient}*/ this.client;
node.setOptions = function (opts, init) {
if (!opts || typeof opts !== "object") {
return; //nothing to change, simply return
}
//apply property changes (only if the property exists in the opts object)
setIfHasProperty(opts, node, "url", init);
setIfHasProperty(opts, node, "broker", init);
setIfHasProperty(opts, node, "port", init);
setIfHasProperty(opts, node, "clientid", init);
setIfHasProperty(opts, node, "autoConnect", init);
setIfHasProperty(opts, node, "usetls", init);
setIfHasProperty(opts, node, "verifyservercert", init);
setIfHasProperty(opts, node, "compatmode", init);
setIfHasProperty(opts, node, "protocolVersion", init);
setIfHasProperty(opts, node, "protocolVersionCustom", init);
setIfHasProperty(opts, node, "keepalive", init);
setIfHasProperty(opts, node, "cleansession", init);
setIfHasProperty(opts, node, "autoUnsubscribe", init);
setIfHasProperty(opts, node, "topicAliasMaximum", init);
setIfHasProperty(opts, node, "maximumPacketSize", init);
setIfHasProperty(opts, node, "receiveMaximum", init);
//https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901116
if (hasProperty(opts, "userProperties")) {
node.userProperties = opts.userProperties;
} else if (hasProperty(opts, "userProps")) {
node.userProperties = opts.userProps;
}
if (hasProperty(opts, "sessionExpiry")) {
node.sessionExpiryInterval = opts.sessionExpiry;
} else if (hasProperty(opts, "sessionExpiryInterval")) {
node.sessionExpiryInterval = opts.sessionExpiryInterval
}
function createLWT(topic, payload, qos, retain, v5opts, v5SubPropName) {
let message = undefined;
if (topic) {
message = {
topic: topic,
payload: payload || "",
qos: Number(qos || 0),
retain: retain == "true" || retain === true,
}
if (v5opts) {
let v5Properties = message;
if (v5SubPropName) {
v5Properties = message[v5SubPropName] = {};
}
//re-align local prop name to mqttjs std
if (hasProperty(v5opts, "respTopic")) { v5opts.responseTopic = v5opts.respTopic; }
if (hasProperty(v5opts, "correl")) { v5opts.correlationData = v5opts.correl; }
if (hasProperty(v5opts, "expiry")) { v5opts.messageExpiryInterval = v5opts.expiry; }
if (hasProperty(v5opts, "delay")) { v5opts.willDelayInterval = v5opts.delay; }
if (hasProperty(v5opts, "userProps")) { v5opts.userProperties = v5opts.userProps; }
//setup v5 properties
if (typeof v5opts.userProperties == "string" && /^ *{/.test(v5opts.userProperties)) {
try {
setUserProperties(JSON.parse(v5opts.userProps), v5Properties);
} catch (err) { }
} else if (typeof v5opts.userProperties == "object") {
setUserProperties(v5opts.userProperties, v5Properties);
}
setStrProp(v5opts, v5Properties, "contentType");
setStrProp(v5opts, v5Properties, "responseTopic");
setBufferProp(v5opts, v5Properties, "correlationData");
setIntProp(v5opts, v5Properties, "messageExpiryInterval");
setIntProp(v5opts, v5Properties, "willDelayInterval");
}
}
return message;
}
if (init) {
if (hasProperty(opts, "birthTopic")) {
node.birthMessage = createLWT(opts.birthTopic, opts.birthPayload, opts.birthQos, opts.birthRetain, opts.birthMsg, "");
};
if (hasProperty(opts, "closeTopic")) {
node.closeMessage = createLWT(opts.closeTopic, opts.closePayload, opts.closeQos, opts.closeRetain, opts.closeMsg, "");
};
if (hasProperty(opts, "willTopic")) {
//will v5 properties must be set in the "properties" sub object
node.options.will = createLWT(opts.willTopic, opts.willPayload, opts.willQos, opts.willRetain, opts.willMsg, "properties");
};
} else {
//update options
if (hasProperty(opts, "birth")) {
if (typeof opts.birth !== "object") { opts.birth = {}; }
node.birthMessage = createLWT(opts.birth.topic, opts.birth.payload, opts.birth.qos, opts.birth.retain, opts.birth.properties, "");
}
if (hasProperty(opts, "close")) {
if (typeof opts.close !== "object") { opts.close = {}; }
node.closeMessage = createLWT(opts.close.topic, opts.close.payload, opts.close.qos, opts.close.retain, opts.close.properties, "");
}
if (hasProperty(opts, "will")) {
if (typeof opts.will !== "object") { opts.will = {}; }
//will v5 properties must be set in the "properties" sub object
node.options.will = createLWT(opts.will.topic, opts.will.payload, opts.will.qos, opts.will.retain, opts.will.properties, "properties");
}
}
if (node.credentials) {
node.username = node.credentials.user;
node.password = node.credentials.password;
}
if (!init & hasProperty(opts, "username")) {
node.username = opts.username;
};
if (!init & hasProperty(opts, "password")) {
node.password = opts.password;
};
// If the config node is missing certain options (it was probably deployed prior to an update to the node code),
// select/generate sensible options for the new fields
if (typeof node.usetls === 'undefined') {
node.usetls = false;
}
if (typeof node.verifyservercert === 'undefined') {
node.verifyservercert = false;
}
if (typeof node.keepalive === 'undefined') {
node.keepalive = 60;
} else if (typeof node.keepalive === 'string') {
node.keepalive = Number(node.keepalive);
}
if (typeof node.cleansession === 'undefined') {
node.cleansession = true;
}
if (typeof node.autoUnsubscribe !== 'boolean') {
node.autoUnsubscribe = true;
}
//use url or build a url from usetls://broker:port
if (node.url && node.brokerurl !== node.url) {
node.brokerurl = node.url;
} else {
// if the broker is ws:// or wss:// or tcp://
if ((typeof node.broker === 'string') && node.broker.indexOf("://") > -1) {
node.brokerurl = node.broker;
// Only for ws or wss, check if proxy env var for additional configuration
if (node.brokerurl.indexOf("wss://") > -1 || node.brokerurl.indexOf("ws://") > -1) {
// check if proxy is set in env
const prox = getProxyForUrl(node.brokerurl, RED.settings.proxyOptions);
if (prox) {
var parsedUrl = url.parse(node.brokerurl);
var proxyOpts = url.parse(prox);
// true for wss
proxyOpts.secureEndpoint = parsedUrl.protocol ? parsedUrl.protocol === 'wss:' : true;
// Set Agent for wsOption in MQTT
var agent = new HttpsProxyAgent(proxyOpts);
node.options.wsOptions = {
agent: agent
};
}
}
} else {
// construct the std mqtt:// url
if (node.usetls === true || node.usetls === "true") {
node.brokerurl = "mqtts://";
} else {
node.brokerurl = "mqtt://";
}
if (node.broker !== "") {
//Check for an IPv6 address
if (/(?:^|(?<=\s))(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(?=\s|$)/.test(node.broker)) {
node.brokerurl = node.brokerurl + "[" + node.broker + "]:";
} else {
node.brokerurl = node.brokerurl + node.broker + ":";
}
// port now defaults to 1883 if unset.
if (!node.port) {
node.brokerurl = node.brokerurl + "1883";
} else {
// Assicurati che port sia una stringa valida
node.brokerurl = node.brokerurl + node.port.toString();
}
} else {
node.brokerurl = node.brokerurl + "localhost:1883";
}
}
}
// Ensure cleansession set if clientid not supplied
if (!node.cleansession && !node.clientid) {
node.cleansession = true;
node.warn(RED._("mqtt.errors.nonclean-missingclientid"));
}
// Build options for passing to the MQTT.js API
node.options.username = node.username;
node.options.password = node.password;
node.options.keepalive = node.keepalive;
node.options.clean = node.cleansession;
node.options.clientId = node.clientid || 'nodered' + RED.util.generateId();
node.options.reconnectPeriod = RED.settings.mqttReconnectTime || 5000;
delete node.options.protocolId; //V4+ default
delete node.options.protocolVersion; //V4 default
delete node.options.properties;//V5 only
var effectiveProtocolVersion = getEffectiveProtocolVersion(node);
if (node.compatmode == "true" || node.compatmode === true || effectiveProtocolVersion == 3 || effectiveProtocolVersion == "3") {
node.options.protocolId = 'MQIsdp';//V3 compat only
node.options.protocolVersion = 3;
node.log("MQTT-GEM: Using MQTT v3 (effective: " + effectiveProtocolVersion + ")");
} else if (effectiveProtocolVersion == 5 || effectiveProtocolVersion == "5") {
delete node.options.protocolId;
node.options.protocolVersion = 5; // Questo rimane ora
node.log("MQTT-GEM: Using MQTT v5 (effective: " + effectiveProtocolVersion + ")");
node.options.properties = {};
node.options.properties.requestResponseInformation = true;
node.options.properties.requestProblemInformation = true;
if (node.userProperties && /^ *{/.test(node.userProperties)) {
try {
setUserProperties(JSON.parse(node.userProperties), node.options.properties);
} catch (err) { }
}
if (node.sessionExpiryInterval && node.sessionExpiryInterval !== "0") {
setIntProp(node, node.options.properties, "sessionExpiryInterval");
}
} else {
node.options.protocolVersion = 4;
node.log("MQTT-GEM: Using MQTT v4 (default) (effective: " + effectiveProtocolVersion + ")");
}
// Ensure will payload, if set, is a string
if (node.options.will && Object.hasOwn(node.options.will, 'payload')) {
let payload = node.options.will.payload
if (payload === null || typeof payload === 'undefined') {
payload = "";
} else if (!Buffer.isBuffer(payload)) {
if (typeof payload === "object") {
payload = JSON.stringify(payload);
} else if (typeof payload !== "string") {
payload = "" + payload;
}
}
node.options.will.payload = payload
}
if ((node.usetls === true || node.usetls === "true") && n.tls) {
var tlsNode = RED.nodes.getNode(n.tls);
if (tlsNode) {
tlsNode.addTLSOptions(node.options);
}
}
// If there's no rejectUnauthorized already, then this could be an
// old config where this option was provided on the broker node and
// not the tls node
if (typeof node.options.rejectUnauthorized === 'undefined') {
node.options.rejectUnauthorized = (node.verifyservercert == "true" || node.verifyservercert === true);
}
}
node.v5 = () => node.options && node.options.protocolVersion == 5
node.subscriptionIdentifiersAvailable = () => node.v5() && node.serverProperties && node.serverProperties.subscriptionIdentifiersAvailable
n.autoConnect = n.autoConnect === "false" || n.autoConnect === false ? false : true;
node.setOptions(n, true);
// Assicurati che autoConnect sia un booleano
node.autoConnect = node.autoConnect === "false" || node.autoConnect === false ? false : true;
// Define functions called by MQTT in and out nodes
node.register = function (mqttNode) {
node.users[mqttNode.id] = mqttNode;
if (Object.keys(node.users).length === 1) {
if (node.autoConnect) {
node.connect();
//update nodes status
setTimeout(function () {
updateStatus(node, true)
}, 1)
} else {
// If autoConnect is false, show disabled status
setTimeout(function () {
for (var id in node.users) {
if (hasProperty(node.users, id)) {
node.users[id].status({ fill: "grey", shape: "dot", text: "disabled" });
}
}
}, 1)
}
}
};
node.deregister = function (mqttNode, done, autoDisconnect) {
setStatusDisconnected(mqttNode, false);
delete node.users[mqttNode.id];
if (autoDisconnect && !node.closing && node.connected && Object.keys(node.users).length === 0) {
node.disconnect(done);
} else {
done();
}
};
node.canConnect = function () {
return !node.connected && !node.connecting;
}
node.connect = function (callback) {
if (node.canConnect()) {
node.closing = false;
node.connecting = true;
setStatusConnecting(node, true);
try {
node.serverProperties = {};
if (node.client) {
//belt and braces to avoid left over clients
node.client.end(true);
node._clientRemoveListeners();
}
// LOG DYNAMIC PARAMETERS - START
var effectiveProtocolVersion = getEffectiveProtocolVersion(node);
console.log("=== MQTT-GEM CONNECTION DEBUG ===");
console.log("Broker Name: " + (node.name || "unnamed"));
console.log("Broker URL: " + node.brokerurl);
console.log("Auto Connect: " + node.autoConnect + " (type: " + typeof node.autoConnect + ")");
console.log("Use TLS: " + node.usetls + " (type: " + typeof node.usetls + ")");
console.log("Port (original): " + node.port + " (type: " + typeof node.port + ")");
console.log("Protocol Version (select): " + node.protocolVersion);
console.log("Protocol Version (custom): " + (node.protocolVersionCustom || "not set"));
console.log("Protocol Version (effective): " + effectiveProtocolVersion + " (type: " + typeof effectiveProtocolVersion + ")");
console.log("Client ID: " + node.options.clientId);
console.log("Clean Session: " + node.options.clean);
console.log("Keep Alive: " + node.options.keepalive);
console.log("Final Options Protocol Version: " + node.options.protocolVersion);
console.log("=== END CONNECTION DEBUG ===");
// LOG DYNAMIC PARAMETERS - END
node.client = mqtt.connect(node.brokerurl, node.options);
node.client.setMaxListeners(0);
let callbackDone = false; //prevent re-connects causing node._clientOn('connect') to fire callback multiple times
// Register successful connect or reconnect handler
node._clientOn('connect', function (connack) {
node.closing = false;
node.connecting = false;
node.connected = true;
if (!callbackDone && typeof callback == "function") {
callback();
}
callbackDone = true;
node.topicAliases = {};
node.log(RED._("mqtt.state.connected", { broker: (node.clientid ? node.clientid + "@" : "") + node.brokerurl }));
if (node.options.protocolVersion == 5 && connack && hasProperty(connack, "properties")) {
if (typeof connack.properties == "object") {
//clean & assign all props sent from server.
setIntProp(connack.properties, node.serverProperties, "topicAliasMaximum", 0);
setIntProp(connack.properties, node.serverProperties, "receiveMaximum", 0);
setIntProp(connack.properties, node.serverProperties, "sessionExpiryInterval", 0, 0xFFFFFFFF);
setIntProp(connack.properties, node.serverProperties, "maximumQoS", 0, 2);
setBoolProp(connack.properties, node.serverProperties, "retainAvailable", true);
setBoolProp(connack.properties, node.serverProperties, "wildcardSubscriptionAvailable", true);
setBoolProp(connack.properties, node.serverProperties, "subscriptionIdentifiersAvailable", true);
setBoolProp(connack.properties, node.serverProperties, "sharedSubscriptionAvailable");
setIntProp(connack.properties, node.serverProperties, "maximumPacketSize", 0);
setIntProp(connack.properties, node.serverProperties, "serverKeepAlive");
setStrProp(connack.properties, node.serverProperties, "responseInformation");
setStrProp(connack.properties, node.serverProperties, "serverReference");
setStrProp(connack.properties, node.serverProperties, "assignedClientIdentifier");
setStrProp(connack.properties, node.serverProperties, "reasonString");
setUserProperties(connack.properties, node.serverProperties);
}
}
setStatusConnected(node, true);
// Remove any existing listeners before resubscribing to avoid duplicates in the event of a re-connection
node._clientRemoveListeners('message');
// Re-subscribe to stored topics
for (var s in node.subscriptions) {
if (node.subscriptions.hasOwnProperty(s)) {
for (var r in node.subscriptions[s]) {
if (node.subscriptions[s].hasOwnProperty(r)) {
node.subscribe(node.subscriptions[s][r])
}
}
}
}
// Send any birth message
if (node.birthMessage) {
setTimeout(() => {
node.publish(node.birthMessage);
}, 1);
}
});
node._clientOn("reconnect", function () {
setStatusConnecting(node, true);
});
//Broker Disconnect - V5 event
node._clientOn("disconnect", function (packet) {
//Emitted after receiving disconnect packet from broker. MQTT 5.0 feature.
const rc = (packet && packet.properties && packet.reasonCode) || packet.reasonCode;
const rs = packet && packet.properties && packet.properties.reasonString || "";
const details = {
broker: (node.clientid ? node.clientid + "@" : "") + node.brokerurl,
reasonCode: rc,
reasonString: rs
}
node.connected = false;
node.log(RED._("mqtt.state.broker-disconnected", details));
setStatusDisconnected(node, true);
});
// Register disconnect handlers
node._clientOn('close', function () {
if (node.connected) {
node.connected = false;
node.log(RED._("mqtt.state.disconnected", { broker: (node.clientid ? node.clientid + "@" : "") + node.brokerurl }));
setStatusDisconnected(node, true);
} else if (node.connecting) {
node.log(RED._("mqtt.state.connect-failed", { broker: (node.clientid ? node.clientid + "@" : "") + node.brokerurl }));
}
});
// Register connect error handler
// The client's own reconnect logic will take care of errors
node._clientOn('error', function (error) {
});
} catch (err) {
console.log(err);
}
}
};
node.disconnect = function (callback) {
const _callback = function () {
if (node.connected || node.connecting) {
setStatusDisconnected(node, true);
}
if (node.client) { node._clientRemoveListeners(); }
node.connecting = false;
node.connected = false;
callback && typeof callback == "function" && callback();
};
if (!node.client) { return _callback(); }
if (node.closing) { return _callback(); }
/**
* Call end and wait for the client to end (or timeout)
* @param {mqtt.MqttClient} client The broker client
* @param {number} ms The time to wait for the client to end
* @returns
*/
let waitEnd = (client, ms) => {
return new Promise((resolve, reject) => {
node.closing = true;
if (!client) {
resolve();
} else {
const t = setTimeout(() => {
//clean end() has exceeded WAIT_END, lets force end!
client && client.end(true);
resolve();
}, ms);
client.end(() => {
clearTimeout(t);
resolve()
});
}
});
};
if (node.connected && node.closeMessage) {
node.publish(node.closeMessage, function (err) {
waitEnd(node.client, 2000).then(() => {
_callback();
}).catch((e) => {
_callback();
})
});
} else {
waitEnd(node.client, 2000).then(() => {
_callback();
}).catch((e) => {
_callback();
})
}
}
node.subscriptionIds = {};
node.subid = 1;
//typedef for subscription object:
/**
* @typedef {Object} Subscription
* @property {String} topic - topic to subscribe to
* @property {Object} [options] - options object
* @property {Number} [options.qos] - quality of service
* @property {Number} [options.nl] - no local
* @property {Number} [options.rap] - retain as published
* @property {Number} [options.rh] - retain handling
* @property {Number} [options.properties] - MQTT 5.0 properties
* @property {Number} [options.properties.subscriptionIdentifier] - MQTT 5.0 subscription identifier
* @property {Number} [options.properties.userProperties] - MQTT 5.0 user properties
* @property {Function} callback
* @property {String} ref - reference to the node that created the subscription
*/
/**
* Create a subscription object
* @param {String} _topic - topic to subscribe to
* @param {Object} _options - options object
* @param {String} _ref - reference to the node that created the subscription
* @returns {Subscription}
*/
function createSubscriptionObject(_topic, _options, _ref, _brokerId) {