const express = require("express"); const execSync = require('child_process').execSync; var parser = require('xml2json'); const fs = require('fs'); var cors = require('cors'); const bodyParser = require("body-parser"); var mysql = require('mysql2/promise'); const bluebird = require('bluebird'); const app = express(); app.use(cors()); const port = 3001; app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); let conf = { connectionLimit : 10, host : '127.0.0.1', user : 'ds', password : 'EmcoAdmin!', database : 'modeler', Promise: bluebird } const jsn = require("./base.json"); const di = require("./di.json"); const ia = require("./ia.json"); const mach = require("./machinery.json"); const mt = require("./mt.json"); let ns_array = []; let nsray = []; nsray.push(jsn); nsray.push(di); nsray.push(ia); nsray.push(mach); nsray.push(mt); /* async function gen_query(sql, params){ const connection = await mysql.createConnection(conf); const [results, ] = await connection.execute(sql, params); //console.log(results); return results; }*/ function database_connection() { pool = mysql.createPool(conf); pool.getConnection(function(err, connection) { if(err) { logger.error('[ERROR] Connecting to database "' + err.toString() + '"'); setTimeout(function() { database_connection(); }, 2500); } else { pool.query('SET NAMES utf8'); pool.query('SET CHARACTER SET utf8'); logger.trace('[INFO] Connected to database and set utf8!'); } })}; database_connection(); function inverse(dev){ if("IsForward" in dev){ if(dev.IsForward === "false"){ return true; }else{ return false; } }else{ return false; } } function forward(dev){ var b = true; if("IsForward" in dev){ if(dev.IsForward === "false"){ b = false; } }else{ b = true; } return b; } function sortNS(files){ let nsets = []; for(let x = 0; x{ try{ var namejs = req.params["name"]; var shorty = req.params["ident"]; const id = "./"+namejs+".json"; const fl = require(id); for(let i = 0; i < ns_array.length; i++){ if(ns_array[i][1] === shorty){ return res.json({result:"Array already includes element."}) } } ns_array.push([fl, shorty, fl.UANodeSet.Models.Model.ModelUri]); res.json({result:"OK"}); }catch(err){ console.log("NOK"); res.json({result:"NOK", error: "Json file may not be available. Call list json files."}); } }) app.get('/shownsarray',(req, res) =>{ try{ let str = ''; for(let i = 0; i < ns_array.length; i++){ str += '('+i+': '+ns_array[i][1]+')'; } res.json({result:str}); console.log(ns_array); }catch(err){ console.log("NOK"); res.json({result:"NOK", error: "Json file may not be available. Call list json files."}); } }) app.get('/getredis',(req, res) =>{ try{ redis_get(); res.json({result:"OK"}); }catch(err){ console.log("NOK"); res.json({result:"NOK"}); } }) app.get('/get_root',(req, res) =>{ try{ let rt = jsn.UANodeSet.UAObject.find( record => record.NodeId === "i=84"); let resj = { id: rt.NodeId, parent: "#", text: rt.DisplayName}; res.json(resj); }catch(err){ console.log("NOK"); res.json({result:"NOK"}); } }) app.get('/get_children/base/:id',(req, res) =>{ var nid = req.params["id"]; try{ if(Array.isArray(jsn.UANodeSet.UAObject)){ for (let i = 0; i < jsn.UANodeSet.UAObject.length;i++){ if(Array.isArray(jsn.UANodeSet.UAObject[i].References.Reference)){ for (let x = 0; x < jsn.UANodeSet.UAObject[i].References.Reference.length;x++){ if(jsn.UANodeSet.UAObject[i].References.Reference[x].$t === nid){ console.log(jsn.UANodeSet.UAObject[i].BrowseName + inverse(jsn.UANodeSet.UAObject[i].References.Reference[x]) +jsn.UANodeSet.UAObject[i].References.Reference[x].ReferenceType); } } }else{ if(jsn.UANodeSet.UAObject[i].References.Reference.$t === nid){ console.log(jsn.UANodeSet.UAObject[i].BrowseName + inverse(jsn.UANodeSet.UAObject[i].References.Reference) +jsn.UANodeSet.UAObject[i].References.Reference.ReferenceType); } } } }else{ if(Array.isArray(jsn.UANodeSet.UAObject.References.Reference)){ for (let x = 0; x < jsn.UANodeSet.UAObject.References.Reference.length;x++){ if(jsn.UANodeSet.UAObject[i].References.Reference[x].$t === nid){ console.log(jsn.UANodeSet.UAObject[i].BrowseName + inverse(jsn.UANodeSet.UAObject.References.Reference[x]) +jsn.UANodeSet.UAObject.References.Reference[x].ReferenceType); } } }else{ if(jsn.UANodeSet.UAObject.References.Reference.$t === nid){ console.log(jsn.UANodeSet.UAObject.BrowseName + inverse(jsn.UANodeSet.UAObject.References.Reference) +jsn.UANodeSet.UAObject.References.Reference.ReferenceType); } } } console.log(''); res.json({result:"OK"}); }catch(err){ console.log("NOK"); res.json({result:"NOK"}); } }) app.get('/get_children/all/:ns/:id',(req, res) =>{ var ret_obj = []; var ns = req.params["ns"]; var id = req.params["id"]; var nid = 'ns='+ns+';'+'i='+id; console.log(nid); get_Children(di, nid, ret_obj); get_Children(ia, nid, ret_obj); get_Children(mach, nid, ret_obj); get_Children(mt, nid, ret_obj); res.json(ret_obj); }) app.get('/getNode/all/:ns/:id',(req, res) =>{ var ret_obj = []; var ns = req.params["ns"]; var id = req.params["id"]; var nid = 'ns='+ns+';'+'i='+id; console.log(nid); get_Children(di, nid, ret_obj); get_Children(ia, nid, ret_obj); get_Children(mach, nid, ret_obj); get_Children(mt, nid, ret_obj); let node = { id:nid, text: "home", children:ret_obj } res.json(node); }) app.get('/flushall',(req, res) =>{ redis_flush(); res.json({result:"OK"}); }) app.get('/p2json/:nodeset/:ident',(req, res) =>{ var name = req.params["nodeset"]; var shorty = req.params["ident"]; p2json(name, shorty); res.json({result:"OK"}); }) app.get('/list_projects', (req, res) => { //reacts to requests -> /list_projects const output = execSync("cd .. && cd Projects && ls", { encoding: 'utf-8' }); var out = output.split("\n"); if(out[out.length-1] === ""){ out.splice(-1,1); } console.log("Response: ", out); res.json({result:out}); }) app.get('/list_nodesets', (req, res) => { //reacts to requests -> /list_nodesets const output = execSync("cd .. && cd nodesets && ls", { encoding: 'utf-8' }); var out = output.split("\n"); var result = []; for(let i = 0; i < out.length; i++){ if(out[i].includes(".xml")){ result.push(out[i]); } } console.log("Response: ", result); res.json({result:result}); }) app.get('/new_project', (req, res) => { //reacts to requests -> /new_project?name=myproject const name = req.query.name; //project name const output = execSync("cd .. && cd Projects && ls", { encoding: 'utf-8' }); var out = output.split("\n"); var result = ""; var err = "Error - Project already exists."; for(let i = 0; i < out.length; i++){ if(out[i] === name){ return res.json({result:err}); } } const dir = execSync("cd .. && cd Projects && mkdir "+name, { encoding: 'utf-8' }); var cp = execSync("sudo cp /home/pi/ModelingTool/nodesets/Opc.Ua.NodeSet2.xml /home/pi/ModelingTool/Projects/"+name+"/Opc.Ua.NodeSet2.xml", { encoding: 'utf-8' }); cp = execSync("sudo cp /home/pi/ModelingTool/nodesets/Opc.Ua.NodeSet2.json /home/pi/ModelingTool/Projects/"+name+"/Opc.Ua.NodeSet2.json", { encoding: 'utf-8' }); const cur_dir = execSync("cd .. && cd Projects && cd "+name+" && ls", { encoding: 'utf-8' }); console.log("New Project was created."); res.json({result:cur_dir}); }) app.get('/save_project', (req, res) => { //reacts to requests -> /save_project?name=myproject const name = req.query.name; //project name const output = execSync("sudo cp /var/www/html/root.json /home/pi/ModelingTool/Projects/"+name+"/"+name+".json", { encoding: 'utf-8' }); console.log("Project "+name+" was saved."); res.json({result:"Project saved"}); }) app.get('/load_json', (req, res) => { //reacts to requests -> /load_json?name=myproject const name = req.query.name; //project name var output = execSync("cd .. && cd Projects && ls", { encoding: 'utf-8' }); var out = output.split("\n"); var result = ""; var err = "Error - Project or file not available."; for(let i = 0; i < out.length; i++){ if(out[i] === name){ var output1 = execSync("cd .. && cd Projects && cd "+name+" && ls", { encoding: 'utf-8' }); var out1 = output1.split("\n"); var chk = name+".json" for(let y = 0; y < out1.length; y++){ if(out1[y] === chk){ result = execSync("sudo cp /home/pi/ModelingTool/Projects/"+name+"/"+name+".json /var/www/html/root.json", { encoding: 'utf-8' }); console.log("Project has been loaded."); return res.json({result:"Project loaded"}); } } } } res.json({result:err}); }) app.get('/root', (req, res) => { //reacts to requests -> /root console.log("Return root."); res.json([{id:"i=84",text:"Root",children:[{id:"i=85",text:"Objects",children:true},{id:"i=86",text:"Types", icon : "/variable_node.svg", children:true},{id:"i=87",text:"View",children:false}]}]); }) function isChildRef(obj){ if('IsForward' in obj && obj.IsForward === 'false'){ return false; } if('IsForward' in obj && obj.IsForward === 'true'){ switch (obj.ReferenceType) { case 'Organizes': return true; case 'HasComponent': return true; case 'HasProperty': return true; case 'HasAddIn': return true; case 'HasSubtype': return true; default: return false; } } switch (obj.ReferenceType) { case 'Organizes': return true; case 'HasComponent': return true; case 'HasProperty': return true; case 'HasAddIn': return true; case 'HasSubtype': return true; default: return false; } return false; } function checkDouble(item, obj){ for(let i = 0; i < obj.length; i++){ if(item.id === obj[i].id){ return true; } } return false; } app.get('/lazy', (req, res) => { //console.log(req); var ret_obj = []; let node = {}; if(req.query.id == "#"){ //res.json([{id:"i=84",text:"Root",data:{nodeclass:"Object"},children:true}]); res.json([{id:"i=84",text:"Root",data:{nodeclass:"Object"},children:[{id:"i=85",text:"Objects",data:{nodeclass:"Objects"},children:true},{id:"i=86",text:"Types", data:{nodeclass:"Objects"},children:true},{id:"i=87",text:"View",data:{nodeclass:"Objects"},children:true}]}]); } var nid = req.query.id; node = searchNode(nid); if(node.data.references != null){ console.log("Here:"+node.data.references); if(Array.isArray(node.data.references.Reference)){ console.log("And:"+node.data.references.Reference); for(let x = 0; x < node.data.references.Reference.length; x++ ){ if(isChildRef(node.data.references.Reference[x])){ var cnode = searchNode(node.data.references.Reference[x].$t); if(!checkDouble(cnode,ret_obj)){ ret_obj.push(cnode); } } } }else{ console.log("But:"+node.data.references); if(isChildRef(node.data.references)){ var cnode = searchNode(node.data.references.$t); if(!checkDouble(cnode,ret_obj)){ ret_obj.push(cnode); } } } } getAllChildren(nid, ret_obj); console.log(ret_obj); res.json(ret_obj); }); app.get('/index/:ns1/:ns2', (req, res) => { var n1 = req.params["ns1"]; var n2 = req.params["ns2"]; var num = getIndexObj(ns_array[n1][0],ns_array[n2][0]); console.log(getNode(ns_array[3][0],2,15048)); res.send("Index of "+ns_array[n2][1]+' in '+ns_array[n1][1]+' is '+num); }); app.get('/test/:id', (req, res) => { //test var n1 = parseInt(req.params["id"]); console.log(ns_array[n1][1],); var ret = searchNode("i=85"); console.log(ret); res.send("All good"); //res.json([{id:"i=84",text:"Root",children:[{id:"i=85",text:"Objects",children:true},{id:"i=86",text:"Types", children:true},{id:"i=87",text:"View",children:false}]}]); }) app.get('/require/all', (req, res) => { //test ns_array.push([jsn, "base", jsn.UANodeSet.Models.Model.ModelUri]); ns_array.push([di, "di", di.UANodeSet.Models.Model.ModelUri]); ns_array.push([ia, "ia", ia.UANodeSet.Models.Model.ModelUri]); ns_array.push([mach, "mach", mach.UANodeSet.Models.Model.ModelUri]); ns_array.push([mt, "mt", mt.UANodeSet.Models.Model.ModelUri]); res.json({result:"OK"}); }) app.listen(port, () => { console.log("Server listening at http://localhost:", port); })