UNPKG

mbtcpprotocol

Version:

Routine to communicate with Modbus-TCP including symbol lookup, etc, for PLCs

1,215 lines (1,033 loc) 88.9 kB
// NodeMBTCP - MBTCPPROTOCOL - A library for communication using Modbus/TCP from node.js. var net = require("net"); var _ = require("underscore"); var util = require("util"); var crc16 = require("./crc16"); var effectiveDebugLevel = 1; // intentionally global, shared between connections module.exports = NodeMBTCP; function NodeMBTCP(){ var self = this; // This header is used to assemble a read packet. self.Header = new Buffer([0xff,0xff,0x00,0x00,0x00,0x00]);// followed by function and then data. 0,1 = trans ID, 2,3 = always 0, 4,5 = length, 6 = unit ID, 7=function, 8+=data self.readReq = new Buffer(1500); self.writeReq = new Buffer(1500); self.resetPending = false; self.resetTimeout = undefined; self.sendpdu = false; self.maxPDU = 255; self.isoclient = undefined; self.isoConnectionState = 0; self.requestMaxParallel = 1; self.maxParallel = 1; 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; self.dropConnectionCallback = null; self.dropConnectionTimer = null; // EIP specific self.sessionHandle = 0; // Define as zero for when we write packets prior to connection } NodeMBTCP.prototype.setTranslationCB = function(cb) { var self = this; if (typeof cb === "function") { outputLog('Translation OK'); self.translationCB = cb; } } NodeMBTCP.prototype.initiateConnection = function (cParam, callback) { var self = this; if (cParam === undefined) { cParam = {port: 502, host: '192.168.8.106', RTU: 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; } self.connectionParams = cParam; self.connectCallback = callback; self.connectCBIssued = false; self.connectNow(self.connectionParams, false); } NodeMBTCP.prototype.dropConnection = function (callback) { var self = this; if (typeof(self.isoclient) !== 'undefined') { // store the callback and request and end to the connection self.dropConnectionCallback = callback; self.isoclient.end(); // now wait for 'on close' event to trigger connection cleanup // but also start a timer to destroy the connection in case we do not receive the close self.dropConnectionTimer = setTimeout(function() { if (self.dropConnectionCallback) { // destroy the socket connection self.isoclient.destroy(); // clean up the connection now the socket has closed self.connectionCleanup(); // initate the callback self.dropConnectionCallback(); // prevent any possiblity of the callback being called twice self.dropConnectionCallback = null; } }, 2500); } else { // if client not active, then callback immediately callback(); } } NodeMBTCP.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.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); } NodeMBTCP.prototype.connectError = function(e) { var self = this; // Note that a TCP connection timeout error will appear here. An ISO 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; } NodeMBTCP.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(); } NodeMBTCP.prototype.packetTimeout = function(packetType, packetSeqNum) { var self = this; outputLog('PacketTimeout called with type ' + packetType + ' and seq ' + packetSeqNum,1,self.connectionID); /* if (packetType === "connect") { outputLog("TIMED OUT waiting for EIP Connection Response from the PLC - Disconnecting",0,self.connectionID); outputLog("Wait for 2 seconds then try again.",0,self.connectionID); self.connectionReset(); outputLog("Scheduling a reconnect from packetTimeout, connect type",0,self.connectionID); setTimeout(function(){ outputLog("The scheduled reconnect from packetTimeout, connect type, is happening now",0,self.connectionID); self.connectNow.apply(self,arguments); }, 2000, connectionParams); return undefined; } */ 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); } NodeMBTCP.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 Modbus 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 // Hook up the event that fires on disconnect self.isoclient.on('end', function() { self.onClientDisconnect.apply(self, arguments); }); // listen for close (caused by us sending an end) self.isoclient.on('close', function() { self.onClientClose.apply(self, arguments); }); if ((!self.connectCBIssued) && (typeof(self.connectCallback) === "function")) { self.connectCBIssued = true; self.connectCallback(); } return; } NodeMBTCP.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(stringToMBAddr(self.translationCB(arg), arg)); 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(stringToMBAddr(self.translationCB(arg[i]), arg[i])); 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; } } NodeMBTCP.prototype.findItem = function(useraddr) { var self = this; var i; for (i = 0; i < self.polledReadBlockList.length; i++) { if (self.polledReadBlockList[i].useraddr === useraddr) { return self.polledReadBlockList[i]; } } return undefined; } NodeMBTCP.prototype.addItems = function(arg) { var self = this; self.addRemoveArray.push({arg: arg, action: 'add'}); } NodeMBTCP.prototype.addItemsNow = function(arg) { var self = this; var i; outputLog("Adding " + arg,0,self.connectionID); addItemsFlag = false; if (typeof arg === "string") { self.polledReadBlockList.push(stringToMBAddr(self.translationCB(arg), arg)); } else if (_.isArray(arg)) { for (i = 0; i < arg.length; i++) { if (typeof arg[i] === "string") { self.polledReadBlockList.push(stringToMBAddr(self.translationCB(arg[i]), arg[i])); } } } // 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; } NodeMBTCP.prototype.removeItems = function(arg) { var self = this; self.addRemoveArray.push({arg : arg, action: 'remove'}); } NodeMBTCP.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(); } NodeMBTCP.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. } NodeMBTCP.prototype.isWaiting = function() { var self = this; return (self.isReading() || self.isWriting()); } NodeMBTCP.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; } NodeMBTCP.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; } NodeMBTCP.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; } } NodeMBTCP.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; } } NodeMBTCP.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 an array yourself and it will. self.globalWriteBlockList[0] = itemList[0]; self.globalWriteBlockList[0].itemReference = []; self.globalWriteBlockList[0].itemReference.push(itemList[0]); var thisBlock = 0; itemList[0].block = thisBlock; var maxByteRequest = 244; // 4*Math.floor((self.maxPDU - 18 - 12)/4); // Absolutely must not break a real array into two requests. Maybe we can extend by two bytes when not DINT/REAL/INT. // outputLog("Max Write Length is " + maxByteRequest); // 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]); bufferizeMBItem(itemList[i]); // outputLog("Really Here"); } // outputLog("itemList0 wb 0 is " + itemList[0].writeBuffer[0] + " gwbl is " + globalWriteBlockList[0].writeBuffer[0]); var thisRequest = 0; // 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].byteLength; var remainingTotalArrayLength = self.globalWriteBlockList[i].totalArrayLength; var lengthOffset = 0; // Always create a request for a globalReadBlockList. requestList[thisRequest] = self.globalWriteBlockList[i].clone(); // How many parts? self.globalWriteBlockList[i].parts = Math.ceil(self.globalWriteBlockList[i].byteLength/maxByteRequest); // This is still true for modbus coils // outputLog("globalWriteBlockList " + i + " parts is " + globalWriteBlockList[i].parts + " offset is " + globalWriteBlockList[i].offset + " MBR is " + maxByteRequest); 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].byteLength = Math.min(maxByteRequest,remainingLength); requestList[thisRequest].totalArrayLength = Math.min(maxByteRequest*8,remainingLength*8,self.globalWriteBlockList[i].totalArrayLength); requestList[thisRequest].byteLengthWithFill = requestList[thisRequest].byteLength; if (requestList[thisRequest].byteLengthWithFill % 2) { requestList[thisRequest].byteLengthWithFill += 1; }; // max //outputLog("LO " + lengthOffset + " rblf " + requestList[thisRequest].byteLengthWithFill + " val " + globalWriteBlockList[i].writeBuffer[0]); 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].byteLength; if (self.globalWriteBlockList[i].parts > 1) { requestList[thisRequest].datatype = 'BYTE'; requestList[thisRequest].dtypelen = 1; requestList[thisRequest].arrayLength = requestList[thisRequest].byteLength;//globalReadBlockList[thisBlock].byteLength; (This line shouldn't be needed anymore - shouldn't matter) } remainingLength -= maxByteRequest; if (self.globalWriteBlockList[i].startRegister > 20000) { // startElement += maxByteRequest/requestList[thisRequest].multidtypelen; // I believe we want to in this case divide by the "register width" which for modbus is always 2 startElement += maxByteRequest/2; // I believe we want to in this case divide by the "register width" which for modbus is always 2 for holding regs } else { startElement += maxByteRequest*8; } thisRequest++; } } self.clearWritePacketTimeouts(); self.writePacketArray = []; // outputLog("RLL is " + requestList.length); // 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; self.writePacketArray.push(new PLCPacket()); var thisPacketNumber = self.writePacketArray.length - 1; self.writePacketArray[thisPacketNumber].seqNum = self.masterSequenceNumber; // outputLog("Write Sequence Number is " + writePacketArray[thisPacketNumber].seqNum); 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++; self.writePacketArray[thisPacketNumber].itemList.push(requestList[i]); } } outputLog("WPAL is " + self.writePacketArray.length, 1); } NodeMBTCP.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 thisBlock = 0; itemList[0].block = thisBlock; var maxByteRequest = 248; // Could do 250 but that's not divisible by 4 for REAL // used to use 4*Math.floor((self.maxPDU - 18)/4); // Absolutely must not break a real array into two requests. Maybe we can extend by two bytes when not DINT/REAL/INT. // Optimize the items into blocks for (i=1;i<itemList.length;i++) { // Skip T, C, P types if ((itemList[i].areaMBCode !== self.globalReadBlockList[thisBlock].areaMBCode) || // Can't optimize between areas (!self.isOptimizableArea(itemList[i].areaMBCode)) || // 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].startRegister > 20000) || ((itemList[i].offset - (self.globalReadBlockList[thisBlock].offset + self.globalReadBlockList[thisBlock].byteLength) > self.maxGap*8) && itemList[i].startRegister < 20000)) { // 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. //worked when complicated. globalReadBlockList[thisBlock].byteLength = Math.max(globalReadBlockList[thisBlock].byteLength, ((itemList[i].offset - globalReadBlockList[thisBlock].offset) + Math.ceil(itemList[i].byteLength/itemList[i].multidtypelen))*itemList[i].multidtypelen); // console.log("THISBL", self.globalReadBlockList[thisBlock].byteLength); // console.log("THIS OFFSET", itemList[i].offset); // console.log("S.GRBL[tb].offset ", self.globalReadBlockList[thisBlock].offset); // console.log("math ceil", Math.ceil(itemList[i].byteLength/itemList[i].multidtypelen)); // console.log("mdtl", itemList[i].multidtypelen); if (itemList[i].startRegister < 20000) { // Coils and inputs must be special-cased for Modbus self.globalReadBlockList[thisBlock].byteLength = Math.max( self.globalReadBlockList[thisBlock].byteLength, (Math.floor((itemList[i].offset - self.globalReadBlockList[thisBlock].offset)/8) + itemList[i].totalArrayLength) ); } else { self.globalReadBlockList[thisBlock].byteLength = Math.max( self.globalReadBlockList[thisBlock].byteLength, ((itemList[i].offset - self.globalReadBlockList[thisBlock].offset) + Math.ceil(itemList[i].byteLength/itemList[i].multidtypelen))*itemList[i].multidtypelen // trial that did not work (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); // globalReadBlockList[thisBlock].subelement = 0; // We can't read just a timer preset, for example, // 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].startRegister < 20000) { // Again a special case. startOfSlice = Math.floor((itemList[i].offset - self.globalReadBlockList[thisBlock].offset)/8); // multidtype len is guaranteed to be 1 // For Modbus coils and input bits, we need to modify this bit offset itemList[i].bitOffset = ((itemList[i].offset - self.globalReadBlockList[thisBlock].offset) % 8); // For Modbus coils and input bits, the array length is often different than the byte length and we need to keep track of it. oldEndCoil = self.globalReadBlockList[thisBlock].offset + self.globalReadBlockList[thisBlock].totalArrayLength - 1; demandEndCoil = itemList[i].offset + itemList[i].totalArrayLength - 1; if (demandEndCoil > oldEndCoil) { self.globalReadBlockList[thisBlock].totalArrayLength += (demandEndCoil - oldEndCoil); } } else { // Do we want to multiply by multidtypelen here? startOfSlice = (itemList[i].offset - self.globalReadBlockList[thisBlock].offset)*2; // NO, NO, NO - not the dtype length - start of slice varies with register width. itemList[i].multidtypelen; } // console.log('ILI offset ' + itemList[i].offset + ' SGRBLTBO ' + self.globalReadBlockList[thisBlock].offset + 'IMDTL ' + itemList[i].multidtypelen); endOfSlice = startOfSlice + itemList[i].byteLength; // outputLog("SOS + EOS " + startOfSlice + " " + endOfSlice); 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; // outputLog("Preparing the read packet..."); // 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? self.globalReadBlockList[i].parts = Math.ceil(self.globalReadBlockList[i].byteLength/maxByteRequest); // outputLog("globalReadBlockList " + i + " parts is " + globalReadBlockList[i].parts + " offset is " + globalReadBlockList[i].offset + " MBR is " + maxByteRequest); var startElement = self.globalReadBlockList[i].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]); //outputLog(globalReadBlockList[i]); //outputLog(globalReadBlockList.slice(i,i+1)); requestList[thisRequest].offset = startElement; requestList[thisRequest].byteLength = Math.min(maxByteRequest,remainingLength); // Modbus needs the "total array length" for a number of bits. Other protocols just read extra bits - not always safe with Modbus. requestList[thisRequest].totalArrayLength = Math.min(maxByteRequest*8,remainingLength*8,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; requestList[thisRequest].arrayLength = requestList[thisRequest].byteLength;//globalReadBlockList[thisBlock].byteLength; } remainingLength -= maxByteRequest; if (self.globalReadBlockList[i].startRegister > 20000) { // startElement += maxByteRequest/requestList[thisRequest].multidtypelen; startElement += maxByteRequest/2; // I believe we want to in this case divide by the "register width" which for modbus is always 2 for holding regs } else { startElement += maxByteRequest*8; } thisRequest++; } } //requestList[5].offset = 243; // requestList = globalReadBlockList; // The packetizer... var requestNumber = 0; var itemsThisPacket; self.clearReadPacketTimeouts(); self.readPacketArray = []; // outputLog("Request list length is " + requestList.length); 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; // outputLog("Sequence Number is " + self.readPacketArray[thisPacketNumber].seqNum); 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 with Modbus. } requestNumber++; numItems++; self.readPacketArray[thisPacketNumber].itemList.push(requestList[i]); } } self.readPacketValid = true; } NodeMBTCP.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; // For TCP we always need a Modbus header with the seq number, etc. if (!self.connectionParams.RTU) { self.Header.copy(self.readReq, curLength); curLength = self.Header.length; } // Write the sequence number to the offset in the Modbus packet. Eventually this should be moved to within the FOR loop if we keep a FOR loop. if (!self.connectionParams.RTU) { self.readReq.writeUInt16BE(self.readPacketArray[i].seqNum, 0); // right at the start } else { self.lastSeqNum = i; // not really... self.readPacketArray[i].seqNum; } // 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++) { returnedBfr = MBAddrToBuffer(self.readPacketArray[i].itemList[j], false); outputLog('The Returned Modbus Buffer is:',2); outputLog(returnedBfr, 2); outputLog("The returned buffer length is " + returnedBfr.length, 2); returnedBfr.copy(self.readReq, curLength); curLength += returnedBfr.length; } // This is the overall message length for the Modbus request, minus most of the header, only for TCP if (!self.connectionParams.RTU) { self.readReq.writeUInt16BE(curLength - 6, 4); } // Add the CRC if (self.connectionParams.RTU) { self.readReq.writeUInt16LE(crc16(self.readReq.slice(0, curLength)), curLength); curLength += 2; } outputLog("The Returned buffer is:", 2); outputLog(returnedBfr, 2); if (self.isoConnectionState == 4) { self.readPacketArray[i].timeout = setTimeout(function(){ self.packetTimeout.apply(self,arguments); }, self.globalTimeout, "read", self.readPacketArray[i].seqNum); 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) { // console.log("Asking for callback next tick and my ID is " + self.connectionID); setTimeout(function() { // console.log("Next tick is here and my ID is " + self.connectionID); 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); } } NodeMBTCP.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; // For TCP we always need a Modbus header with the seq number, etc. if (!self.connectionParams.RTU) { self.Header.copy(self.readReq, curLength); curLength = self.Header.length; } // Write the sequence number to the offset in the Modbus packet. Eventually this should be moved to within the FOR loop if we keep a FOR loop. if (!self.connectionParams.RTU) { self.writeReq.writeUInt16BE(self.writePacketArray[i].seqNum, 0); } else { self.lastSeqNum = self.writePacketArray[i].seqNum; } dataBufferPointer = 0; for (var j = 0; j < self.writePacketArray[i].itemList.length; j++) { returnedBfr = MBAddrToBuffer(self.writePacketArray[i].itemList[j], true); outputLog(returnedBfr); returnedBfr.copy(self.writeReq, curLength); curLength += returnedBfr.length; } // Write the length to the header starting at the 5th byte if we're TCP if (!self.connectionParams.RTU) { self.writeReq.writeUInt16BE(curLength - 6, 4); } // Add the CRC if (self.connectionParams.RTU) { self.writeReq.writeUInt16LE(crc16(self.writeReq.slice(0, curLength)), curLength); curLength += 2; } 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); // console.log(self.writeReq.slice(0,curLength)); 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 { // outputLog('Somehow got into write block without proper isoConnectionState of 4. Disconnect.'); // connectionReset(); // setTimeout(connectNow, 2000, connectionParams); // 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) { // console.log("Asking for callback next tick and my ID is " + self.connectionID); setTimeout(function() { // console.log("Next tick is here and my ID is " + self.connectionID); 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); } } NodeMBTCP.prototype.isOptimizableArea = function(area) { var self = this; // for PCCC always say yes. if (self.doNotOptimize) { return false; } // Are we skipping all optimization due to user request? return true; } NodeMBTCP.prototype.onResponse = function(data) { var self = this; // Packet Validity Check. Note that this will pass even with a "not available" response received from the server. // For length calculation and verification: // data[4] = COTP header length. Normally 2. This doesn't include the length byte so add 1. // read(13) is parameter length. Normally 4. // read(14) is data length. (Includes item headers) // 12 is length of "S7 header" // Then we need to add 4 for TPKT header. // 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(data,2); // Only log the entire buffer at high debug level outputLog("onResponse called with length " + data.length,1); if ((!self.connectionParams.RTU) && data.length < 9) { outputLog('DATA LESS THAN 9 BYTES RECEIVED. TOTAL CONNECTION RESET.'); outputLog(data); self.connectionReset(); // setTimeout(connectNow, 2000, connectionParams); return null; } if ((!self.connectionParams.RTU) && (data.length < (data.readInt16BE(4) + 6))) { outputLog('DATA LESS THAN MARKED LENGTH RECEIVED. TOTAL CONNECTION RESET.'); outputLog(data); self.connectionReset(); // setTimeout(connectNow, 2000, connectionParams); return null; } // The smallest read packet will pass a length check of 25. For a 1-item write response with no data, length will be 22. if ((!self.connectionParams.RTU) && (data.length > (data.readInt16BE(4) + 6))) { outputLog("An oversize packet was detected. Excess length is " + (data.length - data.readInt16BE(4) - 6) + ". "); outputLog("Usually because two packets were sent at nearly the same time by the PLC."); outputLog("We slice the buffer and schedule the second half for later processing."); // setTimeout(onResponse, 0, data.slice(data.readInt16BE(2) + 24)); // This re-triggers this same function with the sliced-up buffer. process.nextTick(function(){ self.onResponse(data.slice(data.readInt16BE(4) + 6)) }); // This re-triggers this same function with the sliced-up buffer. // was used as a test setTimeout(process.exit, 2000); } if (self.connectionParams.RTU) { if (data.length < 6) { // Some functions may return less than this but looking at slave ID, function number, one word of data and CRC we should not see less than 6 outputLog('DATA LESS THAN 6 BYTES RECEIVED. TOTAL CONNECTION RESET.'); outputLog(data); self.connectionReset(); // setTimeout(connectNow, 2000, connectionParams); return null; } var crcIn = data.readUInt16LE(data.length - 2); if (crcIn !== crc16(data.slice(0, -2))) { outputLog('CRC ERROR'); return null; } } outputLog('Valid Modbus 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 var foundSeqNum = undefined; // readPacketArray.length - 1; var packetCount = undefined; var isReadResponse = false, isWriteResponse = false; if (!self.connectionParams.RTU) { outputLog("On Response - Sequence " + data.readUInt16BE(0), 1); foundSeqNum = self.findReadIndexOfSeqNum(data.readUInt16BE(0)); // if (readPacketArray[packetCount] == undefined) { if (foundSeqNum == undefined) { foundSeqNum = self.findWriteIndexOfSeqNum(data.readUInt16BE(0)); if (foundSeqNum != undefined) { // for (packetCount = 0; packetCount < writePacketArray.length; packetCount++) { // if (writePacketArray[packetCount].seqNum == data.readUInt16BE(11)) { // foundSeqNum = packetCount; isWriteResponse = true; // break; } } else { isReadResponse = true; outputLog("Received Read Response - Array Offset Is " + foundSeqNum,1); } } if (self.connectionParams.RTU && self.isReading()) { // Could probably use this for TCP too isReadResponse = true; foundSeqNum = self.lastSeqNum; } if (self.connectionParams.RTU && self.isWriting()) { // Could probably use this for TCP too isWriteResponse = true; foundSeqNum = self.lastSeqNum; } if (isWriteResponse) { self.writeResponse(data, foundSeqNum); } else if (isReadResponse) { self.readResponse(data, foundSeqNum); } if ((!isReadResponse) && (!isWriteResponse)) { outputLog("Sequence number that arrived wasn't a write reply either - dropping"); outputLog(data); // I guess this isn't a showstopper, just ignore it. // connectionReset(); // setTimeout(connectNow, 2000, connectionParams); return null; } } NodeMBTCP.prototype.findReadIndexOfSeqNum = function(seqNum) { var self = this; var packetCounter; for (packetCounter = 0; packetCounter < self.readPacketArray.length; packetCounter++) { if (self.readPacketArray[packetCounter].seqNum == seqNum) { return packetCounter; } } return undefined; } NodeMBTCP.prototype.findWriteIndexOfSeqNum = function(seqNum) { var self = this; var packetCounter; for (packetCounter = 0; packetCounter < self.writePacketArray.length; packetCounter++) { if (self.writePacketArray[packetCounter].seqNum == seqNum) { return packetCounter; } } return undefined; } NodeMBTCP.prototype.writeResponse = function(data, foundSeqNum) { var self = this; var dataPointer = 21,i,anyBadQualities; if (!self.writePacketArray[foundSeqNum].sent) { outputLog('WARNING: Received a write packet that was not marked as sent',0,self.connectionID); return null; } if (self.writePacketArray[foundSeqNum].rcvd) { outputLog('WARNING: Received a write packet that was already marked as received',0,self.connectionID); return null; } for (itemCount = 0; itemCount < self.writePacketArray[foundSeqNum].itemList.length; itemCount++) { dataPointer = processMBWriteItem(data, self.writePacketArray[foundSeqNum].itemList[itemCount], dataPointer); if (!dataPointer) { outputLog('Stopping Processing Write Response Packet due to unrecoverable packet error'); break; } } // Make a note of the time it took the PLC to process the request. self.writePacketArray[foundSeqNum].reqTime = process.hrtime(self.writePacketArray[foundSeqNum].reqTime); outputLog('Time is ' + self.writePacketArray[foundSeqNum].reqTime[0] + ' seconds and ' + Math.round(self.writePacketArray[foundSeqNum].reqTime[1]*10/1e6)/10 + ' ms.',1); // writePacketArray.splice(foundSeqNum, 1); if (!self.writePacketArray[foundSeqNum].rcvd) { self.writePacketArray[foundSeqNum].rcvd = true; self.parallelJobsNow--; } clearTimeout(self.writePacketArray[foundSeqNum].timeout); if (!self.writePacketArray.every(doneSending)) { // readPacketInterval = setTimeout(prepareReadPacket, 3000); self.sendWritePacket(); outputLog("Sending again",1); } else { for (i=0;i<self.writePacketArray.length;i++) { self.writePacketArray[i].sent = false; self.writePacketArray[i].rcvd = false; } anyBadQualities = false; for (i=0;i<self.globalWriteBlockList.length;i++) { // Post-process the write code and apply the quality. // Loop through the global block list... writePostProcess(self.globalWriteBlockList[i]); outputLog(self.globalWriteBlockList[i].addr + ' write completed with quality ' + self.globalWriteBlockList[i].writeQuality,0); if (!isQualityOK(self.globalWriteBlockList[i].writeQuality)) { anyBadQualities = true; } } if (typeof(self.writeDoneCallback === 'function')) { self.writeDoneCallback(anyBadQualities); } } } NodeMBTCP.prototype.readResponse = function(data, foundSeqNum) { var self = this; var anyBadQualities,dataPointer = 21; // For non-routed packets we start at byte 21 of the packet. If we do routing it will be more than this. var dataObject = {}; outputLog("ReadResponse called",1,self.connectionID); if (!self.readPacketArray[foundSeqNum].sent) { outputLog('WARNING: Received a read response packet that was not marked as sent',0,self.connectionID); //TODO - fix the network unreachable error that made us do this return null; } if (self.readPacketArray[foundSeqNum].rcvd) { outputLog('WARNING: Received a read response packet that was already marked as received',0,self.connectionID); return null; } for (itemCount = 0; itemCount < self.readPacketArray[foundSeqNum].itemList.length; itemCount++) { dataPointer = processMBPacket(data, self.readPacketArray[foundSeqNum].itemList[itemCount], dataPointer, self.connectionParams.RTU); if (!dataPointer && typeof(data) !== "undefined") { // Don't bother showing this message on timeout. outputLog('Received a ZERO RESPONSE Processing Read Packet due to unrecoverable packet error'); // break; // We rely on this for our timeout now. } } // Make a note of the time it took the PLC to process the request. self.readPacketArray[foundSeqNum].reqTime = process.hrtime(self.readPacketArray[foundSeqNum].reqTime); outputLog('Read Time is ' + self.readPacketArray[foundSeqNum].reqTime[0] + ' seconds and ' + Math.round(self.readPacketArray[foundSeqNum].reqTime[1]*10/1e6)/10 + ' ms.',1,self.connectionID); // Do the bookkeeping for packet and timeout. if (!self.readPacketArray[foundSeqNum].rcvd) { self.readPacketArray[foundSeqNum].rcvd = true; self.parallelJobsNow--; if (self.parallelJobsNow < 0) { self.parallelJobsNow = 0; } } clearTimeout(self.readPacketArray[foundSeqNum].timeout); if(self.readPacketArray.every(doneSending)) { // if sendReadPacket returns true we're all done. // Mark our packets unread for next time. outputLog('Every packet done sending',1,self.connectionID); for (i=0;i<self.readPacketArray.length;i++) { self.readPacketArray[i].sent = false; self.readPacketArray[i].rcvd = false; } anyBadQualities = false; // Loop through the global block list... for (var i=0;i<self.globalReadBlockList.length;i++) { var lengthOffset = 0; // For each block, we