UNPKG

i6-s7ip

Version:
135 lines (103 loc) 2.7 kB
var util = require('util'); var nodeS7 = require('nodes7'); module.exports = device; function device(params){ nodeS7.call(this, {silent:true}); this.updateInterval = typeof(params.cycle)=='undefined'? 1000 : params.cycle; this.name = params.name; this.properties = { host : params.host, port : params.port, rack : params.rack, slot : params.slot }; this.enabled = params.enabled; this.connected = false; //Save tag properties this.tags = {}; params.tags.forEach(tag=>{ this.tags[tag.name] = tag; }); } //Inherits nodeS7 class util.inherits(device, nodeS7); //method var method = device.prototype; method.connect = function(cb){ //pass callback this.connect_cb = cb; //Start PLC connection if(this.enabled){ sails.log.info('[i6-device][' + this.name + '] connecting...'); this.initiateConnection(this.properties, this._connectionHandler); }else{ sails.log.warn('[i6-device][' + this.name + '] is disabled'); cb(); } } method.disconnect = function(){ this.dropConnection(function(){ }); } method._connectionHandler = function(err){ if (typeof(err) !== "undefined") { //log connection status sails.log.error('[i6-device][' + this.name + '] connection timeout'); //call next async this.connect_cb(); //save connection state this.isConnected = false; //break proccess return; } //log connection status sails.log.info('[i6-device][' + this.name + '] connected'); //call next async this.connect_cb(); //save connection state this.isConnected = true; this.items = ["_COMMERR"]; var tagsKey = Object.keys(this.tags); tagsKey.forEach(tagName=>{ this.items.push(tagName); }); this.setTranslationCB(function(tag){ return this.tags[tag].address; }); this.addItems(this.items); //Read all tags value if(this.enabled){ var interval = this.updateInterval; var conn = this; if(!this.timerUpdate){ setInterval(function(){ conn.readAllItems(valueReady); }, interval); } } //old read interval method /* var conn = this; setInterval(function(){ conn.readAllItems(valueReady); }, 500); */ } //Tulis val ke addr PLC method.writeToDevice = function(addr, val){ if(this.isoConnectionState==4){ this.writeItems(addr, val); } } function valueReady (err,values){ if (err) { sails.log.error("[i6-device][" + this.name + '] something wrong when read values!'); } var keys = Object.keys(values); keys.forEach(key=>{ //Save previous value var _previous = i6.tags[key]; //Update tags variable i6.tags[key].value = err? 0 : values[key]; i6.tags[key].timestamp = new Date(); i6.tags[key].status = err? "BAD" : "GOOD"; }); }