-
Notifications
You must be signed in to change notification settings - Fork 40
/
mcprotocol.js
2572 lines (2275 loc) · 92.3 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 _ = require("underscore");
var util = require("util");
var effectiveDebugLevel = 0; // intentionally global, shared between connections
var monitoringTime = 10;
module.exports = MCProtocol;
function MCProtocol(){
var self = this;
self.readReq = new Buffer(1500);
self.writeReq = new Buffer(1500);
self.resetPending = false;
self.resetTimeout = undefined;
self.maxPDU = 255;
self.isoclient = undefined;
self.isoConnectionState = 0;
self.requestMaxParallel = 1;
self.maxParallel = 1; // MC protocol is read/response. Parallel jobs not supported.
self.isAscii = 1;
self.frame = '1E';
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.readPacketArray = [];
self.writePacketArray = [];
self.polledReadBlockList = [];
self.instantWriteBlockList = [];
self.globalReadBlockList = [];
self.globalWriteBlockList = [];
self.masterSequenceNumber = 1;
self.translationCB = doNothing;
self.connectionParams = undefined;
self.connectionID = 'UNDEF';
self.addRemoveArray = [];
self.readPacketValid = false;
self.writeInQueue = false;
self.connectCBIssued = false;
}
MCProtocol.prototype.setTranslationCB = function(cb) {
var self = this;
if (typeof cb === "function") {
outputLog('Translation OK');
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:');
outputLog(cParam);
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 (cParam.debug) {
effectiveDebugLevel = 99;
}
if (typeof(cParam.frame) === 'undefined') {
self.frame = '1E';
} else {
self.frame = cParam.frame;
}
if (typeof(cParam.octalInputOutput) === 'undefined') {
self.octalInputOutput = true;
} else {
self.octalInputOutput = cParam.octalInputOutput;
}
self.connectionParams = cParam;
self.connectCallback = callback;
self.connectCBIssued = false;
self.connectNow(self.connectionParams, false);
}
MCProtocol.prototype.dropConnection = function () {
var self = this;
if (typeof(self.isoclient) !== 'undefined') {
self.isoclient.end();
}
self.connectionCleanup(); // TODO - check this.
}
MCProtocol.prototype.connectNow = function(cParam, suppressCallback) { // TODO - implement or remove suppressCallback
var self = this;
// Don't re-trigger.
if (self.isoConnectionState >= 1) { return; }
self.connectionCleanup();
self.isoclient = net.connect(cParam, function(){
self.onTCPConnect.apply(self,arguments);
});
self.isoclient.setKeepAlive(true,2500); // For reliable unplug detection in most cases - although it takes 10 minutes to notify
self.isoConnectionState = 1; // 1 = trying to connect
self.isoclient.on('error', function(){
self.connectError.apply(self, arguments);
});
outputLog('<initiating a new connection>',1,self.connectionID);
outputLog('Attempting to connect to host...',0,self.connectionID);
}
MCProtocol.prototype.connectError = function(e) {
var self = this;
// 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,0,self.connectionID);
if ((!self.connectCBIssued) && (typeof(self.connectCallback) === "function")) {
self.connectCBIssued = true;
self.connectCallback(e);
}
self.isoConnectionState = 0;
}
MCProtocol.prototype.readWriteError = function(e) {
var self = this;
outputLog('We Caught a read/write error ' + e.code + ' - resetting connection',0,self.connectionID);
self.isoConnectionState = 0;
self.connectionReset();
}
MCProtocol.prototype.packetTimeout = function(packetType, packetSeqNum) {
var self = this;
outputLog('PacketTimeout called with type ' + packetType + ' and seq ' + packetSeqNum,1,self.connectionID);
if (packetType === "read") {
outputLog("READ TIMEOUT on sequence number " + packetSeqNum,0,self.connectionID);
self.readResponse(undefined); //, self.findReadIndexOfSeqNum(packetSeqNum));
return undefined;
}
if (packetType === "write") {
outputLog("WRITE TIMEOUT on sequence number " + packetSeqNum,0,self.connectionID);
self.writeResponse(undefined); //, self.findWriteIndexOfSeqNum(packetSeqNum));
return undefined;
}
outputLog("Unknown timeout error. Nothing was done - this shouldn't happen.",0,self.connectionID);
}
MCProtocol.prototype.onTCPConnect = function() {
var self = this;
outputLog('TCP Connection Established to ' + self.isoclient.remoteAddress + ' on port ' + self.isoclient.remotePort,0,self.connectionID);
// Track the connection state
self.isoConnectionState = 4; // 4 = all connected, simple with MC protocol. Other protocols have a negotiation/session packet as well.
self.isoclient.removeAllListeners('data');
self.isoclient.removeAllListeners('error');
self.isoclient.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.isoclient.on('error', function() {
self.readWriteError.apply(self, arguments);
}); // Might want to remove the connecterror listener
if ((!self.connectCBIssued) && (typeof(self.connectCallback) === "function")) {
self.connectCBIssued = true;
self.connectCallback();
}
return;
}
MCProtocol.prototype.writeItems = function(arg, value, cb) {
var self = this;
var i;
outputLog("Preparing to WRITE " + arg,0,self.connectionID);
if (self.isWriting()) {
outputLog("You must wait until all previous writes have finished before scheduling another. ",0,self.connectionID);
return;
}
if (typeof cb === "function") {
self.writeDoneCallback = cb;
} else {
self.writeDoneCallback = doNothing;
}
self.instantWriteBlockList = []; // Initialize the array.
if (typeof arg === "string") {
self.instantWriteBlockList.push(stringToMCAddr(self.translationCB(arg), arg, self.octalInputOutput));
if (typeof(self.instantWriteBlockList[self.instantWriteBlockList.length - 1]) !== "undefined") {
self.instantWriteBlockList[self.instantWriteBlockList.length - 1].writeValue = value;
}
} else if (_.isArray(arg) && _.isArray(value) && (arg.length == value.length)) {
for (i = 0; i < arg.length; i++) {
if (typeof arg[i] === "string") {
self.instantWriteBlockList.push(stringToMCAddr(self.translationCB(arg[i]), arg[i], self.octalInputOutput));
if (typeof(self.instantWriteBlockList[self.instantWriteBlockList.length - 1]) !== "undefined") {
self.instantWriteBlockList[self.instantWriteBlockList.length - 1].writeValue = value[i];
}
}
}
}
// Validity check.
for (i=self.instantWriteBlockList.length-1;i>=0;i--) {
if (self.instantWriteBlockList[i] === undefined) {
self.instantWriteBlockList.splice(i,1);
outputLog("Dropping an undefined write item.");
}
}
self.prepareWritePacket();
if (!self.isReading()) {
self.sendWritePacket();
} else {
self.writeInQueue = true;
}
}
MCProtocol.prototype.findItem = function(useraddr) {
var self = this;
var i;
var commstate = { value: self.isoConnectionState !== 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) {
var self = this;
self.addRemoveArray.push({arg: arg, action: 'add'});
}
MCProtocol.prototype.addItemsNow = function(arg) {
var self = this;
var i;
outputLog("Adding " + arg,0,self.connectionID);
addItemsFlag = false;
if (typeof arg === "string" && arg !== "_COMMERR") {
self.polledReadBlockList.push(stringToMCAddr(self.translationCB(arg), arg, self.octalInputOutput));
} else if (_.isArray(arg)) {
for (i = 0; i < arg.length; i++) {
if (typeof arg[i] === "string" && arg[i] !== "_COMMERR") {
self.polledReadBlockList.push(stringToMCAddr(self.translationCB(arg[i]), arg[i], self.octalInputOutput));
}
}
}
// 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.");
}
}
// 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));
if (self.polledReadBlockList[i].addr === self.translationCB(arg)) {
outputLog('Splicing');
self.polledReadBlockList.splice(i, 1);
}
}
} else if (_.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)",1,self.connectionID);
if (typeof arg === "function") {
self.readDoneCallback = arg;
} else {
self.readDoneCallback = doNothing;
}
if (self.isoConnectionState !== 4) {
outputLog("Unable to read when not connected. Return bad values.",0,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.");
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), 1, self.connectionID);
if (element.action === 'remove') {
self.removeItemsNow(element.arg);
}
if (element.action === 'add') {
self.addItemsNow(element.arg);
}
});
self.addRemoveArray = []; // Clear for next time.
if (!self.readPacketValid) { self.prepareReadPacket(); }
// ideally... incrementSequenceNumbers();
outputLog("Calling SRP from RAI",1,self.connectionID);
self.sendReadPacket(); // Note this sends the first few read packets depending on parallel connection restrictions.
}
MCProtocol.prototype.isWaiting = function() {
var self = this;
return (self.isReading() || self.isWriting());
}
MCProtocol.prototype.isReading = function() {
var self = this;
var i;
// Walk through the array and if any packets are marked as sent, it means we haven't received our final confirmation.
for (i=0; i<self.readPacketArray.length; i++) {
if (self.readPacketArray[i].sent === true) { return true };
}
return false;
}
MCProtocol.prototype.isWriting = function() {
var self = this;
var i;
// Walk through the array and if any packets are marked as sent, it means we haven't received our final confirmation.
for (i=0; i<self.writePacketArray.length; i++) {
if (self.writePacketArray[i].sent === true) { return true };
}
return false;
}
MCProtocol.prototype.clearReadPacketTimeouts = function() {
var self = this;
outputLog('Clearing read PacketTimeouts',1,self.connectionID);
// Before we initialize the readPacketArray, we need to loop through all of them and clear timeouts.
for (i=0;i<self.readPacketArray.length;i++) {
clearTimeout(self.readPacketArray[i].timeout);
self.readPacketArray[i].sent = false;
self.readPacketArray[i].rcvd = false;
}
}
MCProtocol.prototype.clearWritePacketTimeouts = function() {
var self = this;
outputLog('Clearing write PacketTimeouts',1,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() {
var self = this;
var itemList = self.instantWriteBlockList;
var requestList = []; // The request list consists of the block list, split into chunks readable by PDU.
var requestNumber = 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;
}
// At this time we do not do write optimizations.
// The reason for this is it is would cause numerous issues depending how the code was written in the PLC.
// If we write B3:0/0 and B3:0/1 then to optimize we would have to write all of B3:0, which also writes /2, /3...
//
// I suppose when working with integers, we could write these as one block.
// But if you really, really want the program to do that, write the integer yourself.
self.globalWriteBlockList[0] = itemList[0];
self.globalWriteBlockList[0].itemReference = [];
self.globalWriteBlockList[0].itemReference.push(itemList[0]);
var thisBlock = 0;
var thisRequest = 0;
itemList[0].block = thisBlock;
// Just push the items into blocks and figure out the write buffers
for (i=0;i<itemList.length;i++) {
self.globalWriteBlockList[i] = itemList[i]; // Remember - by reference.
self.globalWriteBlockList[i].isOptimized = false;
self.globalWriteBlockList[i].itemReference = [];
self.globalWriteBlockList[i].itemReference.push(itemList[i]);
bufferizeMCItem(itemList[i],self.isAscii);
}
// Split the blocks into requests, if they're too large.
for (i=0;i<self.globalWriteBlockList.length;i++) {
var startElement = self.globalWriteBlockList[i].offset;
var remainingLength = self.globalWriteBlockList[i].byteLengthWrite;
var remainingTotalArrayLength = self.globalWriteBlockList[i].totalArrayLength;
// With the MC protocol, maxByteRequest is variable.
// We also use maxByteRequest to enforce a boundary on reading counter values that we can't cross.
var maxByteRequest = self.globalWriteBlockList[i].maxWordLength(true)*2; // Will be 10*2 = 20 for bit native. (160 point max)
var lengthOffset = 0;
// Always create a request for a globalWriteBlockList.
requestList[thisRequest] = self.globalWriteBlockList[i].clone();
// How many parts?
self.globalWriteBlockList[i].parts = Math.ceil(self.globalWriteBlockList[i].byteLengthWrite/maxByteRequest);
outputLog("globalWriteBlockList " + i + " parts is " + self.globalWriteBlockList[i].parts + " offset is " + self.globalWriteBlockList[i].offset + " MBR is " + maxByteRequest,2);
self.globalWriteBlockList[i].requestReference = [];
// If we need to spread the sending/receiving over multiple packets...
for (j=0;j<self.globalWriteBlockList[i].parts;j++) {
requestList[thisRequest] = self.globalWriteBlockList[i].clone();
self.globalWriteBlockList[i].requestReference.push(requestList[thisRequest]);
requestList[thisRequest].offset = startElement;
requestList[thisRequest].byteLengthWrite = Math.min(maxByteRequest,remainingLength);
if(requestList[thisRequest].bitNative) {
requestList[thisRequest].totalArrayLength = Math.min(maxByteRequest*2,remainingTotalArrayLength,self.globalWriteBlockList[i].totalArrayLength);
} else {
// I think we should be dividing by dtypelen here
requestList[thisRequest].totalArrayLength = Math.min(maxByteRequest/self.globalWriteBlockList[i].dtypelen,remainingLength/self.globalWriteBlockList[i].dtypelen,self.globalWriteBlockList[i].totalArrayLength);
}
remainingTotalArrayLength -= requestList[thisRequest].totalArrayLength;
requestList[thisRequest].byteLengthWithFill = requestList[thisRequest].byteLengthWrite;
requestList[thisRequest].writeBuffer = self.globalWriteBlockList[i].writeBuffer.slice(lengthOffset, lengthOffset + requestList[thisRequest].byteLengthWithFill);
requestList[thisRequest].writeQualityBuffer = self.globalWriteBlockList[i].writeQualityBuffer.slice(lengthOffset, lengthOffset + requestList[thisRequest].byteLengthWithFill);
lengthOffset += self.globalWriteBlockList[i].requestReference[j].byteLengthWrite;
if (self.globalWriteBlockList[i].parts > 1) {
requestList[thisRequest].datatype = 'BYTE';
requestList[thisRequest].dtypelen = 1;
if (requestList[thisRequest].bitNative) {
requestList[thisRequest].arrayLength = requestList[thisRequest].totalArrayLength;//globalReadBlockList[thisBlock].byteLength;
} else {
requestList[thisRequest].arrayLength = requestList[thisRequest].byteLengthWrite/2;//globalReadBlockList[thisBlock].byteLength;
}
}
remainingLength -= maxByteRequest;
if (self.globalWriteBlockList[i].bitNative) {
startElement += maxByteRequest*2;
} else {
startElement += maxByteRequest/2;
}
thisRequest++;
}
}
self.clearWritePacketTimeouts();
self.writePacketArray = [];
// Before we initialize the writePacketArray, we need to loop through all of them and clear timeouts.
// The packetizer...
while (requestNumber < requestList.length) {
// Set up the read packet
// Yes this is the same master sequence number shared with the read queue
self.masterSequenceNumber += 1;
if (self.masterSequenceNumber > 32767) {
self.masterSequenceNumber = 1;
}
numItems = 0;
// Packet's length
var packetWriteLength = 10 + 4; // 10 byte header and 4 byte param header
self.writePacketArray.push(new PLCPacket());
var thisPacketNumber = self.writePacketArray.length - 1;
self.writePacketArray[thisPacketNumber].seqNum = self.masterSequenceNumber;
self.writePacketArray[thisPacketNumber].itemList = []; // Initialize as array.
for (var i = requestNumber; i < requestList.length; i++) {
if (numItems == 1) {
break; // Used to break when packet was full. Now break when we can't fit this packet in here.
}
requestNumber++;
numItems++;
packetWriteLength += (requestList[i].byteLengthWithFill + 4);
self.writePacketArray[thisPacketNumber].itemList.push(requestList[i]);
}
}
outputLog("WPAL is " + self.writePacketArray.length, 1);
}
MCProtocol.prototype.prepareReadPacket = function() {
var self = this;
var itemList = self.polledReadBlockList; // The items are the actual items requested by the user
var requestList = []; // The request list consists of the block list, split into chunks readable by PDU.
var startOfSlice, endOfSlice, oldEndCoil, demandEndCoil;
// Validity check.
for (i=itemList.length-1;i>=0;i--) {
if (itemList[i] === undefined) {
itemList.splice(i,1);
outputLog("Dropping an undefined request item.",0,self.connectionID);
}
}
// 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.globalReadBlockList = [];
// ...because you have to start your optimization somewhere.
self.globalReadBlockList[0] = itemList[0];
self.globalReadBlockList[0].itemReference = [];
self.globalReadBlockList[0].itemReference.push(itemList[0]);
var maxByteRequest, thisBlock = 0;
itemList[0].block = thisBlock;
// variable for MC var maxByteRequest = 128;
// Optimize the items into blocks
for (i=1;i<itemList.length;i++) {
// Skip T, C, P types
maxByteRequest = itemList[i].maxWordLength(true)*2; // Will be 10*2 = 20 for bit native. (160 point max)
if ((itemList[i].areaMCCode !== self.globalReadBlockList[thisBlock].areaMCCode) || // Can't optimize between areas
(!self.isOptimizableArea(itemList[i].areaMCCode)) || // May as well try to optimize everything.
((itemList[i].offset - self.globalReadBlockList[thisBlock].offset + itemList[i].byteLength) > maxByteRequest) || // If this request puts us over our max byte length, create a new block for consistency reasons.
((itemList[i].offset - (self.globalReadBlockList[thisBlock].offset + self.globalReadBlockList[thisBlock].byteLength) > self.maxGap) && !itemList[i].bitNative) ||
((itemList[i].offset - (self.globalReadBlockList[thisBlock].offset + self.globalReadBlockList[thisBlock].byteLength) > self.maxGap*8) && itemList[i].bitNative)) { // If our gap is large, create a new block.
// At this point we give up and create a new block.
thisBlock = thisBlock + 1;
self.globalReadBlockList[thisBlock] = itemList[i]; // By reference.
// itemList[i].block = thisBlock; // Don't need to do this.
self.globalReadBlockList[thisBlock].isOptimized = false;
self.globalReadBlockList[thisBlock].itemReference = [];
self.globalReadBlockList[thisBlock].itemReference.push(itemList[i]);
// outputLog("Not optimizing.");
} else {
outputLog("Performing optimization of item " + itemList[i].addr + " with " + self.globalReadBlockList[thisBlock].addr,1);
// This next line checks the maximum.
// Think of this situation - we have a large request of 40 bytes starting at byte 10.
// Then someone else wants one byte starting at byte 12. The block length doesn't change.
//
// But if we had 40 bytes starting at byte 10 (which gives us byte 10-49) and we want byte 50, our byte length is 50-10 + 1 = 41.
if (itemList[i].bitNative) { // Coils and inputs must be special-cased
self.globalReadBlockList[thisBlock].byteLength =
Math.max(
self.globalReadBlockList[thisBlock].byteLength,
(Math.floor((itemList[i].requestOffset - self.globalReadBlockList[thisBlock].requestOffset)/8) + itemList[i].byteLength)
);
if (self.globalReadBlockList[thisBlock].byteLength % 2) { // shouldn't be necessary
self.globalReadBlockList[thisBlock].byteLength += 1;
}
} else {
self.globalReadBlockList[thisBlock].byteLength =
Math.max(
self.globalReadBlockList[thisBlock].byteLength,
((itemList[i].offset - self.globalReadBlockList[thisBlock].offset)*2 + Math.ceil(itemList[i].byteLength/itemList[i].multidtypelen))*itemList[i].multidtypelen
);
}
outputLog("Optimized byte length is now " + self.globalReadBlockList[thisBlock].byteLength,1);
// Point the buffers (byte and quality) to a sliced version of the optimized block. This is by reference (same area of memory)
if (itemList[i].bitNative) { // Again a special case.
startOfSlice = (itemList[i].requestOffset - self.globalReadBlockList[thisBlock].requestOffset)/8; // NO, NO, NO - not the dtype length - start of slice varies with register width. itemList[i].multidtypelen;
} else {
startOfSlice = (itemList[i].requestOffset - self.globalReadBlockList[thisBlock].requestOffset)*2; // NO, NO, NO - not the dtype length - start of slice varies with register width. itemList[i].multidtypelen;
}
endOfSlice = startOfSlice + itemList[i].byteLength;
itemList[i].byteBuffer = self.globalReadBlockList[thisBlock].byteBuffer.slice(startOfSlice, endOfSlice);
itemList[i].qualityBuffer = self.globalReadBlockList[thisBlock].qualityBuffer.slice(startOfSlice, endOfSlice);
// For now, change the request type here, and fill in some other things.
// I am not sure we want to do these next two steps.
// It seems like things get screwed up when we do this.
// Since globalReadBlockList[thisBlock] exists already at this point, and our buffer is already set, let's not do this now.
// globalReadBlockList[thisBlock].datatype = 'BYTE';
// globalReadBlockList[thisBlock].dtypelen = 1;
self.globalReadBlockList[thisBlock].isOptimized = true;
self.globalReadBlockList[thisBlock].itemReference.push(itemList[i]);
}
}
var thisRequest = 0;
// Split the blocks into requests, if they're too large.
for (i=0;i<self.globalReadBlockList.length;i++) {
// Always create a request for a globalReadBlockList.
requestList[thisRequest] = self.globalReadBlockList[i].clone();
// How many parts?
maxByteRequest = self.globalReadBlockList[i].maxWordLength(true)*2; // Will be 10*2 = 20 for bit native. (160 point max)
self.globalReadBlockList[i].parts = Math.ceil(self.globalReadBlockList[i].byteLength/maxByteRequest);
var startElement = self.globalReadBlockList[i].requestOffset; // try to ignore the offset
var remainingLength = self.globalReadBlockList[i].byteLength;
var remainingTotalArrayLength = self.globalReadBlockList[i].totalArrayLength;
self.globalReadBlockList[i].requestReference = [];
// If we need to spread the sending/receiving over multiple packets...
for (j=0;j<self.globalReadBlockList[i].parts;j++) {
requestList[thisRequest] = self.globalReadBlockList[i].clone();
self.globalReadBlockList[i].requestReference.push(requestList[thisRequest]);
requestList[thisRequest].requestOffset = startElement;
requestList[thisRequest].byteLength = Math.min(maxByteRequest,remainingLength);
if (requestList[thisRequest].bitNative) {
requestList[thisRequest].totalArrayLength = Math.min(maxByteRequest*8,remainingLength*8,self.globalReadBlockList[i].totalArrayLength);
} else {
requestList[thisRequest].totalArrayLength = Math.min(maxByteRequest/self.globalReadBlockList[i].dtypelen,remainingLength/self.globalReadBlockList[i].dtypelen,self.globalReadBlockList[i].totalArrayLength);
}
requestList[thisRequest].byteLengthWithFill = requestList[thisRequest].byteLength;
if (requestList[thisRequest].byteLengthWithFill % 2) { requestList[thisRequest].byteLengthWithFill += 1; };
// Just for now... I am not sure if we really want to do this in this case.
if (self.globalReadBlockList[i].parts > 1) {
requestList[thisRequest].datatype = 'BYTE';
requestList[thisRequest].dtypelen = 1;
if (requestList[thisRequest].bitNative) {
requestList[thisRequest].arrayLength = requestList[thisRequest].totalArrayLength;//globalReadBlockList[thisBlock].byteLength;
} else {
requestList[thisRequest].arrayLength = requestList[thisRequest].byteLength/2;//globalReadBlockList[thisBlock].byteLength;
}
}
remainingLength -= maxByteRequest;
if (self.globalReadBlockList[i].bitNative) {
// startElement += maxByteRequest/requestList[thisRequest].multidtypelen;
startElement += maxByteRequest*8;
} else {
startElement += maxByteRequest/2;
}
thisRequest++;
}
}
// The packetizer...
var requestNumber = 0;
var itemsThisPacket;
self.clearReadPacketTimeouts();
self.readPacketArray = [];
while (requestNumber < requestList.length) {
// Set up the read packet
self.masterSequenceNumber += 1;
if (self.masterSequenceNumber > 32767) {
self.masterSequenceNumber = 1;
}
var numItems = 0;
self.readPacketArray.push(new PLCPacket());
var thisPacketNumber = self.readPacketArray.length - 1;
self.readPacketArray[thisPacketNumber].seqNum = self.masterSequenceNumber;
self.readPacketArray[thisPacketNumber].itemList = []; // Initialize as array.
for (var i = requestNumber; i < requestList.length; i++) {
if (numItems >= 1) {
break; // We can't fit this packet in here. For now, this is always the case as we only have one item in MC protocol.
}
requestNumber++;
numItems++;
self.readPacketArray[thisPacketNumber].itemList.push(requestList[i]);
}
}
self.readPacketValid = true;
}
MCProtocol.prototype.sendReadPacket = function() {
var self = this;
var i, j, curLength, returnedBfr, routerLength;
var flagReconnect = false;
outputLog("SendReadPacket called",1,self.connectionID);
for (i = 0;i < self.readPacketArray.length; i++) {
if (self.readPacketArray[i].sent) { continue; }
if (self.parallelJobsNow >= self.maxParallel) { continue; }
// From here down is SENDING the packet
self.readPacketArray[i].reqTime = process.hrtime();
curLength = 0;
routerLength = 0;
// We always need an MC subheader BUT we are now going to do this in
//self.readWordHeader.copy(self.readReq, curLength);
//curLength = self.readWordHeader.length;
// The FOR loop is left in here for now, but really we are only doing one request per packet for now.
for (j = 0; j < self.readPacketArray[i].itemList.length; j++) {
if (self.frame == '3E') {
returnedBfr = MCAddrToBuffer3E(self.readPacketArray[i].itemList[j],false /* not writing */,self.isAscii);
} else {
returnedBfr = MCAddrToBuffer1E(self.readPacketArray[i].itemList[j],false /* not writing */,self.isAscii);
}
outputLog('The Returned MC Buffer is:',2);
outputLog(returnedBfr, 2);
outputLog("The returned buffer length is " + returnedBfr.length, 2);
returnedBfr.copy(self.readReq, curLength);
curLength += returnedBfr.length;
}
outputLog("The final send buffer is:", 2);
if (!self.isAscii) {
outputLog(self.readReq.slice(0,curLength), 2);
}
if (self.isoConnectionState == 4) {
self.readPacketArray[i].timeout = setTimeout(function(){
self.packetTimeout.apply(self,arguments);
}, self.globalTimeout, "read", self.readPacketArray[i].seqNum);
if (self.isAscii) {
var writeBuf = asciize(self.readReq.slice(0,curLength));
if (self.frame == '3E') {
writeBuf[30] = self.readPacketArray[i].itemList[0].areaSLMPCodeAscii.charCodeAt(0);
writeBuf[31] = self.readPacketArray[i].itemList[0].areaSLMPCodeAscii.charCodeAt(1);
}
self.isoclient.write(writeBuf);
outputLog(writeBuf, 2);
} else {
self.isoclient.write(self.readReq.slice(0,curLength)); // was 31
}
self.readPacketArray[i].sent = true;
self.readPacketArray[i].rcvd = false;
self.readPacketArray[i].timeoutError = false;
self.parallelJobsNow += 1;
outputLog('Sending Read Packet SEQ ' + self.readPacketArray[i].seqNum,1);
} else {
// outputLog('Somehow got into read block without proper isoConnectionState of 4. Disconnect.');
// connectionReset();
// setTimeout(connectNow, 2000, connectionParams);
// Note we aren't incrementing maxParallel so we are actually going to time out on all our packets all at once.
self.readPacketArray[i].sent = true;
self.readPacketArray[i].rcvd = false;
self.readPacketArray[i].timeoutError = true;
if (!flagReconnect) {
// Prevent duplicates
outputLog('Not Sending Read Packet because we are not connected - ISO CS is ' + self.isoConnectionState,0,self.connectionID);
}
// This is essentially an instantTimeout.
if (self.isoConnectionState == 0) {
flagReconnect = true;
}
outputLog('Requesting PacketTimeout Due to ISO CS NOT 4 - READ SN ' + self.readPacketArray[i].seqNum,1,self.connectionID);
self.readPacketArray[i].timeout = setTimeout(function() {
self.packetTimeout.apply(self, arguments);
}, 0, "read", self.readPacketArray[i].seqNum);
}
}
if (flagReconnect) {
setTimeout(function() {
outputLog("The scheduled reconnect from sendReadPacket is happening now",1,self.connectionID);
self.connectNow(self.connectionParams); // We used to do this NOW - not NextTick() as we need to mark isoConnectionState as 1 right now. Otherwise we queue up LOTS of connects and crash.
}, 0);
}
}
MCProtocol.prototype.sendWritePacket = function() {
var self = this;
var dataBuffer, itemDataBuffer, dataBufferPointer, curLength, returnedBfr, flagReconnect = false;
dataBuffer = new Buffer(8192);
self.writeInQueue = false;
for (i=0;i<self.writePacketArray.length;i++) {
if (self.writePacketArray[i].sent) { continue; }
if (self.parallelJobsNow >= self.maxParallel) { continue; }
// From here down is SENDING the packet
self.writePacketArray[i].reqTime = process.hrtime();
curLength = 0;
// With MC we generate the simple header inside the packet generator as well
dataBufferPointer = 0;
for (var j = 0; j < self.writePacketArray[i].itemList.length; j++) {
if (self.frame == '3E') {
returnedBfr = MCAddrToBuffer3E(self.writePacketArray[i].itemList[j], true /* writing */,self.isAscii);
} else {
returnedBfr = MCAddrToBuffer1E(self.writePacketArray[i].itemList[j], true /* writing */,self.isAscii);
}
returnedBfr.copy(self.writeReq, curLength);
curLength += returnedBfr.length;
}
outputLog("The returned buffer length is " + returnedBfr.length,1);
if (self.isoConnectionState === 4) {
self.writePacketArray[i].timeout = setTimeout(function() {
self.packetTimeout.apply(self, arguments);
}, self.globalTimeout, "write", self.writePacketArray[i].seqNum);
outputLog("Actual Send Packet:",2);
outputLog(self.writeReq.slice(0,curLength),2);
if (self.isAscii) {
var writeBuf = asciize(self.writeReq.slice(0,curLength));
if (self.frame == '3E') {
writeBuf[30] = self.writePacketArray[i].itemList[0].areaSLMPCodeAscii.charCodeAt(0);
writeBuf[31] = self.writePacketArray[i].itemList[0].areaSLMPCodeAscii.charCodeAt(1);
}
self.isoclient.write(writeBuf); // was 31
} else {
self.isoclient.write(self.writeReq.slice(0,curLength)); // was 31
}
self.writePacketArray[i].sent = true;
self.writePacketArray[i].rcvd = false;
self.writePacketArray[i].timeoutError = false;
self.parallelJobsNow += 1;
outputLog('Sending Write Packet With Sequence Number ' + self.writePacketArray[i].seqNum,1,self.connectionID);
} else {
// This is essentially an instantTimeout.
self.writePacketArray[i].sent = true;
self.writePacketArray[i].rcvd = false;
self.writePacketArray[i].timeoutError = true;
// Without the scopePlaceholder, this doesn't work. writePacketArray[i] becomes undefined.
// The reason is that the value i is part of a closure and when seen "nextTick" has the same value
// it would have just after the FOR loop is done.
// (The FOR statement will increment it to beyond the array, then exit after the condition fails)
// scopePlaceholder works as the array is de-referenced NOW, not "nextTick".
var scopePlaceholder = self.writePacketArray[i].seqNum;
process.nextTick(function() {
self.packetTimeout("write", scopePlaceholder);
});
if (self.isoConnectionState == 0) {
flagReconnect = true;
}
}
}
if (flagReconnect) {
setTimeout(function() {
outputLog("The scheduled reconnect from sendWritePacket is happening now",1,self.connectionID);
self.connectNow(self.connectionParams); // We used to do this NOW - not NextTick() as we need to mark isoConnectionState as 1 right now. Otherwise we queue up LOTS of connects and crash.
}, 0);
}
}
MCProtocol.prototype.isOptimizableArea = function(area) {
var self = this;
// For MC protocol always say yes.
if (self.doNotOptimize) { return false; } // Are we skipping all optimization due to user request?
return true;
}
MCProtocol.prototype.onResponse = function(rawdata) {
var self = this;
var isReadResponse, isWriteResponse,data;
// Packet Validity Check.
if (!self.isAscii) {
data = rawdata;
} else {
data = binarize(rawdata);
if (typeof(data) === 'undefined') {
outputLog('Failed ASCII conversion to binary on reply. Ignoring packet.');
outputLog(data,0);
return null;
}
}
// Decrement our parallel jobs now
// NOT SO FAST - can't do this here. If we time out, then later get the reply, we can't decrement this twice. Or the CPU will not like us. Do it if not rcvd. parallelJobsNow--;
outputLog("onResponse called with length " + data.length,1);
if (data.length < 2) {
outputLog('DATA LESS THAN 2 BYTES RECEIVED. NO PROCESSING WILL OCCUR - CONNECTION RESET.');
outputLog(data,0);
self.connectionReset();
return null;
}
if (data.length < 11 && self.frame == '3E') {
outputLog('DATA LESS THAN 11 BYTES RECEIVED FOR 3E FRAME. NO PROCESSING WILL OCCUR - CONNECTION RESET.');
outputLog(data,0);
self.connectionReset();
return null;
}
outputLog('Valid MC Response Received (not yet checked for error)', 1);
// Log the receive
outputLog('Received ' + data.length + ' bytes of data from PLC.', 1);
outputLog(data, 2);
// Check the sequence number
// On a lot of other industrial protocols the sequence number is coded as part of the
// packet and read in the response which is used as a check.
// On the MC protocol, we can't do that - so we need to either give up on tracking sequence
// numbers (this is what we've done) or fake sequence numbers (adds code complexity for no perceived benefit)
if (self.isReading()) {
isReadResponse = true;
outputLog("Received Read Response",1);
self.readResponse(data);
}
if (self.isWriting()) {
isWriteResponse = true;
outputLog("Received Write Response",1);
self.writeResponse(data);
}
if ((!isReadResponse) && (!isWriteResponse)) {
outputLog("Packet arrived wasn't a write or read reply - dropping");
outputLog(data,0);
// I guess this isn't a showstopper, just ignore it. In situations like this we used to reset.