requirebin sketch
// Welcome! require() some modules from npm (like you were using browserify)
// and then hit Run Code to run your code on the right side.
// Modules get downloaded from browserify-cdn and bundled in your browser.
var nodes7 = require('nodes7');
var conn = new nodes7;
//var ourProcess = require('.process/browser');
var doneReading = false;
var doneWriting = false;
//<data block number.> <memory area><data type><byte offset><.array length>
// TEST2: 'M32.2', // Bit at M32.2
// TEST3: 'M20.0', // Bit at M20.0
// TEST4: 'DB1,REAL0.20', // Array of 20 values in DB1
// TEST5: 'DB1,REAL4', // Single real value
// TEST6: 'DB1,REAL8', // Another single real value
// TEST7: 'DB1,INT12.2' // Two integer value array
var variables = {
CONTADORT1: 'DB10,INT10.1',
CONTADORT2: 'DB0,D10,'
};
conn.initiateConnection({port: 102, host: '10.0.2.1', rack: 1, slot: 0}, connected); // slot 2 for 300/400, slot 1 for 1200/1500
function connected(err) {
if (typeof(err) !== "undefined") {
// We have an error. Maybe the PLC is not reachable.
console.log(err);
process.exit();
}
conn.setTranslationCB(function(tag) {return variables[tag];}); // This sets the "translation" to allow us to work with object names
//conn.addItems(['TEST1', 'TEST4']);
conn.addItems('CONTADORT2');
// conn.removeItems(['TEST2', 'TEST3']); // We could do this.
// conn.writeItems(['TEST5', 'TEST6'], [ 867.5309, 9 ], valuesWritten); // You can write an array of items as well.
conn.writeItems('CONTADORT2', [121] , valuesWritten); // You can write a single array item too.
conn.readAllItems(valuesReady);
}
function valuesReady(anythingBad, values) {
if (anythingBad) { console.log("SOMETHING WENT WRONG READING VALUES!!!!"); }
console.log(values);
doneReading = true;
if (doneWriting) { process.exit(); }
}
function valuesWritten(anythingBad) {
if (anythingBad) { console.log("SOMETHING WENT WRONG WRITING VALUES!!!!"); }
console.log("Done writing.");
doneWriting = true;
if (doneReading) { process.exit(); }
}
setTimeout(function(){require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){},{}],2:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var rootParent={};Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();function typedArraySupport(){function Bar(){}try{var arr=new Uint8Array(1);arr.foo=function(){return 42};arr.constructor=Bar;return arr.foo()===42&&arr.constructor===Bar&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Buffer(arg){if(!(this instanceof Buffer)){if(arguments.length>1)return new Buffer(arg,arguments[1]);return new Buffer(arg)}if(!Buffer.TYPED_ARRAY_SUPPORT){this.length=0;this.parent=undefined}if(typeof arg==="number"){return fromNumber(this,arg)}if(typeof arg==="string"){return fromString(this,arg,arguments.length>1?arguments[1]:"utf8")}return fromObject(this,arg)}function fromNumber(that,length){that=allocate(that,length<0?0:checked(length)|0);if(!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<length;i++){that[i]=0}}return that}function fromString(that,string,encoding){if(typeof encoding!=="string"||encoding==="")encoding="utf8";var length=byteLength(string,encoding)|0;that=allocate(that,length);that.write(string,encoding);return that}function fromObject(that,object){if(Buffer.isBuffer(object))return fromBuffer(that,object);if(isArray(object))return fromArray(that,object);if(object==null){throw new TypeError("must start with number, buffer, array or string")}if(typeof ArrayBuffer!=="undefined"){if(object.buffer instanceof ArrayBuffer){return fromTypedArray(that,object)}if(object instanceof ArrayBuffer){return fromArrayBuffer(that,object)}}if(object.length)return fromArrayLike(that,object);return fromJsonObject(that,object)}function fromBuffer(that,buffer){var length=checked(buffer.length)|0;that=allocate(that,length);buffer.copy(that,0,0,length);return that}function fromArray(that,array){var length=checked(array.length)|0;that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}function fromTypedArray(that,array){var length=checked(array.length)|0;that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}function fromArrayBuffer(that,array){if(Buffer.TYPED_ARRAY_SUPPORT){array.byteLength;that=Buffer._augment(new Uint8Array(array))}else{that=fromTypedArray(that,new Uint8Array(array))}return that}function fromArrayLike(that,array){var length=checked(array.length)|0;that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}function fromJsonObject(that,object){var array;var length=0;if(object.type==="Buffer"&&isArray(object.data)){array=object.data;length=checked(array.length)|0}that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}if(Buffer.TYPED_ARRAY_SUPPORT){Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array}else{Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined}function allocate(that,length){if(Buffer.TYPED_ARRAY_SUPPORT){that=Buffer._augment(new Uint8Array(length));that.__proto__=Buffer.prototype}else{that.length=length;that._isBuffer=true}var fromPool=length!==0&&length<=Buffer.poolSize>>>1;if(fromPool)that.parent=rootParent;return that}function checked(length){if(length>=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(subject,encoding){if(!(this instanceof SlowBuffer))return new SlowBuffer(subject,encoding);var buf=new Buffer(subject,encoding);delete buf.parent;return buf}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;var i=0;var len=Math.min(x,y);while(i<len){if(a[i]!==b[i])break;++i}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function concat(list,length){if(!isArray(list))throw new TypeError("list argument must be an Array of Buffers.");if(list.length===0){return new Buffer(0)}var i;if(length===undefined){length=0;for(i=0;i<list.length;i++){length+=list[i].length}}var buf=new Buffer(length);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};function byteLength(string,encoding){if(typeof string!=="string")string=""+string;var len=string.length;if(len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"binary":case"raw":case"raws":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;start=start|0;end=end===undefined||end===Infinity?this.length:end|0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype.toString=function toString(){var length=this.length|0;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this,arguments)};Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function compare(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return 0;return Buffer.compare(this,b)};Buffer.prototype.indexOf=function indexOf(val,byteOffset){if(byteOffset>2147483647)byteOffset=2147483647;else if(byteOffset<-2147483648)byteOffset=-2147483648;byteOffset>>=0;if(this.length===0)return-1;if(byteOffset>=this.length)return-1;if(byteOffset<0)byteOffset=Math.max(this.length+byteOffset,0);if(typeof val==="string"){if(val.length===0)return-1;return String.prototype.indexOf.call(this,val,byteOffset)}if(Buffer.isBuffer(val)){return arrayIndexOf(this,val,byteOffset)}if(typeof val==="number"){if(Buffer.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,val,byteOffset)}return arrayIndexOf(this,[val],byteOffset)}function arrayIndexOf(arr,val,byteOffset){var foundIndex=-1;for(var i=0;byteOffset+i<arr.length;i++){if(arr[byteOffset+i]===val[foundIndex===-1?0:i-foundIndex]){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===val.length)return byteOffset+foundIndex}else{foundIndex=-1}}return-1}throw new TypeError("val must be string, number or Buffer")};Buffer.prototype.get=function get(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function set(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var parsed=parseInt(string.substr(i*2,2),16);if(isNaN(parsed))throw new Error("Invalid hex string");buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding="utf8";length=this.length;offset=0}else if(length===undefined&&typeof offset==="string"){encoding=offset;length=this.length;offset=0}else if(isFinite(offset)){offset=offset|0;if(isFinite(length)){length=length|0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length|0;length=swap}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"binary":return binaryWrite(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i<end){var firstByte=buf[i];var codePoint=null;var bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(i<len){res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH))}return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i]&127)}return ret}function binarySlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function slice(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}}if(newBuf.length)newBuf.parent=this.parent||this;return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}return val};Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=value<0?1:0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=value<0?1:0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range");if(offset<0)throw new RangeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||this.length===0)return 0;if(targetStart<0){throw new RangeError("targetStart out of bounds")}if(start<0||start>=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart<end-start){end=target.length-targetStart+start}var len=end-start;var i;if(this===target&&start<targetStart&&targetStart<end){for(i=len-1;i>=0;i--){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i<len;i++){target[i+targetStart]=this[i+start]}}else{target._set(this.subarray(start,start+len),targetStart)}return len};Buffer.prototype.fill=function fill(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new RangeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new RangeError("start out of bounds");if(end<0||end>this.length)throw new RangeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.toArrayBuffer=function toArrayBuffer(){if(typeof Uint8Array!=="undefined"){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function _augment(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.indexOf=BP.indexOf;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUIntLE=BP.readUIntLE;arr.readUIntBE=BP.readUIntBE;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readIntLE=BP.readIntLE;arr.readIntBE=BP.readIntBE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUIntLE=BP.writeUIntLE;arr.writeUIntBE=BP.writeUIntBE;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeIntLE=BP.writeIntLE;arr.writeIntBE=BP.writeIntBE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){units=units||Infinity;var codePoint;var length=string.length;var leadSurrogate=null;var bytes=[];for(var i=0;i<length;i++){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":3,ieee754:4,isarray:5}],3:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);var PLUS_URL_SAFE="-".charCodeAt(0);var SLASH_URL_SAFE="_".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS||code===PLUS_URL_SAFE)return 62;if(code===SLASH||code===SLASH_URL_SAFE)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];
output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],4:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],5:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],6:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],7:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],8:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],9:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":8,_process:6,inherits:7}],nodes7:[function(require,module,exports){(function(process,Buffer){var net=require("net");var util=require("util");var effectiveDebugLevel=0;var silentMode=false;module.exports=NodeS7;function NodeS7(opts){opts=opts||{};silentMode=opts.silent||false;effectiveDebugLevel=opts.debug?99:0;var self=this;self.connectReq=new Buffer([3,0,0,22,17,224,0,0,0,2,0,192,1,10,193,2,1,0,194,2,1,2]);self.negotiatePDU=new Buffer([3,0,0,25,2,240,128,50,1,0,0,0,0,0,8,0,0,240,0,0,8,0,8,3,192]);self.readReqHeader=new Buffer([3,0,0,31,2,240,128,50,1,0,0,8,0,0,14,0,0,4,1]);self.readReq=new Buffer(1500);self.writeReqHeader=new Buffer([3,0,0,31,2,240,128,50,1,0,0,8,0,0,14,0,0,5,1]);self.writeReq=new Buffer(1500);self.resetPending=false;self.resetTimeout=undefined;self.isoclient=undefined;self.isoConnectionState=0;self.requestMaxPDU=960;self.maxPDU=960;self.requestMaxParallel=8;self.maxParallel=8;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=1500;self.rack=0;self.slot=2;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}NodeS7.prototype.setTranslationCB=function(cb){var self=this;if(typeof cb==="function"){outputLog("Translation OK");self.translationCB=cb}};NodeS7.prototype.initiateConnection=function(cParam,callback){var self=this;if(cParam===undefined){cParam={port:102,host:"192.168.8.106"}}outputLog("Initiate Called - Connecting to PLC with address and parameters:");outputLog(cParam);if(typeof cParam.rack!=="undefined"){self.rack=cParam.rack}if(typeof cParam.slot!=="undefined"){self.slot=cParam.slot}if(typeof cParam.connection_name==="undefined"){self.connectionID=cParam.host+" S"+self.slot}else{self.connectionID=cParam.connection_name}self.connectionParams=cParam;self.connectCallback=callback;self.connectCBIssued=false;self.connectNow(self.connectionParams,false)};NodeS7.prototype.dropConnection=function(callback){var self=this;if(typeof self.isoclient!=="undefined"){self.dropConnectionCallback=callback;self.isoclient.end();self.dropConnectionTimer=setTimeout(function(){if(self.dropConnectionCallback){self.isoclient.destroy();self.connectionCleanup();self.dropConnectionCallback();self.dropConnectionCallback=null}},2500)}else{callback()}};NodeS7.prototype.connectNow=function(cParam){var self=this;if(self.isoConnectionState>=1){return}self.connectionCleanup();self.isoclient=net.connect(cParam,function(){self.onTCPConnect.apply(self,arguments)});self.isoConnectionState=1;self.isoclient.on("error",function(){self.connectError.apply(self,arguments)});outputLog("<initiating a new connection "+Date()+">",1,self.connectionID);outputLog("Attempting to connect to host...",0,self.connectionID)};NodeS7.prototype.connectError=function(e){var self=this;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};NodeS7.prototype.readWriteError=function(e){var self=this;outputLog("We Caught a read/write error "+e.code+" - will DISCONNECT and attempt to reconnect.");self.isoConnectionState=0;self.connectionReset()};NodeS7.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 connecting to 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)},2e3,self.connectionParams);return undefined}if(packetType==="PDU"){outputLog("TIMED OUT waiting for PDU reply packet from PLC - Disconnecting");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, PDU type, is happening now",0,self.connectionID);self.connectNow.apply(self,arguments)},2e3,self.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.")};NodeS7.prototype.onTCPConnect=function(){var self=this;outputLog("TCP Connection Established to "+self.isoclient.remoteAddress+" on port "+self.isoclient.remotePort,0,self.connectionID);outputLog("Will attempt ISO-on-TCP connection",0,self.connectionID);self.isoConnectionState=2;self.connectTimeout=setTimeout(function(){self.packetTimeout.apply(self,arguments)},self.globalTimeout,"connect");self.connectReq[21]=self.rack*32+self.slot;self.isoclient.write(self.connectReq.slice(0,22));self.isoclient.on("data",function(){self.onISOConnectReply.apply(self,arguments)});self.isoclient.on("end",function(){self.onClientDisconnect.apply(self,arguments)});self.isoclient.on("close",function(){self.onClientClose.apply(self,arguments)})};NodeS7.prototype.onISOConnectReply=function(data){var self=this;self.isoclient.removeAllListeners("data");self.isoclient.removeAllListeners("error");clearTimeout(self.connectTimeout);self.isoConnectionState=3;if(data.readInt16BE(2)!==data.length||data.length<22||data[5]!==208||data[4]!==data.length-5){outputLog("INVALID PACKET or CONNECTION REFUSED - DISCONNECTING");outputLog(data);outputLog("TPKT Length From Header is "+data.readInt16BE(2)+" and RCV buffer length is "+data.length+" and COTP length is "+data.readUInt8(4)+" and data[5] is "+data[5]);self.connectionReset();return null}outputLog("ISO-on-TCP Connection Confirm Packet Received",0,self.connectionID);self.negotiatePDU.writeInt16BE(self.requestMaxParallel,19);self.negotiatePDU.writeInt16BE(self.requestMaxParallel,21);self.negotiatePDU.writeInt16BE(self.requestMaxPDU,23);self.PDUTimeout=setTimeout(function(){self.packetTimeout.apply(self,arguments)},self.globalTimeout,"PDU");self.isoclient.write(self.negotiatePDU.slice(0,25));self.isoclient.on("data",function(){self.onPDUReply.apply(self,arguments)});self.isoclient.on("error",function(){self.readWriteError.apply(self,arguments)})};NodeS7.prototype.onPDUReply=function(data){var self=this;self.isoclient.removeAllListeners("data");self.isoclient.removeAllListeners("error");clearTimeout(self.PDUTimeout);if(data.readInt16BE(2)!==data.length||data.length<27||data[5]!==240||data[4]+1+12+data.readInt16BE(13)!==data.length-4||!(data[6]>>7)){outputLog("INVALID PDU RESPONSE or CONNECTION REFUSED - DISCONNECTING",0,self.connectionID);outputLog("TPKT Length From Header is "+data.readInt16BE(2)+" and RCV buffer length is "+data.length+" and COTP length is "+data.readUInt8(4)+" and data[6] is "+data[6],0,self.connectionID);outputLog(data);self.isoclient.end();setTimeout(function(){self.connectNow.apply(self,arguments)},2e3,self.connectionParams);return null}self.isoConnectionState=4;var partnerMaxParallel1=data.readInt16BE(21);var partnerMaxParallel2=data.readInt16BE(23);var partnerPDU=data.readInt16BE(25);self.maxParallel=self.requestMaxParallel;if(partnerMaxParallel1<self.requestMaxParallel){self.maxParallel=partnerMaxParallel1}if(partnerMaxParallel2<self.requestMaxParallel){self.maxParallel=partnerMaxParallel2}if(partnerPDU<self.requestMaxPDU){self.maxPDU=partnerPDU}else{self.maxPDU=self.requestMaxPDU}outputLog("Received PDU Response - Proceeding with PDU "+self.maxPDU+" and "+self.maxParallel+" max parallel connections.",0,self.connectionID);self.isoclient.on("data",function(){self.onResponse.apply(self,arguments)});self.isoclient.on("error",function(){self.readWriteError.apply(self,arguments)});if(!self.connectCBIssued&&typeof self.connectCallback==="function"){self.connectCBIssued=true;self.connectCallback()}};NodeS7.prototype.writeItems=function(arg,value,cb){var self=this,i;outputLog("Preparing to WRITE "+arg+" to value "+value,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=[];if(typeof arg==="string"){self.instantWriteBlockList.push(stringToS7Addr(self.translationCB(arg),arg));if(typeof self.instantWriteBlockList[self.instantWriteBlockList.length-1]!=="undefined"){self.instantWriteBlockList[self.instantWriteBlockList.length-1].writeValue=value}}else if(Array.isArray(arg)&&Array.isArray(value)&&arg.length==value.length){for(i=0;i<arg.length;i++){if(typeof arg[i]==="string"){self.instantWriteBlockList.push(stringToS7Addr(self.translationCB(arg[i]),arg[i]));if(typeof self.instantWriteBlockList[self.instantWriteBlockList.length-1]!=="undefined"){self.instantWriteBlockList[self.instantWriteBlockList.length-1].writeValue=value[i]}}}}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}};NodeS7.prototype.findItem=function(useraddr){var self=this,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};NodeS7.prototype.addItems=function(arg){var self=this;self.addRemoveArray.push({arg:arg,action:"add"})};NodeS7.prototype.addItemsNow=function(arg){var self=this,i;outputLog("Adding "+arg,0,self.connectionID);if(typeof arg==="string"&&arg!=="_COMMERR"){self.polledReadBlockList.push(stringToS7Addr(self.translationCB(arg),arg))}else if(Array.isArray(arg)){for(i=0;i<arg.length;i++){if(typeof arg[i]==="string"&&arg[i]!=="_COMMERR"){self.polledReadBlockList.push(stringToS7Addr(self.translationCB(arg[i]),arg[i]))}}}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.",0,self.connectionID)}}self.readPacketValid=false};NodeS7.prototype.removeItems=function(arg){var self=this;self.addRemoveArray.push({arg:arg,action:"remove"})};NodeS7.prototype.removeItemsNow=function(arg){var self=this,i;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(Array.isArray(arg)){for(i=0;i<self.polledReadBlockList.length;i++){for(var j=0;j<arg.length;j++){if(self.polledReadBlockList[i].addr===self.translationCB(arg[j])){self.polledReadBlockList.splice(i,1)}}}}self.readPacketValid=false};NodeS7.prototype.readAllItems=function(arg){var self=this;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)}if(self.isWaiting()){outputLog("Waiting to read for all R/W operations to complete. Will re-trigger readAllItems in 100ms.",0,self.connectionID);setTimeout(function(){self.readAllItems.apply(self,arguments)},100,arg);return}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=[];if(!self.readPacketValid){self.prepareReadPacket()}outputLog("Calling SRP from RAI",1,self.connectionID);self.sendReadPacket()};NodeS7.prototype.isWaiting=function(){var self=this;return self.isReading()||self.isWriting()};NodeS7.prototype.isReading=function(){var self=this,i;for(i=0;i<self.readPacketArray.length;i++){if(self.readPacketArray[i].sent===true){return true}}return false};NodeS7.prototype.isWriting=function(){var self=this,i;for(i=0;i<self.writePacketArray.length;i++){if(self.writePacketArray[i].sent===true){return true}}return false};NodeS7.prototype.clearReadPacketTimeouts=function(){var self=this,i;outputLog("Clearing read PacketTimeouts",1,self.connectionID);for(i=0;i<self.readPacketArray.length;i++){clearTimeout(self.readPacketArray[i].timeout);self.readPacketArray[i].sent=false;self.readPacketArray[i].rcvd=false}};NodeS7.prototype.clearWritePacketTimeouts=function(){var self=this,i;outputLog("Clearing write PacketTimeouts",1,self.connectionID);for(i=0;i<self.writePacketArray.length;i++){clearTimeout(self.writePacketArray[i].timeout);self.writePacketArray[i].sent=false;self.writePacketArray[i].rcvd=false}};NodeS7.prototype.prepareWritePacket=function(){var self=this,i;var itemList=self.instantWriteBlockList;var requestList=[];var requestNumber=0;itemList.sort(itemListSorter);if(itemList.length===0){return undefined}self.globalWriteBlockList=[];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=4*Math.floor((self.maxPDU-18-12)/4);for(i=0;i<itemList.length;i++){self.globalWriteBlockList[i]=itemList[i];self.globalWriteBlockList[i].isOptimized=false;self.globalWriteBlockList[i].itemReference=[];self.globalWriteBlockList[i].itemReference.push(itemList[i]);bufferizeS7Item(itemList[i])}var thisRequest=0;for(i=0;i<self.globalWriteBlockList.length;i++){var startByte=self.globalWriteBlockList[i].offset;var remainingLength=self.globalWriteBlockList[i].byteLength;var lengthOffset=0;requestList[thisRequest]=self.globalWriteBlockList[i].clone();self.globalWriteBlockList[i].parts=Math.ceil(self.globalWriteBlockList[i].byteLength/maxByteRequest);self.globalWriteBlockList[i].requestReference=[];for(var j=0;j<self.globalWriteBlockList[i].parts;j++){requestList[thisRequest]=self.globalWriteBlockList[i].clone();self.globalWriteBlockList[i].requestReference.push(requestList[thisRequest]);requestList[thisRequest].offset=startByte;requestList[thisRequest].byteLength=Math.min(maxByteRequest,remainingLength);requestList[thisRequest].byteLengthWithFill=requestList[thisRequest].byteLength;if(requestList[thisRequest].byteLengthWithFill%2){requestList[thisRequest].byteLengthWithFill+=1}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}remainingLength-=maxByteRequest;thisRequest++;startByte+=maxByteRequest}}self.clearWritePacketTimeouts();self.writePacketArray=[];while(requestNumber<requestList.length){self.masterSequenceNumber+=1;if(self.masterSequenceNumber>32767){self.masterSequenceNumber=1}var numItems=0;self.writeReqHeader.copy(self.writeReq,0);var packetWriteLength=10+4;self.writePacketArray.push(new S7Packet);var thisPacketNumber=self.writePacketArray.length-1;self.writePacketArray[thisPacketNumber].seqNum=self.masterSequenceNumber;self.writePacketArray[thisPacketNumber].itemList=[];for(i=requestNumber;i<requestList.length;i++){if(requestList[i].byteLengthWithFill+12+4+packetWriteLength>self.maxPDU){if(numItems===0){outputLog("breaking when we shouldn't, byte length with fill is "+requestList[i].byteLengthWithFill+" max byte request "+maxByteRequest,0,self.connectionID);throw new Error("Somehow write request didn't split properly - exiting. Report this as a bug.")}break}requestNumber++;numItems++;packetWriteLength+=requestList[i].byteLengthWithFill+12+4;self.writePacketArray[thisPacketNumber].itemList.push(requestList[i])}}};NodeS7.prototype.prepareReadPacket=function(){var self=this,i;var itemList=self.polledReadBlockList;var requestList=[];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)}}itemList.sort(itemListSorter);if(itemList.length===0){return undefined}self.globalReadBlockList=[];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=4*Math.floor((self.maxPDU-18)/4);for(i=1;i<itemList.length;i++){if(itemList[i].areaS7Code!==self.globalReadBlockList[thisBlock].areaS7Code||itemList[i].dbNumber!==self.globalReadBlockList[thisBlock].dbNumber||!self.isOptimizableArea(itemList[i].areaS7Code)||itemList[i].offset-self.globalReadBlockList[thisBlock].offset+itemList[i].byteLength>maxByteRequest||itemList[i].offset-(self.globalReadBlockList[thisBlock].offset+self.globalReadBlockList[thisBlock].byteLength)>self.maxGap){thisBlock=thisBlock+1;self.globalReadBlockList[thisBlock]=itemList[i];self.globalReadBlockList[thisBlock].isOptimized=false;self.globalReadBlockList[thisBlock].itemReference=[];self.globalReadBlockList[thisBlock].itemReference.push(itemList[i])}else{outputLog("Attempting optimization of item "+itemList[i].addr+" with "+self.globalReadBlockList[thisBlock].addr,0,self.connectionID);
self.globalReadBlockList[thisBlock].byteLength=Math.max(self.globalReadBlockList[thisBlock].byteLength,itemList[i].offset-self.globalReadBlockList[thisBlock].offset+itemList[i].byteLength);itemList[i].byteBuffer=self.globalReadBlockList[thisBlock].byteBuffer.slice(itemList[i].offset-self.globalReadBlockList[thisBlock].offset,itemList[i].offset-self.globalReadBlockList[thisBlock].offset+itemList[i].byteLength);itemList[i].qualityBuffer=self.globalReadBlockList[thisBlock].qualityBuffer.slice(itemList[i].offset-self.globalReadBlockList[thisBlock].offset,itemList[i].offset-self.globalReadBlockList[thisBlock].offset+itemList[i].byteLength);self.globalReadBlockList[thisBlock].isOptimized=true;self.globalReadBlockList[thisBlock].itemReference.push(itemList[i])}}var thisRequest=0;for(i=0;i<self.globalReadBlockList.length;i++){requestList[thisRequest]=self.globalReadBlockList[i].clone();self.globalReadBlockList[i].parts=Math.ceil(self.globalReadBlockList[i].byteLength/maxByteRequest);outputLog("self.globalReadBlockList "+i+" parts is "+self.globalReadBlockList[i].parts+" offset is "+self.globalReadBlockList[i].offset+" MBR is "+maxByteRequest,1,self.connectionID);var startByte=self.globalReadBlockList[i].offset;var remainingLength=self.globalReadBlockList[i].byteLength;self.globalReadBlockList[i].requestReference=[];for(var j=0;j<self.globalReadBlockList[i].parts;j++){requestList[thisRequest]=self.globalReadBlockList[i].clone();self.globalReadBlockList[i].requestReference.push(requestList[thisRequest]);requestList[thisRequest].offset=startByte;requestList[thisRequest].byteLength=Math.min(maxByteRequest,remainingLength);requestList[thisRequest].byteLengthWithFill=requestList[thisRequest].byteLength;if(requestList[thisRequest].byteLengthWithFill%2){requestList[thisRequest].byteLengthWithFill+=1}if(self.globalReadBlockList[i].parts>1){requestList[thisRequest].datatype="BYTE";requestList[thisRequest].dtypelen=1;requestList[thisRequest].arrayLength=requestList[thisRequest].byteLength}remainingLength-=maxByteRequest;thisRequest++;startByte+=maxByteRequest}}var requestNumber=0;self.clearReadPacketTimeouts();self.readPacketArray=[];while(requestNumber<requestList.length){self.masterSequenceNumber+=1;if(self.masterSequenceNumber>32767){self.masterSequenceNumber=1}var numItems=0;self.readReqHeader.copy(self.readReq,0);var packetReplyLength=12+2;self.readPacketArray.push(new S7Packet);var thisPacketNumber=self.readPacketArray.length-1;self.readPacketArray[thisPacketNumber].seqNum=self.masterSequenceNumber;outputLog("Sequence Number is "+self.readPacketArray[thisPacketNumber].seqNum,1,self.connectionID);self.readPacketArray[thisPacketNumber].itemList=[];for(i=requestNumber;i<requestList.length;i++){if(requestList[i].byteLengthWithFill+4+packetReplyLength>self.maxPDU){if(numItems===0){outputLog("breaking when we shouldn't, rlibl "+requestList[i].byteLengthWithFill+" MBR "+maxByteRequest,0,self.connectionID);throw new Error("Somehow write request didn't split properly - exiting. Report this as a bug.")}break}requestNumber++;numItems++;packetReplyLength+=requestList[i].byteLengthWithFill+4;self.readPacketArray[thisPacketNumber].itemList.push(requestList[i])}}self.readPacketValid=true};NodeS7.prototype.sendReadPacket=function(){var self=this,i,j,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}self.readPacketArray[i].reqTime=process.hrtime();self.readReq.writeUInt8(self.readPacketArray[i].itemList.length,18);self.readReq.writeUInt16BE(19+self.readPacketArray[i].itemList.length*12,2);self.readReq.writeUInt16BE(self.readPacketArray[i].seqNum,11);self.readReq.writeUInt16BE(self.readPacketArray[i].itemList.length*12+2,13);for(j=0;j<self.readPacketArray[i].itemList.length;j++){S7AddrToBuffer(self.readPacketArray[i].itemList[j],false).copy(self.readReq,19+j*12)}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,19+self.readPacketArray[i].itemList.length*12));self.readPacketArray[i].sent=true;self.readPacketArray[i].rcvd=false;self.readPacketArray[i].timeoutError=false;self.parallelJobsNow+=1}else{self.readPacketArray[i].sent=true;self.readPacketArray[i].rcvd=false;self.readPacketArray[i].timeoutError=true;if(!flagReconnect){outputLog("Not Sending Read Packet because we are not connected - ISO CS is "+self.isoConnectionState,0,self.connectionID)}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)}outputLog("Sending Read Packet",1,self.connectionID)}if(flagReconnect){setTimeout(function(){outputLog("The scheduled reconnect from sendReadPacket is happening now",1,self.connectionID);self.connectNow(self.connectionParams)},0)}};NodeS7.prototype.sendWritePacket=function(){var self=this,i,dataBuffer,itemBuffer,dataBufferPointer,flagReconnect;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}self.writePacketArray[i].reqTime=process.hrtime();self.writeReq.writeUInt8(self.writePacketArray[i].itemList.length,18);self.writeReq.writeUInt16BE(self.writePacketArray[i].seqNum,11);dataBufferPointer=0;for(var j=0;j<self.writePacketArray[i].itemList.length;j++){S7AddrToBuffer(self.writePacketArray[i].itemList[j],true).copy(self.writeReq,19+j*12);itemBuffer=getWriteBuffer(self.writePacketArray[i].itemList[j]);itemBuffer.copy(dataBuffer,dataBufferPointer);dataBufferPointer+=itemBuffer.length;if(j<self.writePacketArray[i].itemList.length-1){if(itemBuffer.length%2){dataBufferPointer+=1}}}self.writeReq.writeUInt16BE(19+self.writePacketArray[i].itemList.length*12+dataBufferPointer,2);self.writeReq.writeUInt16BE(self.writePacketArray[i].itemList.length*12+2,13);self.writeReq.writeUInt16BE(dataBufferPointer,15);dataBuffer.copy(self.writeReq,19+self.writePacketArray[i].itemList.length*12,0,dataBufferPointer);if(self.isoConnectionState===4){self.writePacketArray[i].timeout=setTimeout(function(){self.packetTimeout.apply(self,arguments)},self.globalTimeout,"write",self.writePacketArray[i].seqNum);self.isoclient.write(self.writeReq.slice(0,19+dataBufferPointer+self.writePacketArray[i].itemList.length*12));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{self.writePacketArray[i].sent=true;self.writePacketArray[i].rcvd=false;self.writePacketArray[i].timeoutError=true;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)},0)}};NodeS7.prototype.isOptimizableArea=function(area){var self=this;if(self.doNotOptimize){return false}switch(area){case 132:case 129:case 130:case 131:return true;default:return false}};NodeS7.prototype.onResponse=function(data){var self=this;if(data.length>8&&data[8]!=3){outputLog("PDU type (byte 8) was returned as "+data[8]+" where the response PDU of 3 was expected.");outputLog("Maybe you are requesting more than 240 bytes of data in a packet?");outputLog(data);self.connectionReset();return null}if(data.length>data.readInt16BE(2)){outputLog("An oversize packet was detected. Excess length is "+data.length-data.readInt16BE(2)+". ");outputLog("We assume this is because two packets were sent at nearly the same time by the PLC.");outputLog("We are slicing the buffer and scheduling the second half for further processing next loop.");setTimeout(function(){self.onResponse.apply(self,arguments)},0,data.slice(data.readInt16BE(2)))}if(data.length<data.readInt16BE(2)||data.readInt16BE(2)<22||data[5]!==240||data[4]+1+12+4+data.readInt16BE(13)+data.readInt16BE(15)!==data.readInt16BE(2)||!(data[6]>>7)||data[7]!==50||data[8]!==3){outputLog("INVALID READ RESPONSE - DISCONNECTING");outputLog("TPKT Length From Header is "+data.readInt16BE(2)+" and RCV buffer length is "+data.length+" and COTP length is "+data.readUInt8(4)+" and data[6] is "+data[6]);outputLog(data);self.connectionReset();return null}outputLog("Received "+data.readUInt16BE(15)+" bytes of S7-data from PLC. Sequence number is "+data.readUInt16BE(11),1,self.connectionID);var foundSeqNum;var isReadResponse,isWriteResponse;foundSeqNum=self.findReadIndexOfSeqNum(data.readUInt16BE(11));if(foundSeqNum===undefined){foundSeqNum=self.findWriteIndexOfSeqNum(data.readUInt16BE(11));if(foundSeqNum!==undefined){self.writeResponse(data,foundSeqNum);isWriteResponse=true}}else{isReadResponse=true;self.readResponse(data,foundSeqNum)}if(!isReadResponse&&!isWriteResponse){outputLog("Sequence number that arrived wasn't a write reply either - dropping");outputLog(data);return null}};NodeS7.prototype.findReadIndexOfSeqNum=function(seqNum){var self=this,packetCounter;for(packetCounter=0;packetCounter<self.readPacketArray.length;packetCounter++){if(self.readPacketArray[packetCounter].seqNum==seqNum){return packetCounter}}return undefined};NodeS7.prototype.findWriteIndexOfSeqNum=function(seqNum){var self=this,packetCounter;for(packetCounter=0;packetCounter<self.writePacketArray.length;packetCounter++){if(self.writePacketArray[packetCounter].seqNum==seqNum){return packetCounter}}return undefined};NodeS7.prototype.writeResponse=function(data,foundSeqNum){var self=this,dataPointer=21,i,anyBadQualities;for(var itemCount=0;itemCount<self.writePacketArray[foundSeqNum].itemList.length;itemCount++){dataPointer=processS7WriteItem(data,self.writePacketArray[foundSeqNum].itemList[itemCount],dataPointer);if(!dataPointer){outputLog("Stopping Processing Write Response Packet due to unrecoverable packet error");break}}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,self.connectionID);if(!self.writePacketArray[foundSeqNum].rcvd){self.writePacketArray[foundSeqNum].rcvd=true;self.parallelJobsNow--}clearTimeout(self.writePacketArray[foundSeqNum].timeout);if(!self.writePacketArray.every(doneSending)){self.sendWritePacket()}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++){writePostProcess(self.globalWriteBlockList[i]);outputLog(self.globalWriteBlockList[i].addr+" write completed with quality "+self.globalWriteBlockList[i].writeQuality,1,self.connectionID);if(!isQualityOK(self.globalWriteBlockList[i].writeQuality)){anyBadQualities=true}}self.writeDoneCallback(anyBadQualities)}};function doneSending(element){return element.sent&&element.rcvd?true:false}NodeS7.prototype.readResponse=function(data,foundSeqNum){var self=this,i;var anyBadQualities;var dataPointer=21;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);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(var itemCount=0;itemCount<self.readPacketArray[foundSeqNum].itemList.length;itemCount++){dataPointer=processS7Packet(data,self.readPacketArray[foundSeqNum].itemList[itemCount],dataPointer);if(!dataPointer){outputLog("Received a ZERO RESPONSE Processing Read Packet due to unrecoverable packet error",0,self.connectionID)}}self.readPacketArray[foundSeqNum].reqTime=process.hrtime(self.readPacketArray[foundSeqNum].reqTime);outputLog("Time is "+self.readPacketArray[foundSeqNum].reqTime[0]+" seconds and "+Math.round(self.readPacketArray[foundSeqNum].reqTime[1]*10/1e6)/10+" ms.",1,self.connectionID);if(!self.readPacketArray[foundSeqNum].rcvd){self.readPacketArray[foundSeqNum].rcvd=true;self.parallelJobsNow--}clearTimeout(self.readPacketArray[foundSeqNum].timeout);if(self.readPacketArray.every(doneSending)){for(i=0;i<self.readPacketArray.length;i++){self.readPacketArray[i].sent=false;self.readPacketArray[i].rcvd=false}anyBadQualities=false;for(i=0;i<self.globalReadBlockList.length;i++){var lengthOffset=0;for(var j=0;j<self.globalReadBlockList[i].requestReference.length;j++){self.globalReadBlockList[i].requestReference[j].byteBuffer.copy(self.globalReadBlockList[i].byteBuffer,lengthOffset,0,self.globalReadBlockList[i].requestReference[j].byteLength);self.globalReadBlockList[i].requestReference[j].qualityBuffer.copy(self.globalReadBlockList[i].qualityBuffer,lengthOffset,0,self.globalReadBlockList[i].requestReference[j].byteLength);lengthOffset+=self.globalReadBlockList[i].requestReference[j].byteLength}for(var k=0;k<self.globalReadBlockList[i].itemReference.length;k++){processS7ReadItem(self.globalReadBlockList[i].itemReference[k]);outputLog("Address "+self.globalReadBlockList[i].itemReference[k].addr+" has value "+self.globalReadBlockList[i].itemReference[k].value+" and quality "+self.globalReadBlockList[i].itemReference[k].quality,1,self.connectionID);if(!isQualityOK(self.globalReadBlockList[i].itemReference[k].quality)){anyBadQualities=true;dataObject[self.globalReadBlockList[i].itemReference[k].useraddr]=self.globalReadBlockList[i].itemReference[k].quality}else{dataObject[self.globalReadBlockList[i].itemReference[k].useraddr]=self.globalReadBlockList[i].itemReference[k].value}}}outputLog("We are calling back our readDoneCallback.",1,self.connectionID);if(typeof(self.readDoneCallback==="function")){self.readDoneCallback(anyBadQualities,dataObject)}if(self.resetPending){self.resetNow()}if(!self.isReading()&&self.writeInQueue){self.sendWritePacket()}}else{self.sendReadPacket()}};NodeS7.prototype.onClientDisconnect=function(){var self=this;outputLog("ISO-on-TCP connection DISCONNECTED.",0,self.connectionID);if(!self.connectCBIssued&&typeof self.connectCallback==="function"){self.connectCBIssued=true;self.connectCallback("Error - TCP connected, ISO didn't")}self.connectionReset()};NodeS7.prototype.onClientClose=function(){var self=this;self.connectionCleanup();if(self.dropConnectionCallback){self.dropConnectionCallback();self.dropConnectionCallback=null;clearTimeout(self.dropConnectionTimer)}};NodeS7.prototype.connectionReset=function(){var self=this;self.isoConnectionState=0;self.resetPending=true;outputLog("ConnectionReset is happening");if(!self.isReading()&&typeof self.resetTimeout==="undefined"){self.resetTimeout=setTimeout(function(){self.resetNow.apply(self,arguments)},1500)}};NodeS7.prototype.resetNow=function(){var self=this;self.isoConnectionState=0;self.isoclient.end();outputLog("ResetNOW is happening");self.resetPending=false;if(typeof self.resetTimeout!=="undefined"){clearTimeout(self.resetTimeout);self.resetTimeout=undefined;outputLog("Clearing an earlier scheduled reset")}};NodeS7.prototype.connectionCleanup=function(){var self=this;self.isoConnectionState=0;outputLog("Connection cleanup is happening");if(typeof self.isoclient!=="undefined"){self.isoclient.removeAllListeners("data");self.isoclient.removeAllListeners("error");self.isoclient.removeAllListeners("connect");self.isoclient.removeAllListeners("end");self.isoclient.removeAllListeners("close")}clearTimeout(self.connectTimeout);clearTimeout(self.PDUTimeout);self.clearReadPacketTimeouts();self.clearWritePacketTimeouts()};function S7AddrToBuffer(addrinfo,isWriting){var thisBitOffset=0,theReq=new Buffer([18,10,16,0,0,0,0,0,0,0,0,0]);theReq[3]=2;if(addrinfo.datatype==="X"){theReq.writeUInt16BE(addrinfo.byteLength,4);if(isWriting&&addrinfo.arrayLength===1){theReq[3]=1;thisBitOffset=addrinfo.bitOffset}}else if(addrinfo.datatype==="TIMER"||addrinfo.datatype==="COUNTER"){theReq.writeUInt16BE(1,4);theReq.writeUInt8(addrinfo.areaS7Code,3)}else{theReq.writeUInt16BE(addrinfo.byteLength,4)}theReq.writeUInt16BE(addrinfo.dbNumber,6);theReq.writeUInt32BE(addrinfo.offset*8+thisBitOffset,8);theReq[8]|=addrinfo.areaS7Code;return theReq}function processS7Packet(theData,theItem,thePointer){var remainingLength;if(typeof theData==="undefined"){remainingLength=0;outputLog("Processing an undefined packet, likely due to timeout error")}else{remainingLength=theData.length-thePointer}var prePointer=thePointer;theItem.qualityBuffer=new Buffer(theItem.byteLength);theItem.qualityBuffer.fill(255);if(remainingLength<4){theItem.valid=false;if(typeof theData!=="undefined"){theItem.errCode="Malformed Packet - Less Than 4 Bytes. TDL"+theData.length+"TP"+thePointer+"RL"+remainingLength}else{theItem.errCode="Timeout error - zero length packet"}outputLog(theItem.errCode);return 0}var reportedDataLength;if(theItem.readTransportCode==4){reportedDataLength=theData.readUInt16BE(thePointer+2)/8}else{reportedDataLength=theData.readUInt16BE(thePointer+2)}var responseCode=theData[thePointer];var transportCode=theData[thePointer+1];if(remainingLength==reportedDataLength+2){outputLog("Not last part.")}if(remainingLength<reportedDataLength+2){theItem.valid=false;theItem.errCode="Malformed Packet - Item Data Length and Packet Length Disagree. RDL+2 "+(reportedDataLength+2)+" remainingLength "+remainingLength;outputLog(theItem.errCode);return 0}if(responseCode!==255){theItem.valid=false;theItem.errCode="Invalid Response Code - "+responseCode;outputLog(theItem.errCode);return thePointer+reportedDataLength+4}if(transportCode!==theItem.readTransportCode){theItem.valid=false;theItem.errCode="Invalid Transport Code - "+transportCode;outputLog(theItem.errCode);return thePointer+reportedDataLength+4}var expectedLength=theItem.byteLength;if(reportedDataLength!==expectedLength){theItem.valid=false;theItem.errCode="Invalid Response Length - Expected "+expectedLength+" but got "+reportedDataLength+" bytes.";outputLog(theItem.errCode);return reportedDataLength+2}thePointer+=4;theItem.valid=true;theItem.byteBuffer=theData.slice(thePointer,thePointer+reportedDataLength);theItem.qualityBuffer.fill(192);thePointer+=theItem.byteLength;if((thePointer-prePointer)%2){thePointer+=1}return thePointer}function processS7WriteItem(theData,theItem,thePointer){var remainingLength;if(!theData){theItem.writeQualityBuffer.fill(255);theItem.valid=false;theItem.errCode="We must have timed Out - we have no response to process";outputLog(theItem.errCode);return 0}remainingLength=theData.length-thePointer;if(remainingLength<1){theItem.writeQualityBuffer.fill(255);theItem.valid=false;theItem.errCode="Malformed Packet - Less Than 1 Byte. TDL "+theData.length+" TP"+thePointer+" RL"+remainingLength;outputLog(theItem.errCode);return 0}var writeResponse=theData.readUInt8(thePointer);theItem.writeResponse=writeResponse;if(writeResponse!==255){outputLog("Received write error of "+theItem.writeResponse+" on "+theItem.addr);theItem.writeQualityBuffer.fill(255)}else{theItem.writeQualityBuffer.fill(192)}return thePointer+1}function writePostProcess(theItem){var thePointer=0;if(theItem.arrayLength===1){if(theItem.writeQualityBuffer[0]===255){theItem.writeQuality="BAD"}else{theItem.writeQuality="OK"}}else{theItem.writeQuality=[];for(var arrayIndex=0;arrayIndex<theItem.arrayLength;arrayIndex++){if(theItem.writeQualityBuffer[thePointer]===255){theItem.writeQuality[arrayIndex]="BAD"}else{theItem.writeQuality[arrayIndex]="OK"}if(theItem.datatype=="X"){if((arrayIndex+theItem.bitOffset+1)%8===0||arrayIndex==theItem.arrayLength-1){thePointer+=theItem.dtypelen}}else{thePointer+=theItem.dtypelen}}}}function processS7ReadItem(theItem){var thePointer=0;var strlen=0;if(theItem.arrayLength>1){if(theItem.datatype!="C"&&theItem.datatype!="CHAR"&&theItem.datatype!="S"&&theItem.datatype!="STRING"){theItem.value=[];theItem.quality=[]}else{theItem.value="";theItem.quality=""}var bitShiftAmount=theItem.bitOffset;for(var arrayIndex=0;arrayIndex<theItem.arrayLength;arrayIndex++){if(theItem.qualityBuffer[thePointer]!==192){if(theItem.quality instanceof Array){theItem.value.push(theItem.badValue());theItem.quality.push("BAD "+theItem.qualityBuffer[thePointer])}else{theItem.value=theItem.badValue();theItem.quality="BAD "+theItem.qualityBuffer[thePointer]}}else{if(theItem.quality instanceof Array){theItem.quality.push("OK")}else{theItem.quality="OK"}switch(theItem.datatype){case"REAL":theItem.value.push(theItem.byteBuffer.readFloatBE(thePointer));break;case"DWORD":theItem.value.push(theItem.byteBuffer.readUInt32BE(thePointer));break;case"DINT":theItem.value.push(theItem.byteBuffer.readInt32BE(thePointer));break;case"INT":theItem.value.push(theItem.byteBuffer.readInt16BE(thePointer));break;case"WORD":theItem.value.push(theItem.byteBuffer.readUInt16BE(thePointer));break;case"X":theItem.value.push(theItem.byteBuffer.readUInt8(thePointer)>>bitShiftAmount&1?true:false);break;case"B":case"BYTE":theItem.value.push(theItem.byteBuffer.readUInt8(thePointer));break;case"S":case"STRING":if(arrayIndex===1){strlen=theItem.byteBuffer.readUInt8(thePointer)}if(arrayIndex>1&&arrayIndex<strlen+2){theItem.value+=String.fromCharCode(theItem.byteBuffer.readUInt8(thePointer))}break;case"C":case"CHAR":theItem.value+=String.fromCharCode(theItem.byteBuffer.readUInt8(thePointer));break;case"TIMER":case"COUNTER":theItem.value.push(theItem.byteBuffer.readInt16BE(thePointer));break;default:outputLog("Unknown data type in response - should never happen. Should have been caught earlier. "+theItem.datatype);return 0}}if(theItem.datatype=="X"){bitShiftAmount++;if((arrayIndex+theItem.bitOffset+1)%8===0||arrayIndex==theItem.arrayLength-1){thePointer+=theItem.dtypelen;bitShiftAmount=0}}else{thePointer+=theItem.dtypelen}}}else{if(theItem.qualityBuffer[thePointer]!==192){theItem.value=theItem.badValue();theItem.quality="BAD "+theItem.qualityBuffer[thePointer]}else{theItem.quality="OK";switch(theItem.datatype){case"REAL":theItem.value=theItem.byteBuffer.readFloatBE(thePointer);break;case"DWORD":theItem.value=theItem.byteBuffer.readUInt32BE(thePointer);break;case"DINT":theItem.value=theItem.byteBuffer.readInt32BE(thePointer);break;case"INT":theItem.value=theItem.byteBuffer.readInt16BE(thePointer);break;case"WORD":theItem.value=theItem.byteBuffer.readUInt16BE(thePointer);break;case"X":theItem.value=theItem.byteBuffer.readUInt8(thePointer)>>theItem.bitOffset&1?true:false;break;case"B":case"BYTE":theItem.value=theItem.byteBuffer.readUInt8(thePointer);break;case"C":case"CHAR":theItem.value=String.fromCharCode(theItem.byteBuffer.readUInt8(thePointer));break;case"TIMER":case"COUNTER":theItem.value=theItem.byteBuffer.readInt16BE(thePointer);break;default:outputLog("Unknown data type in response - should never happen. Should have been caught earlier. "+theItem.datatype);return 0}}thePointer+=theItem.dtypelen}if(thePointer%2){thePointer+=1}return thePointer}function getWriteBuffer(theItem){var newBuffer;if(theItem.datatype==="X"&&theItem.arrayLength===1){newBuffer=new Buffer(2+3);newBuffer.fill(0);newBuffer.writeUInt16BE(1,2)}else{newBuffer=new Buffer(theItem.byteLength+4);newBuffer.fill(0);newBuffer.writeUInt16BE(theItem.byteLength*8,2)}if(theItem.writeBuffer.length<theItem.byteLengthWithFill){outputLog("Attempted to access part of the write buffer that wasn't there when writing an item.")}newBuffer[0]=0;newBuffer[1]=theItem.writeTransportCode;theItem.writeBuffer.copy(newBuffer,4,0,theItem.byteLength);return newBuffer}function bufferizeS7Item(theItem){var thePointer,theByte;theByte=0;thePointer=0;if(theItem.arrayLength>1){var bitShiftAmount=theItem.bitOffset;for(var arrayIndex=0;arrayIndex<theItem.arrayLength;arrayIndex++){switch(theItem.datatype){case"REAL":theItem.writeBuffer.writeFloatBE(theItem.writeValue[arrayIndex],thePointer);break;case"DWORD":theItem.writeBuffer.writeInt32BE(theItem.writeValue[arrayIndex],thePointer);break;case"DINT":theItem.writeBuffer.writeInt32BE(theItem.writeValue[arrayIndex],thePointer);break;case"INT":theItem.writeBuffer.writeInt16BE(theItem.writeValue[arrayIndex],thePointer);break;case"WORD":theItem.writeBuffer.writeUInt16BE(theItem.writeValue[arrayIndex],thePointer);break;case"X":theByte=theByte|(theItem.writeValue[arrayIndex]===true?1:0)<<bitShiftAmount;theItem.writeBuffer.writeUInt8(theByte,thePointer);bitShiftAmount++;break;case"B":case"BYTE":theItem.writeBuffer.writeUInt8(theItem.writeValue[arrayIndex],thePointer);break;case"C":case"CHAR":theItem.writeBuffer.writeUInt8(theItem.writeValue.charCodeAt(arrayIndex),thePointer);break;case"S":case"STRING":if(arrayIndex===0){theItem.writeBuffer.writeUInt8(theItem.arrayLength-2,thePointer)}else if(arrayIndex===1){theItem.writeBuffer.writeUInt8(Math.min(theItem.arrayLength-2,theItem.writeValue.length),thePointer)}else if(arrayIndex>1&&arrayIndex<theItem.writeValue.length+2){theItem.writeBuffer.writeUInt8(theItem.writeValue.charCodeAt(arrayIndex-2),thePointer)}else{theItem.writeBuffer.writeUInt8(32,thePointer)}break;case"TIMER":case"COUNTER":theItem.writeBuffer.writeInt16BE(theItem.writeValue[arrayIndex],thePointer);break;default:outputLog("Unknown data type when preparing array write packet - should never happen. Should have been caught earlier. "+theItem.datatype);return 0}if(theItem.datatype=="X"){if((arrayIndex+theItem.bitOffset+1)%8===0||arrayIndex==theItem.arrayLength-1){thePointer+=theItem.dtypelen;bitShiftAmount=0;theByte=0}}else{thePointer+=theItem.dtypelen}}}else{switch(theItem.datatype){case"REAL":theItem.writeBuffer.writeFloatBE(theItem.writeValue,thePointer);break;case"DWORD":theItem.writeBuffer.writeUInt32BE(theItem.writeValue,thePointer);break;case"DINT":theItem.writeBuffer.writeInt32BE(theItem.writeValue,thePointer);break;case"INT":theItem.writeBuffer.writeInt16BE(theItem.writeValue,thePointer);break;case"WORD":theItem.writeBuffer.writeUInt16BE(theItem.writeValue,thePointer);break;case"X":theItem.writeBuffer.writeUInt8(theItem.writeValue===true?1:0,thePointer);break;case"B":case"BYTE":theItem.writeBuffer.writeUInt8(theItem.writeValue,thePointer);break;case"C":case"CHAR":theItem.writeBuffer.writeUInt8(String.toCharCode(theItem.writeValue),thePointer);break;case"TIMER":case"COUNTER":theItem.writeBuffer.writeInt16BE(theItem.writeValue,thePointer);break;default:outputLog("Unknown data type in write prepare - should never happen. Should have been caught earlier. "+theItem.datatype);return 0}thePointer+=theItem.dtypelen}return undefined}function stringToS7Addr(addr,useraddr){"use strict";var theItem,splitString,splitString2;if(useraddr==="_COMMERR"){return undefined}theItem=new S7Item;splitString=addr.split(",");if(splitString.length===0||splitString.length>2){outputLog("Error - String Couldn't Split Properly.");return undefined}if(splitString.length>1){theItem.addrtype="DB";splitString2=splitString[1].split(".");theItem.datatype=splitString2[0].replace(/[0-9]/gi,"").toUpperCase();if(theItem.datatype==="X"&&splitString2.length===3){theItem.arrayLength=parseInt(splitString2[2],10)}else if(theItem.datatype!=="X"&&splitString2.length===2){theItem.arrayLength=parseInt(splitString2[1],10)}else{theItem.arrayLength=1}if(theItem.arrayLength<=0){outputLog("Zero length arrays not allowed, returning undefined");return undefined}theItem.dbNumber=parseInt(splitString[0].replace(/[A-z]/gi,""),10);theItem.offset=parseInt(splitString2[0].replace(/[A-z]/gi,""),10);if(splitString2.length>1&&theItem.datatype==="X"){theItem.bitOffset=parseInt(splitString2[1],10);if(theItem.bitOffset>7){outputLog("Invalid bit offset specified for address "+addr);return undefined}}}else{splitString2=addr.split(".");switch(splitString2[0].replace(/[0-9]/gi,"")){case"PAW":case"PIW":case"PEW":case"PQW":theItem.addrtype="P";theItem.datatype="INT";break;case"PAD":case"PID":case"PED":case"PQD":theItem.addrtype="P";theItem.datatype="DINT";break;case"PAB":case"PIB":case"PEB":case"PQB":theItem.addrtype="P";theItem.datatype="BYTE";break;case"IB":case"IC":case"EB":case"EC":theItem.addrtype="I";theItem.datatype="BYTE";break;case"IW":case"EW":case"II":case"EI":theItem.addrtype="I";theItem.datatype="INT";break;case"QW":case"AW":case"QI":case"AI":theItem.addrtype="Q";theItem.datatype="INT";break;case"MB":case"MC":theItem.addrtype="M";theItem.datatype="BYTE";break;case"M":theItem.addrtype="M";theItem.datatype="X";break;case"I":case"E":theItem.addrtype="I";theItem.datatype="X";break;case"Q":case"A":theItem.addrtype="Q";theItem.datatype="X";break;case"MW":case"MI":theItem.addrtype="M";theItem.datatype="INT";break;case"MDW":case"MDI":case"MD":theItem.addrtype="M";theItem.datatype="DINT";break;case"MR":theItem.addrtype="M";theItem.datatype="REAL";break;case"T":theItem.addrtype="T";theItem.datatype="TIMER";break;case"C":theItem.addrtype="C";theItem.datatype="COUNTER";break;default:outputLog("Failed to find a match for "+splitString2[0]);return undefined}theItem.bitOffset=0;if(splitString2.length>1&&theItem.datatype==="X"){theItem.bitOffset=parseInt(splitString2[1].replace(/[A-z]/gi,""),10);if(splitString2.length>2){theItem.arrayLength=parseInt(splitString2[2].replace(/[A-z]/gi,""),10)}else{theItem.arrayLength=1}}if(splitString2.length>1&&theItem.datatype!=="X"){theItem.arrayLength=parseInt(splitString2[1].replace(/[A-z]/gi,""),10)}else{theItem.arrayLength=1}theItem.dbNumber=0;theItem.offset=parseInt(splitString2[0].replace(/[A-z]/gi,""),10)}if(theItem.datatype==="DI"){theItem.datatype="DINT"}if(theItem.datatype==="I"){theItem.datatype="INT"}if(theItem.datatype==="DW"){theItem.datatype="DWORD"}if(theItem.datatype==="R"){theItem.datatype="REAL"}switch(theItem.datatype){case"REAL":case"DWORD":case"DINT":theItem.dtypelen=4;break;case"INT":case"WORD":case"TIMER":case"COUNTER":theItem.dtypelen=2;break;case"X":case"B":case"C":case"BYTE":case"CHAR":theItem.dtypelen=1;break;case"S":case"STRING":theItem.arrayLength+=2;theItem.dtypelen=1;break;default:outputLog("Unknown data type "+theItem.datatype);return undefined}theItem.readTransportCode=4;switch(theItem.addrtype){case"DB":case"DI":theItem.areaS7Code=132;break;case"I":case"E":theItem.areaS7Code=129;break;case"Q":case"A":theItem.areaS7Code=130;break;case"M":theItem.areaS7Code=131;break;case"P":theItem.areaS7Code=128;break;case"C":theItem.areaS7Code=28;theItem.readTransportCode=9;break;case"T":theItem.areaS7Code=29;theItem.readTransportCode=9;break;default:outputLog("Unknown memory area entered - "+theItem.addrtype);return undefined}if(theItem.datatype==="X"&&theItem.arrayLength===1){theItem.writeTransportCode=3}else{theItem.writeTransportCode=theItem.readTransportCode}theItem.addr=addr;if(useraddr===undefined){theItem.useraddr=addr}else{theItem.useraddr=useraddr}if(theItem.datatype==="X"){theItem.byteLength=Math.ceil((theItem.bitOffset+theItem.arrayLength)/8)}else{theItem.byteLength=theItem.arrayLength*theItem.dtypelen}theItem.byteLengthWithFill=theItem.byteLength;if(theItem.byteLengthWithFill%2){theItem.byteLengthWithFill+=1}return theItem}function S7Packet(){this.seqNum=undefined;this.itemList=undefined;this.reqTime=undefined;this.sent=false;this.rcvd=false;this.timeoutError=undefined;this.timeout=undefined}function S7Item(){this.addr=undefined;this.useraddr=undefined;this.addrtype=undefined;this.datatype=undefined;this.dbNumber=undefined;this.bitOffset=undefined;this.offset=undefined;this.arrayLength=undefined;this.dtypelen=undefined;this.areaS7Code=undefined;this.byteLength=undefined;this.byteLengthWithFill=undefined;this.readTransportCode=undefined;
this.writeTransportCode=undefined;this.byteBuffer=new Buffer(8192);this.writeBuffer=new Buffer(8192);this.qualityBuffer=new Buffer(8192);this.writeQualityBuffer=new Buffer(8192);this.value=undefined;this.writeValue=undefined;this.valid=false;this.errCode=undefined;this.part=undefined;this.maxPart=undefined;this.isOptimized=false;this.resultReference=undefined;this.itemReference=undefined;this.clone=function(){var newObj=new S7Item;for(var i in this){if(i=="clone")continue;newObj[i]=this[i]}return newObj};this.badValue=function(){switch(this.datatype){case"REAL":return 0;case"DWORD":case"DINT":case"INT":case"WORD":case"B":case"BYTE":case"TIMER":case"COUNTER":return 0;case"X":return false;case"C":case"CHAR":case"S":case"STRING":return"";default:outputLog("Unknown data type when figuring out bad value - should never happen. Should have been caught earlier. "+this.datatype);return 0}}}function itemListSorter(a,b){if(a.areaS7Code<b.areaS7Code){return-1}if(a.areaS7Code>b.areaS7Code){return 1}if(a.offset<b.offset){return-1}if(a.offset>b.offset){return 1}if(a.bitOffset<b.bitOffset){return-1}if(a.bitOffset>b.bitOffset){return 1}if(a.byteLength>b.byteLength){return-1}if(a.byteLength<b.byteLength){return 1}}function doNothing(arg){return arg}function isQualityOK(obj){if(typeof obj==="string"){if(obj!=="OK"){return false}}else if(Array.isArray(obj)){for(var i=0;i<obj.length;i++){if(typeof obj[i]!=="string"||obj[i]!=="OK"){return false}}}return true}function outputLog(txt,debugLevel,id){if(silentMode)return;var idtext;if(typeof id==="undefined"){idtext=""}else{idtext=" "+id}if(typeof debugLevel==="undefined"||effectiveDebugLevel>=debugLevel){console.log("["+process.hrtime()+idtext+"] "+util.format(txt))}}}).call(this,require("_process"),require("buffer").Buffer)},{_process:6,buffer:2,net:1,util:9}]},{},[]);var nodes7=require("nodes7");var conn=new nodes7;var doneReading=false;var doneWriting=false;var variables={CONTADORT1:"DB10,INT10.1",CONTADORT2:"DB0,D10,"};conn.initiateConnection({port:102,host:"10.0.2.1",rack:1,slot:0},connected);function connected(err){if(typeof err!=="undefined"){console.log(err);process.exit()}conn.setTranslationCB(function(tag){return variables[tag]});conn.addItems("CONTADORT2");conn.writeItems("CONTADORT2",[121],valuesWritten);conn.readAllItems(valuesReady)}function valuesReady(anythingBad,values){if(anythingBad){console.log("SOMETHING WENT WRONG READING VALUES!!!!")}console.log(values);doneReading=true;if(doneWriting){process.exit()}}function valuesWritten(anythingBad){if(anythingBad){console.log("SOMETHING WENT WRONG WRITING VALUES!!!!")}console.log("Done writing.");doneWriting=true;if(doneReading){process.exit()}}},0);{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"nodes7": "0.1.10"
}
}<!-- contents of this file will be placed inside the <body> -->
<!-- contents of this file will be placed inside the <head> -->
made with requirebin