forked from plcpeople/mcprotocol
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mcprotocol.js
3957 lines (3469 loc) · 149 KB
/
mcprotocol.js
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
// MCPROTOCOL - A library for communication to Mitsubishi PLCs over Ethernet from node.js.
// Currently only FX3U CPUs using FX3U-ENET and FX3U-ENET-ADP modules (Ethernet modules) tested.
// Please report experiences with others.
// The MIT License (MIT)
// Copyright (c) 2015 Dana Moffit
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// EXTRA WARNING - This is BETA software and as such, be careful, especially when
// writing values to programmable controllers.
//
// Some actions or errors involving programmable controllers can cause injury or death,
// and YOU are indicating that you understand the risks, including the
// possibility that the wrong address will be overwritten with the wrong value,
// when using this library. Test thoroughly in a laboratory environment.
var net = require("net");
var dgram = require('dgram');
var EventEmitter = require('events').EventEmitter;
var util = require("util");
var inherits = require('util').inherits
var effectiveDebugLevel = 0; // intentionally global, shared between connections
var monitoringTime = 10;
module.exports = MCProtocol;
function MCProtocol() {
if (!(this instanceof MCProtocol)) return new MCProtocol();
EventEmitter.call(this);
var self = this;
//self.data = {};//for data access
self.readReq = new Buffer(1000);//not calculated
self.writeReq;// = new Buffer(1500);//size depends on PLC type! As Q/L can read/write 950 WDs
self.queue = [];
self.resetPending = false;
self.resetTimeout = undefined;
self.maxPDU = 255;
self.netClient = undefined;
self.connectionState = 0;
self.requestMaxParallel = 1;
self.maxParallel = 1; // MC protocol is read/response. Parallel jobs not supported.
self.isAscii = false;
self.octalInputOutput;
self.parallelJobsNow = 0;
self.maxGap = 5;
self.doNotOptimize = false;
self.connectCallback = undefined;
self.readDoneCallback = undefined;
self.writeDoneCallback = undefined;
self.connectTimeout = undefined;
self.PDUTimeout = undefined;
self.globalTimeout = 4500;
self.lastPacketSent = undefined;
self.readPacketArray = [];
self.writePacketArray = [];
self.polledReadBlockList = [];
self.globalReadBlockList = [];
self.globalWriteBlockList = [];
self.masterSequenceNumber = 1;
self.translationCB = function (tag) { return tag };
self.connectionParams = undefined;
self.connectionID = 'UNDEF';
self.addRemoveArray = [];
self.readPacketValid = false;
self.connectCBIssued = false;
self.queueTimer = undefined;
self.queuePollTime = 50;
self.queueMaxLength = 50;//avg time on good connection is 20ms. 20 * 50 = 1000ms to process.
}
inherits(MCProtocol, EventEmitter);
MCProtocol.prototype.isConnected = function () {
var self = this;
return self.connectionState == 4;
}
MCProtocol.prototype.setDebugLevel = function (level) {
var l = (level + "").toUpperCase();
switch (l) {
case 'TRACE':
effectiveDebugLevel = 4;
break;
case 'DEBUG':
effectiveDebugLevel = 3;
break;
case 'INFO':
effectiveDebugLevel = 2;
break;
case 'WARN':
effectiveDebugLevel = 1;
break;
case 'ERROR':
effectiveDebugLevel = 0;
break;
case 'NONE':
effectiveDebugLevel = -1;
break;
default:
effectiveDebugLevel = level;
}
}
MCProtocol.prototype.nextSequenceNumber = function () {
var self = this;
self.masterSequenceNumber += 1;
if (self.masterSequenceNumber > 32767) {
self.masterSequenceNumber = 1;
}
return self.masterSequenceNumber;
}
MCProtocol.prototype.setTranslationCB = function (cb) {
var self = this;
if (typeof cb === "function") {
outputLog('Translation OK', "TRACE");
self.translationCB = cb;
}
}
MCProtocol.prototype.initiateConnection = function (cParam, callback) {
var self = this;
if (cParam === undefined) { cParam = { port: 10000, host: '192.168.8.106', ascii: false }; }
outputLog('Initiate Called - Connecting to PLC with address and parameters...', "DEBUG");
outputLog(cParam, "DEBUG");
if (typeof (cParam.name) === 'undefined') {
self.connectionID = cParam.host;
} else {
self.connectionID = cParam.name;
}
if (typeof (cParam.ascii) === 'undefined') {
self.isAscii = false;
} else {
self.isAscii = cParam.ascii;
}
if (typeof (cParam.octalInputOutput) === 'undefined') {
self.octalInputOutput = false;
} else {
self.octalInputOutput = cParam.octalInputOutput;
}
if (typeof (cParam.plcType) === 'undefined') {
self.plcType = MCProtocol.prototype.enumPLCTypes.Q.name;
self.enumDeviceCodeSpec = MCProtocol.prototype.enumDeviceCodeSpecQ;//default to Q/L series
outputLog(`plcType not provided, defaulting to Q series PLC`,"WARN");
} else {
self.plcType = cParam.plcType;
if(!MCProtocol.prototype.enumPLCTypes[cParam.plcType]){
self.plcType = MCProtocol.prototype.enumPLCTypes.Q.name;
outputLog(`plcType '${cParam.plcType}' unknown. Currently supported types are '${MCProtocol.prototype.enumPLCTypes.keys.join("|")}', defaulting to Q series PLC`,"WARN");
}
self.plcSeries = MCProtocol.prototype.enumPLCTypes[self.plcType];
//not sure how best to handle A/QnA series - not even sure A series can do 3E/4E frames!
//for now, default to Q (will be overwritten below if user choses 1E frames)
self.enumDeviceCodeSpec = MCProtocol.prototype['enumDeviceCodeSpec' + self.plcType] || MCProtocol.prototype.enumDeviceCodeSpecQ;
outputLog(`'plcType' set is ${self.plcType}`,"INFO");
}
if (typeof (cParam.frame) === 'undefined') {
outputLog(`'frame' not provided, defaulting '3E'. Valid options are 1E, 3E, 4E.`,"WARN");
self.frame = '3E';
} else {
switch (cParam.frame.toUpperCase()) {
case '1E':
self.frame = '1E';
self.enumDeviceCodeSpec = MCProtocol.prototype.enumDeviceCodeSpec1E;
break;
case '3E':
self.frame = '3E';
break;
case '4E':
self.frame = '4E';
break;
default:
self.frame = '3E';
outputLog(`'frame' ${cParam.frame} is unknown. Defaulting to 3E. Valid options are 1E, 3E, 4E.`,"WARN");
break;
}
self.frame = cParam.frame;
outputLog(`'frame' set is ${self.frame}`,"INFO");
}
if(!self.enumDeviceCodeSpec){
throw new Error("Error determinng device code specification. Check combination of PLC Type and Frame Type are valid");
}
if (typeof (cParam.PLCStation) !== 'undefined') {
self.PLCStation = cParam.PLCStation;
}
if (typeof (cParam.PCStation) !== 'undefined') {
self.PCStation = cParam.PCStation;
}
if (typeof (cParam.network) !== 'undefined') {
self.network = cParam.network;
}
if (typeof (cParam.PLCModuleNo) !== 'undefined') {
self.PLCModuleNo = cParam.PLCModuleNo;
}
if (typeof (cParam.queuePollTime) !== 'undefined') {
self.queuePollTime = cParam.queuePollTime;
}
if (typeof (cParam.queueMaxAge) !== 'undefined') {
self.queueMaxAge = cParam.queueMaxAge;
} else {
self.queueMaxAge = 2000;
}
self.plcSeries = MCProtocol.prototype.enumPLCTypes[self.plcType];
self.writeReq = new Buffer(self.plcSeries.requiredWriteBufferSize);//size depends on PLC type! As Q/L can read/write 950 WDs
self.connectionParams = cParam;
self.connectCallback = callback;
self.connectCBIssued = false;
if (self.fakeTheConnection)//debug
self.connectCallback();
else
self.connectNow(self.connectionParams, false);
self.startQueueTimer = function (ms) {
self.queueTimer = setTimeout(() => {
self._processQueue()
}, ms);
}
self.startQueueTimer(self.queuePollTime);
self.processQueueASAP = function () {
setImmediate(() => {
outputLog(`🛢️ setImmediate Calling _processQueue() --> `, "TRACE");
self._processQueue();
});
}
self._processQueue = function () {
clearTimeout(self.queueTimer);
try {
if (!self.queue.length) {
return;
}
// {arg: , cb: , dt: }
var queueItem = self.queue[0];
var itemAge = Date.now() - queueItem.dt;
if (itemAge > self.queueMaxAge) {
outputLog(`🛢️➡🗑️ Discarding queued '${queueItem.fn}' item ${queueItem.arg} (item age is ${itemAge}ms, max age is ${self.queueMaxAge}ms)`, "WARN")
self.queue.shift();
return;//too old - discard
}
outputLog(`🛢️➡⚙️ Sending queued '${queueItem.fn}' item ${queueItem.arg}`, "DEBUG");
var result;
if (queueItem.fn == "read") {
result = _readItems(self, queueItem.arg, queueItem.cb, true);
} else if (queueItem.fn == "write") {
result = _writeItems(self, queueItem.arg, queueItem.value, queueItem.cb, true);
}
let allSent = result.every(function (r) {
return r.sendStatus == MCProtocol.prototype.enumSendResult.sent;
});
if (allSent) {
outputLog(`🛢️➡⚙️ Successfully sent queued '${queueItem.fn}' item '${queueItem.arg}'. (queue will be shifted to remove this item)`, "DEBUG");
self.queue.shift();//all sent shift the queued item - its done :)
return; //no need to continue
}
let noneSent = result.every(function (r) {
return r.sendStatus == MCProtocol.prototype.enumSendResult.notSent;
});
if (noneSent) {
outputLog(`🛢️➡X Queued '${queueItem.fn}' item ${queueItem.arg} NOT sent - will try again soon`, "DEBUG");
return; //no need to continue
}
//by default, if !allSent and !nonSent, then _some_ were sent!
outputLog(`🛢️➡☠️ Something failed to send '${queueItem.fn}' item '${queueItem.arg}'. Queue will be shifted to remove this item.`, "WARN");
self.queue.shift();//some sent / some bad - shift the queued item regardless
} catch (error) {
outputLog(`Something went wrong polling the queue: ${error}. Queue will be shifted to remove this item.`, "ERROR");
self.queue.shift();
} finally {
self.startQueueTimer();
}
} //_processQueue()
}
MCProtocol.prototype.dropConnection = function () {
var self = this;
outputLog(`dropConnection() called`, "TRACE", self.connectionID);
if(self.connectionParams.protocol == "UDP"){
//TODO - implement UDP
try {
if(self.netClient){
self.netClient.close();
}
} catch (error) {
outputLog(`dropConnection() caused an error error: ${error}`, "ERROR", self.connectionID);
}
} else {
try {
if (typeof (self.netClient) !== 'undefined') {
self.netClient.end();
}
} catch (error) {
outputLog(`dropConnection() caused an error error: ${error}`, "ERROR", self.connectionID);
}
}
self.connectionCleanup();
self.connected = false;
}
MCProtocol.prototype.close = function () {
this.dropConnection();
};
MCProtocol.prototype.connectNow = function (cParam, suppressCallback) { // TODO - implement or remove suppressCallback
var self = this;
if (self.connectionParams.protocol == "UDP") {
//TODO - implement UDP
// Track the connection state
self.connectionState = 1 // 1 = trying to connect
if (self.netClient) {
self.connectionState = 0
self.netClient.removeAllListeners();
delete self.netClient;
}
self.netClient = dgram.createSocket('udp4');
self.connected = false;
self.requests = {};
function close() {
self.connectionState = 0;
self.emit('close');
self.connected = false;
}
// self.netClient.on('listening', function () {
// self.onUDPConnect.apply(self, arguments);
// });
self.netClient.on('close', close);
//self.netClient.connect();
self.netClient.write = function(buffer){
self.netClient.send( buffer, 0, buffer.length, cParam.port, cParam.host, function (err) {
if (err) {
self.emit('error');//??
}
});
}
//{
outputLog('UDP Connection Setup to ' + cParam.host + ' on port ' + cParam.port, "DEBUG", self.connectionID);
self.netClient.removeAllListeners('data');
self.netClient.removeAllListeners('message');
self.netClient.removeAllListeners('error');
self.netClient.on('message', function () {
self.onResponse.apply(self, arguments);
}); // We need to make sure we don't add this event every time if we call it on data.
self.netClient.on('error', function () {
self.readWriteError.apply(self, arguments);
}); // Might want to remove the connecterror listener
self.emit('open');
if ((!self.connectCBIssued) && (typeof (self.connectCallback) === "function")) {
self.connectCBIssued = true;
self.connectCallback();
}
//}
self.connectionState = 4;
} else {
// Don't re-trigger.
if (self.connectionState >= 1) { return; }
self.connectionCleanup();
self.netClient = net.connect(cParam, function () {
self.netClient.setKeepAlive(true, 2500); // For reliable unplug detection in most cases - although it takes 10 minutes to notify
self.onTCPConnect.apply(self, arguments);
});
self.connectionState = 1; // 1 = trying to connect
self.netClient.on('error', function () {
self.connectError.apply(self, arguments);
});
self.netClient.on('close', function () {
self.onClientDisconnect.apply(self, arguments);
});
outputLog('<initiating a new connection>', "INFO", self.connectionID);
outputLog('Attempting to connect to host...', "DEBUG", self.connectionID);
}
}
MCProtocol.prototype.connectError = function (e) {
var self = this;
self.emit('error',e);
// Note that a TCP connection timeout error will appear here. An MC connection timeout error is a packet timeout.
outputLog('We Caught a connect error ' + e.code, "ERROR", self.connectionID);
if ((!self.connectCBIssued) && (typeof (self.connectCallback) === "function")) {
self.connectCBIssued = true;
self.connectCallback(e);
}
self.connectionState = 0;
}
MCProtocol.prototype.readWriteError = function (e) {
var self = this;
outputLog('We Caught a read/write error ' + e.code + ' - resetting connection', "ERROR", self.connectionID);
self.emit('error', e);
self.connectionState = 0;
self.connectionReset();
}
MCProtocol.prototype.packetTimeout = function (packetType, packetSeqNum) {
var self = this;
outputLog('PacketTimeout called with type ' + packetType + ' and seq ' + packetSeqNum, "WARN", self.connectionID);
if (packetType === "read") {
outputLog("READ TIMEOUT on sequence number " + packetSeqNum, "WARN", self.connectionID);
self.readResponse(undefined); //, self.findReadIndexOfSeqNum(packetSeqNum));
return undefined;
}
if (packetType === "write") {
outputLog("WRITE TIMEOUT on sequence number " + packetSeqNum, "WARN", self.connectionID);
self.writeResponse(undefined); //, self.findWriteIndexOfSeqNum(packetSeqNum));
return undefined;
}
outputLog("Unknown timeout error. Nothing was done - this shouldn't happen.", "ERROR", self.connectionID);
}
MCProtocol.prototype.onTCPConnect = function () {
var self = this;
outputLog('TCP Connection Established to ' + self.netClient.remoteAddress + ' on port ' + self.netClient.remotePort, "DEBUG", self.connectionID);
// Track the connection state
self.connectionState = 4; // 4 = all connected, simple with MC protocol. Other protocols have a negotiation/session packet as well.
self.netClient.removeAllListeners('data');
self.netClient.removeAllListeners('message');
self.netClient.removeAllListeners('error');
self.netClient.on('data', function () {
self.onResponse.apply(self, arguments);
}); // We need to make sure we don't add this event every time if we call it on data.
self.netClient.on('error', function () {
self.readWriteError.apply(self, arguments);
}); // Might want to remove the connecterror listener
self.emit('open');
if ((!self.connectCBIssued) && (typeof (self.connectCallback) === "function")) {
self.connectCBIssued = true;
self.connectCallback();
}
return;
}
MCProtocol.prototype.onUDPConnect = function () {
var self = this;
outputLog('UDP Connection Established to ' + self.netClient.remoteAddress + ' on port ' + self.netClient.remotePort, "DEBUG", self.connectionID);
// Track the connection state
self.connectionState = 4; // 4 = all connected, simple with MC protocol. Other protocols have a negotiation/session packet as well.
self.netClient.removeAllListeners('data');
self.netClient.removeAllListeners('message');
self.netClient.removeAllListeners('error');
self.netClient.on('message', function () {
self.onResponse.apply(self, arguments);
}); // We need to make sure we don't add this event every time if we call it on data.
self.netClient.on('error', function () {
self.readWriteError.apply(self, arguments);
}); // Might want to remove the connecterror listener
self.emit('open');
if ((!self.connectCBIssued) && (typeof (self.connectCallback) === "function")) {
self.connectCBIssued = true;
self.connectCallback();
}
return;
}
MCProtocol.prototype.writeItems = function (arg, value, cb) {
return _writeItems(this, arg, value, cb, false);
}
function _writeItems(self, arg, value, cb, queuedItem) {
//var self = this;
var i;
var reply = [];
outputLog("Preparing to WRITE " + arg, "DEBUG", self.connectionID);
//ensure arg is an array regardless of count
let argArr = arg;
let valueArr = value;
if (Array.isArray(arg) != true) {
argArr = [arg];
valueArr = [value];
}
if (self.isWaiting()) {
let sendStatus = MCProtocol.prototype.enumSendResult.unknown;
if (queuedItem) {
sendStatus = MCProtocol.prototype.enumSendResult.notSent;
outputLog(`️🛢️➡🚧 queued writeItem '${arg}' still not sent (isWaiting)`, "DEBUG")
} else if (self.queue.length >= self.queueMaxLength) {
outputLog(`️🛢️➡🗑️ writeItem '${arg}' discarded, queue full`, "WARN")
sendStatus = MCProtocol.prototype.enumSendResult.queueFull;
} else {
sendStatus = MCProtocol.prototype.enumSendResult.queued;
self.queue.push({
arg: arg,
value: value,
cb: cb,
fn: "write",
dt: Date.now()
});
outputLog(`️✏️➡🛢️ writeItem '${arg}' pushed to queue`, "DEBUG")
}
reply.push({ TAG: arg, sendStatus: sendStatus });//[item.useraddr] = MCProtocol.prototype.enumSendResult.badRequest;
return reply;
}
let plcitems = [];
for (i = 0; i < argArr.length; i++) {
if (typeof argArr[i] === "string") {
let plcitem = new PLCItem(self);
plcitem.init(self.translationCB(argArr[i]), argArr[i], self.octalInputOutput, self.frame, self.plcType, valueArr[i]);
plcitem._instance = "original";
if (Array.isArray(cb))
plcitem.cb = cb[i];
else
plcitem.cb = cb;
plcitems.push(plcitem);
}
}
//do callback for non initialised (bad) items
plcitems.map(function (item) {
if (item.initialised == false) {
if (item.cb) {
var cbd = new PLCWriteResult(item.useraddr, item.addr, MCProtocol.prototype.enumOPCQuality.badConfigErrInServer.value, 0);
cbd.extraInfo = item.initError;
item.cb(true, cbd);
}
item.extraInfo = item.initError;
reply.problem = true;
let r = {
TAG: item.useraddr,
sendStatus: MCProtocol.prototype.enumSendResult.badRequest
};
reply.push(r);//[item.useraddr] = MCProtocol.prototype.enumSendResult.badRequest;
}
});
//filter OK items
var plcitemsInitialised = plcitems.filter(function (item) {
return item.initialised;
});
var preparedCount = self.prepareWritePacket(plcitemsInitialised);
var plcitemsBuffered = plcitemsInitialised.filter(function (item) {
return item.bufferized;
});
//do callback for items not buffered
plcitemsInitialised.map(function (item) {
if (!item.bufferized) {
if (item.cb) {
var cbd = new PLCWriteResult(item.useraddr, item.addr, MCProtocol.prototype.enumOPCQuality.bad.value, 0);
item.cb(true, cbd);
}
item.extraInfo = item.lastError;
reply.problem = true;
let r = {
TAG: item.useraddr,
sendStatus: MCProtocol.prototype.enumSendResult.badRequest
};
reply.push(r);//[item.useraddr] = MCProtocol.prototype.enumSendResult.badRequest;
}
});
let sentCount = 0;
if (plcitemsBuffered.length) {
sentCount = self.sendWritePacket();
}
plcitemsBuffered.map(function (item) {
let s = sentCount ? MCProtocol.prototype.enumSendResult.sent : MCProtocol.prototype.enumSendResult.notSent;
if (s != MCProtocol.prototype.enumSendResult.sent) {
reply.problem = true;
}
let r = {
TAG: item.useraddr,
sendStatus: s
};
reply.push(r);
});
return reply;
}
MCProtocol.prototype.findItem = function (useraddr) {
var self = this;
var i;
var commstate = { value: self.connectionState !== 4, quality: 'OK' };
if (useraddr === '_COMMERR') { return commstate; }
for (i = 0; i < self.polledReadBlockList.length; i++) {
if (self.polledReadBlockList[i].useraddr === useraddr) { return self.polledReadBlockList[i]; }
}
return undefined;
}
MCProtocol.prototype.addItems = function (arg, cb) {
var self = this;
self.addRemoveArray.push({ arg: arg, cb: cb, action: 'poll' });
}
MCProtocol.prototype.addItemsNow = function (arg, action, cb) {
var self = this;
var i;
outputLog("Adding " + arg, "DEBUG", self.connectionID);
addItemsFlag = false;
var addedCount = 0;
var expectedCount = Array.isArray(arg) ? arg.length : 1;
if (typeof arg === "string" && arg !== "_COMMERR") {
//plcitem = stringToMCAddr(self.translationCB(arg), arg, self.octalInputOutput, self.frame, self.plcType);
let plcitem = new PLCItem(self);
plcitem.init(self.translationCB(arg), arg, self.octalInputOutput, self.frame, self.plcType, undefined /*not writing*/);
if (plcitem.initialised) {
plcitem.action = action;
plcitem.cb = cb;
self.polledReadBlockList.push(plcitem);
addedCount++;
} else {
outputLog(`Dropping bad request item '${arg}'`, "WARN");
}
} else if (Array.isArray(arg)) {
for (i = 0; i < arg.length; i++) {
if (typeof arg[i] === "string" && arg[i] !== "_COMMERR") {
//plcitem = stringToMCAddr(self.translationCB(arg[i]), arg[i], self.octalInputOutput, self.frame, self.plcType);
let plcitem = new PLCItem(self);
plcitem.init(self.translationCB(arg[i]), arg[i], self.octalInputOutput, self.frame, self.plcType, undefined /*not writing*/);
if (plcitem.initialised) {
if (Array.isArray(cb))
plcitem.cb = cb[i];
else
plcitem.cb = cb;
if (Array.isArray(action))
plcitem.action = action[i];
else
plcitem.action = action;
self.polledReadBlockList.push(plcitem);
addedCount++;
} else {
outputLog(`Dropping bad request item '${arg[i]}'`, "WARN");
}
}
}
}
// Validity check.
for (i = self.polledReadBlockList.length - 1; i >= 0; i--) {
if (self.polledReadBlockList[i] === undefined) {
self.polledReadBlockList.splice(i, 1);
outputLog("Dropping an undefined request item.", "WARN");
}
}
// prepareReadPacket();
self.readPacketValid = false;
}
MCProtocol.prototype.removeItems = function (arg) {
var self = this;
self.addRemoveArray.push({ arg: arg, action: 'remove' });
}
MCProtocol.prototype.removeItemsNow = function (arg) {
var self = this;
var i;
self.removeItemsFlag = false;
if (typeof arg === "undefined") {
self.polledReadBlockList = [];
} else if (typeof arg === "string") {
for (i = 0; i < self.polledReadBlockList.length; i++) {
outputLog('TCBA ' + self.translationCB(arg), "TRACE");
if (self.polledReadBlockList[i].addr === self.translationCB(arg)) {
outputLog('Splicing', "TRACE");
self.polledReadBlockList.splice(i, 1);
}
}
} else if (Array.isArray(arg)) {
for (i = 0; i < self.polledReadBlockList.length; i++) {
for (j = 0; j < arg.length; j++) {
if (self.polledReadBlockList[i].addr === self.translationCB(arg[j])) {
self.polledReadBlockList.splice(i, 1);
}
}
}
}
self.readPacketValid = false;
// prepareReadPacket();
}
MCProtocol.prototype.readAllItems = function (arg) {
var self = this;
var i;
outputLog("Reading All Items (readAllItems was called)", "TRACE", self.connectionID);
if (typeof arg === "function") {
self.readDoneCallback = arg;
} else {
self.readDoneCallback = doNothing;
}
if (self.connectionState !== 4) {
outputLog("Unable to read when not connected. Return bad values.", "WARN", self.connectionID);
} // For better behaviour when auto-reconnecting - don't return now
// Check if ALL are done... You might think we could look at parallel jobs, and for the most part we can, but if one just finished and we end up here before starting another, it's bad.
if (self.isWaiting()) {
outputLog("Waiting to read for all R/W operations to complete. Will re-trigger readAllItems in 100ms.", "INFO");
setTimeout(function () {
self.readAllItems.apply(self, arguments);
}, 100, arg);
return;
}
// Now we check the array of adding and removing things. Only now is it really safe to do this.
self.addRemoveArray.forEach(function (element) {
outputLog('Adding or Removing ' + util.format(element), "INFO", self.connectionID);
if (element.action === 'remove') {
self.removeItemsNow(element.arg);
}
if (element.action === 'poll' || element.action === 'read') {
self.addItemsNow(element.arg, element.action, element.cb);
}
});
self.addRemoveArray = []; // Clear for next time.
if (!self.readPacketValid) {
self.prepareReadPacket();
}
outputLog("Calling SRP from RAI", "TRACE", self.connectionID);
self.sendReadPacket(); // Note this sends the first few read packets depending on parallel connection restrictions.
}
MCProtocol.prototype.readItems = function (arg, cb) {
return _readItems(this, arg, cb, false);
}
function _readItems(self, arg, cb, queuedItem) {
//var self = this;
var i;
var reply = [];
outputLog("#readItems() was called)", "TRACE", self.connectionID);
//ensure arg is an array regardless of count
let argArr = arg;
if (Array.isArray(arg) != true) {
argArr = [arg];
}
if (self.connectionState !== 4) {
outputLog("Unable to read when not connected. Return bad values.", "WARN", self.connectionID);
//self.queue = [];//empty the queue
} // For better behaviour when auto-reconnecting - don't return now
if (self.isWaiting()) {
let sendStatus = MCProtocol.prototype.enumSendResult.unknown;
if (queuedItem) {
sendStatus = MCProtocol.prototype.enumSendResult.notSent;
outputLog(`️🛢️➡🚧 queued readItem '${arg}' still not sent (isWaiting)`, "INFO")
} else if (self.queue.length >= self.queueMaxLength) {
outputLog(`️🛢️➡🗑️ readItem '${arg}' discarded, queue full`, "WARN")
sendStatus = MCProtocol.prototype.enumSendResult.queueFull;
} else {
sendStatus = MCProtocol.prototype.enumSendResult.queued;
self.queue.push({
arg: arg,
cb: cb,
fn: "read",
dt: Date.now()
});
outputLog(`️📒➡🛢️ readItem '${arg}' pushed to queue`, "INFO")
}
reply.push({ TAG: arg, sendStatus: sendStatus });//[item.useraddr] = MCProtocol.prototype.enumSendResult.badRequest;
return reply;
}
let plcitems = [];
for (i = 0; i < argArr.length; i++) {
if (typeof argArr[i] === "string" && argArr[i] !== "_COMMERR") {
let plcitem = new PLCItem(self);
plcitem.init(self.translationCB(argArr[i]), argArr[i], self.octalInputOutput, self.frame, self.plcType, undefined /*not writing*/);
if (Array.isArray(cb))
plcitem.cb = cb[i];
else
plcitem.cb = cb;
plcitem.action = 'read';
plcitems.push(plcitem);
}
}
//do callback for non initialised (bad) items
plcitems.map(function (item) {
if (item.initialised == false) {
var cbd = new PLCReadResult(item.useraddr, item.addr, MCProtocol.prototype.enumOPCQuality.badConfigErrInServer.value, 0, undefined, undefined);
outputLog(`Failed to initialise PLC item. Addr '${item.addr}' may be invalid for this type of PLC and frame setting - item will be dropped`, "ERROR");
item.cb(true, cbd);
item.extraInfo = item.initError;
reply.problem = true;
let r = {
TAG: item.useraddr,
sendStatus: MCProtocol.prototype.enumSendResult.badRequest
};
reply.push(r);
}
});
//filter OK items
var plcitemsInitialised = plcitems.filter(function (item) {
return item.initialised;
});
//check how many good items - return if none
if (!plcitemsInitialised.length) {
outputLog("Nothing to send!", "WARN");
return reply;
}
let pp = self.prepareReadPacket(plcitemsInitialised);
outputLog("Calling sendReadPacket()", "TRACE", self.connectionID);
var sentCount = self.sendReadPacket(); // Note this sends the first few read packets depending on parallel connection restrictions.
plcitemsInitialised.map(function (item) {
let s = sentCount ? MCProtocol.prototype.enumSendResult.sent : MCProtocol.prototype.enumSendResult.notSent;
if (s != MCProtocol.prototype.enumSendResult.sent) {
reply.problem = true;
}
let r = {
TAG: item.useraddr,
sendStatus: s
};
reply.push(r);
});
return reply;
}
MCProtocol.prototype.isWaiting = function () {
var self = this;
return (self.isReading() || self.isWriting());
}
MCProtocol.prototype.isReading = function () {
return this.readPacketArray.some(function(el){
return el.sent;
});
}
MCProtocol.prototype.isWriting = function () {
return this.writePacketArray.some(function(el){
return el.sent;
});
}
MCProtocol.prototype.clearReadPacketTimeouts = function () {
var self = this;
clearPacketTimeouts(self.readPacketArray);
}
MCProtocol.prototype.clearWritePacketTimeouts = function () {
var self = this;
outputLog('Clearing write PacketTimeouts', "DEBUG", self.connectionID);
// Before we initialize the readPacketArray, we need to loop through all of them and clear timeouts.
for (i = 0; i < self.writePacketArray.length; i++) {
clearTimeout(self.writePacketArray[i].timeout);
self.writePacketArray[i].sent = false;
self.writePacketArray[i].rcvd = false;
}
}
MCProtocol.prototype.prepareWritePacket = function (itemList) {
outputLog("#################### prepareWritePacket() ####################", "TRACE");
var self = this;
var requestList = []; // The request list consists of the block list, split into chunks readable by PDU.
var requestNumber = 0, thisBlock = 0, thisRequest = 0;
var itemsThisPacket;
var numItems;
// Sort the items using the sort function, by type and offset.
itemList.sort(itemListSorter);
// Just exit if there are no items.
if (itemList.length == 0) {
return undefined;
}
self.globalWriteBlockList = [];
itemList[0].block = thisBlock;
// Just push the items into blocks and figure out the write buffers
for (i = 0; i < itemList.length; i++) {
if (itemList[i].prepareWriteData()) {
itemList[i].writeBuffer._instance = itemList[i]._instance;
self.globalWriteBlockList.push(itemList[i]); // Remember - by reference.
var bli = self.globalWriteBlockList[self.globalWriteBlockList.length-1];
bli.isOptimized = false;
bli.itemReference = [];
bli.itemReference.push(itemList[i]);
}
}
// Split the blocks into requests, if they're too large.
for (i = 0; i < self.globalWriteBlockList.length; i++) {
let block = self.globalWriteBlockList[i];
var startElement = block.offset;
var remainingLength = block.byteLengthWrite;
var remainingTotalArrayLength = block.totalArrayLength;
var maxByteRequest = block.maxWordLength() * 2;
var lengthOffset = 0;
block.partsBufferized = 0;
// How many parts?
block.parts = Math.ceil(block.byteLengthWrite / maxByteRequest);
outputLog(`globalWriteBlockList[${i}].parts == ${block.parts} for request '${block.useraddr}', .offset (device number) == ${block.offset}, maxByteRequest==${maxByteRequest}`, "DEBUG");
block.requestReference = [];
// If we need to spread the sending/receiving over multiple packets...
for (j = 0; j < block.parts; j++) {
// create a request for a globalWriteBlockList.
requestList[thisRequest] = block.clone();
let reqItem = requestList[thisRequest];
reqItem._instance = "block clone (request item)";
reqItem.part = j+1;
//reqItem.updateSeqNum(self.nextSequenceNumber());
reqItem.offset = startElement;