summaryrefslogtreecommitdiff
path: root/routes/routes.js
blob: cd0075413b3a846c8914ecab011c5c298fa60ed9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
module.exports = function(express,app,fs,os,io,PythonShell,scriptPath){
	console.log("Server started!!! ");	

	var router = express.Router();
	var pyEnv = '/usr/bin/python'

	router.get('/',function(req,res,next){
        res.render('index',{host:app.get('host'),title:'Ngspice Simulator'});
    
    });

	io.on('connection', function (socket) {
		socketID = getSocketID(socket);
		var plot_allv_file = '/tmp/plot_allv_'+socketID.toLowerCase()+'.txt'
		var fileName = '/tmp/'+socketID+'.cir.out';
  		socket.emit('loadingPage', 'User with socket ID '+socket.id+' is Connected');
  		
  		socket.on('user', function (data) {
  			console.log('Socket ID : '+data['socketID']);
  		});

  		socket.on('netlist',function(data){
  			netlistContent = data['netlist'];
  			
  			//Plotting List
  			plotList = data['plotList'];
  			console.log("PlotList----------->"+plotList);
		
			plotOption = plotList.join(" "); //Space is required between two plot

			if (!plotOption.length>0){
				plotOption='allv'
			}
			
			
			// socket.emit('serverMessage','Recived message for client '+socketID);
			fs.writeFile(fileName, netlistContent, function (err) {
				if (err){
					return console.log(err);
				} 
  				console.log('File is stored at '+fileName);
  				fs.exists(fileName, function(exists) {
    				if (exists) {
      					addPlotDetails(fileName,plotOption);
      					executeNgspiceNetlist(fileName);
      					
    				}
  					});
			});

			
		});	
		
		socket.on('disconnect',function(){
			console.log("Client "+socketID+" disconnected");
			fs.exists(fileName, function(exists) {
				if (exists) {
					//Deleting ngspice file
					deleteNetlistFile(fileName);
				}
			});

			fs.exists(plot_allv_file, function(exists) {
				// console.log("Check Plot allv "+plot_allv_file)
				if (exists) {
					console.log("Check Plot allv files")
					//Deleting plot allv file
					deleteNetlistFile(plot_allv_file);
				}
			});

			

		});

		function addPlotDetails(fileName,plotOption)
		{
			
			//Adding Plot component in a file
			sed('-i', 'run', 'run \n print '+plotOption+' > /tmp/plot_allv_'+socketID+'.txt \n' , fileName);

		}

		function executeNgspiceNetlist(fileName)
		{
			fs.exists(fileName, function(exists) {
				if (exists) {
					exec('ngspice '+fileName, function(code, stdout, stderr) {
  					console.log('Exit code:', code);
  					console.log('Program output:', stdout);
  					console.log('Program stderr:', stderr);

	  				if(stderr){
	  					switch(stderr){
	  						case (stderr.match(/Error/) || stderr.match(/error/)||{}).input:
	  							console.log("Error in executing ngspice netlist");        
	  							socket.emit('clearPlot','clearPlot');
	  							socket.emit('serverMessage',{"stderr":stderr,"stdout":stdout});
	  								
	  							break;
	  						default:
	  							parsePlotData()
	  							break;
	  					}
	  					
	  				}
	  				else{
	  					parsePlotData()
	  				}
					
					});
				}
			});
				
		}

		function parsePlotData(){
			console.log("Ngspice netlist executed successfully "+fileName);
			//socket.emit('serverMessage','Ngspice netlist executed successfully: ');	
			//var analysisInfo = grep('.tran|.dc|.ac', fileName); //Not reliable
			var analysisInfo = getAnalysisInfo(fileName);
			console.log("Analysis :"+analysisInfo)
			var options = {
				mode: 'json',
  				pythonPath: pyEnv,
  				pythonOptions: ['-u'],
  				scriptPath: scriptPath,
  				args: [analysisInfo, plot_allv_file]
			};
 
			PythonShell.run('parser.py', options, function (err, results) {
  			if (err) throw err;
  				// results is an array consisting of messages collected during execution 
 			// console.log('results: %j', results);
 			var resultString = results[0];
 			
 			//Emitting Data Points to client
 			socket.emit('plotData',resultString);
 			
			});
		}

		function getSocketID(socket){
			socketID = socket.id;
			//Removing first two char i.e '/#' from socket id
			socketID = socketID.substring(2);
			console.log("Return :"+socketID)
			return socketID;
		}

		function deleteNetlistFile(fileName){
			console.log("Delete File "+fileName)
   			fs.unlink(fileName, function(err){
   				if (err) return console.log("Error while deleting ngspice file :"+err);
				console.log("success");
			});
			
		}

		function getAnalysisInfo(fileName){
			var analysisType;
			fs.readFileSync(fileName).toString().split('\n').forEach(function (line) {
				line = line.trim();
				if(line.startsWith(".ac")||line.startsWith(".tran")||line.startsWith(".dc")){
					analysisType = line;
				}
				
			});
			return analysisType;
		}

	});

	app.use('/',router);
}