This repository was archived by the owner on Feb 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwwwattd
executable file
·368 lines (299 loc) · 10.2 KB
/
wwwattd
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#!/usr/bin/env node
/*
*
* Copyright 2013, Stéphane Desneux <sdx@kooltux.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
var _=require('underscore');
var util=require('util');
var logger=require('winston');
var path=require("path");
var fs=require("fs");
var WattMeter=require("./yoctowatt.js");
var express = require('express');
var http = require('http');
var DEBUG=true;
/*************************************** wwwserver **************************************/
var WWWServer=function(opts) {
var cfg=_.extend({
// listen port
port: 8080,
confdir: 'etc',
htdocs: 'htdocs',
timeout: 5000,
title: "WWWATT Server"
},opts || {});
// resolve confdir and htdocs dir
cfg.confdir=path.resolve(__dirname,cfg.confdir);
cfg.htdocs=path.resolve(__dirname,cfg.htdocs);
DEBUG && logger.debug("Creating www server with config: "+util.inspect(cfg));
_.extend(this,cfg);
this.wmeter=new WattMeter("any");
this.wmeter.on("connect",function() { logger.info("WattMeter connected: ",this.device); });
this.wmeter.on("disconnect",function() { logger.info("WattMeter disconnected"); });
}
WWWServer.prototype.listen=function(cb) {
this._configure();
this._server=http.createServer(this._app);
// configure socketio
this._configure_socketio(this._server);
var self=this;
this._server.listen(this.port,function() {
logger.info("Listening on port "+self.port);
if (cb) cb.call(null,null,this._server,this._app); // cb(err,server,app)
});
}
WWWServer.prototype._configure=function() {
var app=this._app=express();
/******** express configuration **********/
// init view engine
app.set('title', this.title);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// logger, timeout, error handler ...
app.use(express.timeout(this.timeout));
if (DEBUG) {
app.use(express.logger({
format: 'short',
stream: {
write: function() {
logger.debug(Array.prototype.join.call(arguments).trimRight());
}
}
}));
app.use(express.errorHandler());
}
// favicon handling
app.use(express.favicon(this.htdocs+'/ico/icon_qaserver.ico'));
// other middleware
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('WWWATTD COOKIE SECRET'));
app.use(express.session());
// static htdocs dir
app.use(express.static(this.htdocs));
app.use(express.directory(this.htdocs));
/*************** routes *****************/
// declare router
app.use(app.router);
// index is served by static data
// add custom routes
// this._declare_route("custom","/custom");
// a 500 error (useful to keep around)
app.get('/500', function(req, res){
throw new Error("Generic error");
});
//The 404 Route (ALWAYS Keep this as the last route)
function NotFound(msg){
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
app.get('/*', function(req, res){
throw new NotFound;
});
/************* last middleware **********/
// less CSS templates
//app.use(require('less-middleware')({ src: this.htdocs+"/css/less" }));
// finally, a catch-all error handler
var self=this;
app.use(function(err,req,res,next) {
if (err instanceof NotFound) {
res.writeHead(404,"Not found",{"Content-Type":"text/html"});
fs.readFile(path.join(self.htdocs,"404.html"),function(ferr,data) {
if (ferr)
res.end("<html><head><title>"+self.title+" - 404 : Not found</title></head><body><H1>Page not found</H1></body></html>");
else
res.end(data);
});
}
else {
res.writeHead(500,"Internal server error",{"Content-Type":"text/html"});
fs.readFile(path.join(self.htdocs,"500.html"),function(ferr,data) {
if (ferr)
res.end("<html><head><title>"+self.title+" - 500 : Internal server error</title></head><body><H1>The server encountered an error</H1><p>"+err+"</p></body></html>");
else
res.end(data+err+"</div></body></html>");
});
}
});
return app;
}
WWWServer.prototype._declare_route=function(controller,prefix) {
prefix=prefix||"";
if (prefix[prefix.length-1]!='/') { // add trailing slash if needed
prefix+="/";
}
// load route file for controller and call the function with this=wwwserver
require('./routes/'+controller).call(this,this._app,prefix);
}
/****************************** socket.io config *********************************/
WWWServer.prototype._configure_socketio=function(server) {
// prepare a custom logger using existing log
var mylogger={};
['error','warn','info','debug'].forEach(function(name) {
if (DEBUG && (name=="info")) mylogger[name]=function(){};
else if (DEBUG && (name=="debug")) mylogger[name]=function(){};
else mylogger[name]=function() {
logger[name].call(logger, "socket.io: "+_.toArray(arguments).join(" "));
}
});
// setup socket.io
var io=require('socket.io').listen(this._server,{
'log.level': 2,
'log.color': false,
logger: mylogger
});
var self=this;
io.sockets.on('connection',function(socket) {
self._init_socket(socket);
});
}
// called when a new socket connection occurs
WWWServer.prototype._init_socket=function(socket) {
var cnt=1;
var EVENTS={
// received from client
SUBSCRIBE: "subscribe",
UNSUBSCRIBE: "unsubscribe",
// emitted to client
FAILURE: "failure",
SAMPLES: "samples",
SUBSCRIBED: "subscribed",
UNSUBSCRIBED: "unsubscribed",
};
DEBUG && logger.debug("SOCKET: connect from "+socket.handshake.address.address+" with "+socket.transport);
//DEBUG && logger.debug(socket.handshake);
/******************** base handlers **************/
socket.on('disconnect',function(reason) {
DEBUG && logger.debug("SOCKET: disconnect ("+reason+")");
unsubscribe();
});
socket.on('message',function(data) {
DEBUG && logger.debug("SOCKET: received message: "+data);
});
/******************* subscribe/unsubscribe *********/
var self=this;
var refreshtimer=false;
var samples=[];
function newSampleFromWattMeter(s) {
if (refreshtimer)
samples.push(s);
}
function subscribe(samplefreq,refreshfreq) {
self.wmeter.setSamplingFrequency(samplefreq);
self.wmeter.addListener('sample',newSampleFromWattMeter);
if (refreshtimer) {
// change timer interval but do not subscribe again
clearInterval(refreshtimer);
}
refreshtimer=setInterval(function() {
// samples event is volatile (it can be dropped by client)
if (!samples.length) return;
socket.volatile.emit(EVENTS.SAMPLES,JSON.stringify(samples));
samples.splice(0);
},1000/refreshfreq);
return true;
}
function unsubscribe() {
// unsubscribe to samples
self.wmeter.removeListener('sample',newSampleFromWattMeter);
if (refreshtimer)
clearInterval(refreshtimer);
refreshtimer=false;
return true;
}
socket.on(EVENTS.SUBSCRIBE, function(maxfreq, refreshfreq ) {
maxfreq=(maxfreq>0) ? maxfreq : 1.0;
refreshfreq=(refreshfreq>0) ? refreshfreq : 1.0;
DEBUG && logger.debug("SOCKET: received subscribe (freq:"+maxfreq+", refresh:"+refreshfreq+")");
if (subscribe(maxfreq,refreshfreq)) {
socket.emit(EVENTS.SUBSCRIBED,EVENTS.SAMPLES,maxfreq,refreshfreq);
}
else {
socket.emit(EVENTS.FAILURE,"Already Subscribed");
}
});
socket.on(EVENTS.UNSUBSCRIBE, function() {
DEBUG && logger.debug("SOCKET: received unsubscribe");
unsubscribe();
socket.emit(EVENTS.UNSUBSCRIBED,EVENTS.SAMPLES);
});
}
/**************************************** server launch *******************************************/
function main() {
console.log("---------------------------------------------------");
// ------------------- parse args ------------------------------
// build arguments array (argv[0] is 'node', argv[1] is this script)
var argv=process.argv.slice(2);
// assume that config file is passed as argument (array or string)
var cfgfile;
if ((argv instanceof Array) && (argv.length)) {
cfgfile=argv[0];
}
else {
cfgfile=path.join(__dirname,path.join("etc",path.basename(__filename)+".conf"));
}
if (!cfgfile)
throw new Error("No configuration file given");
// ------------------- load config ------------------------------
console.log("Loading config from "+cfgfile);
var config=require(cfgfile);
if (!config)
throw new Error("Unable to load configuration from "+cfgfile);
// ------------------- setup log ---------------------------------
config.log=_.extend({
file:'wwwattd.log',
maxsize: null,
backup: null,
level: 'info'
},config.log || {});
if (DEBUG) {
logger.remove(logger.transports.Console);
logger.add(logger.transports.Console,{
level: config.log.level,
colorize: true,
timestamp: true
});
logger.debug("DEBUG mode - console log not removed");
}
else {
console.log("Redirecting log to "+config.log.file+" (maxsize="+config.log.maxsize+" backup="+config.log.backup+" level="+config.log.level+")");
logger.add(logger.transports.File,{
filename: config.log.file,
level: config.log.level,
maxsize: config.log.maxsize*1024||1024*1024,
maxFiles: 5,
timestamp: true
});
logger.remove(logger.transports.Console);
}
logger.info("-------------- new daemon session -----------------");
// ------------ install exceptions & signal handlers ---------------
process.on("uncaughtException", function(err) {
logger.error(err.stack);
});
['SIGHUP','SIGINT','SIGQUIT','SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
logger.info("Stopping...");
process.exit(1);
});
});
var srv=new WWWServer(config.www);
srv.listen();
}
main();
// vim: set syntax=javascript: