Advertisement
djazz

System monitor for RPi (node.js)

Sep 21st, 2012
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. process.stdout.write("Loading modules: http");var http = require('http');
  2. process.stdout.write(", url");var url  = require('url');
  3. process.stdout.write(", path");var path = require('path');
  4. process.stdout.write(", fs");var fs   = require('fs');
  5. process.stdout.write(", mime");var mime = require('mime');
  6. process.stdout.write(", os");var os   = require('os');
  7. process.stdout.write(", child_process");var exec = require('child_process').exec;
  8. process.stdout.write(", zlib");var zlib = require('zlib');
  9. process.stdout.write(", ws");var WebSocketServer = require('ws').Server;
  10. process.stdout.write(", DONE!\n");
  11.  
  12. var PORT = 7000;
  13. var sockets = [];
  14.  
  15. function getRelativePath(filepath) {
  16.     return path.join(__dirname, filepath)
  17. };
  18.  
  19. function notFound(res) {
  20.     res.writeHead(404, {'Content-Type': 'text/plain;charset=utf-8'});
  21.     res.end('404 Not found');
  22. };
  23.  
  24. function getServerInfo () {
  25.     return "Raspberry Pi rev2 - "+os.type()+" "+os.release()+" "+os.arch().toUpperCase()+" - Node.JS "+process.version+", "+Math.floor(process.memoryUsage().rss/1024/1024)+" MB RAM used - "+Math.floor(os.uptime()/(60*60*24))+" day(s) device uptime";
  26. };
  27.  
  28. function httpGetFile(reqpath, req, res, skipCache) {
  29.  
  30.     var pathname = reqpath;
  31.  
  32.     if (reqpath.substr(-1) === "/") {
  33.         pathname += "index.html";
  34.         skipCache = true;
  35.     }
  36.  
  37.     var filename = path.join(__dirname, './static/', pathname);
  38.     var dirname = path.join(__dirname, './static', reqpath);
  39.  
  40.     fs.stat(filename, function (err, stats) {
  41.        
  42.         if (err) {
  43.  
  44.             if (reqpath.substr(-1) === "/") {
  45.  
  46.                 fs.readdir(dirname, function (err, files) {
  47.                    
  48.                     if (err) {
  49.                         res.writeHead(403, {'Content-Type': 'text/html;charset=utf-8'});
  50.                         res.end('<pre>403 Not allowed to read directory contents\n<strong>'+reqpath+'</strong><hr>'+getServerInfo()+'</pre>');
  51.                         return;
  52.                     }
  53.                     res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
  54.                     res.write("<code>Listing directory <strong>"+reqpath+"</strong><br/><br/>\n\n");
  55.                     for (var i = 0; i < files.length; i++) {
  56.                         res.write("<a href=\""+files[i]+"\">"+files[i]+"</a><br/>\n")
  57.                     }
  58.                     res.write("<hr>");
  59.                     res.write(getServerInfo());
  60.                     res.end("</code>");
  61.                 });
  62.  
  63.             } else {
  64.                 res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'});
  65.                 res.end('<pre>404 Not found\n<strong>'+reqpath+'</strong><hr>'+getServerInfo()+'</pre>');
  66.             }
  67.            
  68.             return;
  69.         } else {
  70.            
  71.         }
  72.  
  73.         if (reqpath.substr(-1) !== "/" && stats.isDirectory()) {
  74.             res.writeHead(302, {'Content-Type': 'text/plain;charset=utf-8', 'Location': reqpath+'/'});
  75.             res.end('302 Redirection');
  76.             return;
  77.         }
  78.  
  79.        
  80.        
  81.         var isCached = false;
  82.  
  83.         if (req.headers['if-modified-since'] && !skipCache) {
  84.             var req_date = new Date(req.headers['if-modified-since']);
  85.             if (stats.mtime <= req_date && req_date <= Date.now()) {
  86.                 res.writeHead(304, {
  87.                     'Last-Modified': stats.mtime
  88.                 });
  89.                 res.end();
  90.                 isCached = true;
  91.             }
  92.         }
  93.         if (!isCached) {
  94.            
  95.             var type = mime.lookup(filename);
  96.  
  97.             var headers = {
  98.                 'Content-Type': type+';charset=utf-8'
  99.             };
  100.             if (!skipCache) {
  101.                 headers['Last-Modified'] = stats.mtime;
  102.             }
  103.  
  104.             var stream = fs.createReadStream(filename);
  105.             var acceptEncoding = req.headers['accept-encoding'] || '';
  106.  
  107.            
  108.            
  109.  
  110.  
  111.             fs.readFile(filename, function (err, data) {
  112.  
  113.                 function sendBody (buf) {
  114.                     headers['Content-Length'] = buf.length;
  115.                     res.writeHead(200, headers);
  116.                     res.end(buf);
  117.                 }
  118.  
  119.                 if (err) {
  120.                     if (reqpath.substr(-1) !== "/") {
  121.                         res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'});
  122.                         res.end('<pre>404 Not found\n<strong>'+reqpath+'</strong>\n\nThis should not happen (dir).</pre>');
  123.                     } else {
  124.                         res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'});
  125.                         res.end('<pre>404 Not found\n<strong>'+reqpath+'</strong>\n\nThis should not happen (file).</pre>');
  126.                     }
  127.                    
  128.                 } else {
  129.                     if (acceptEncoding.match(/\bdeflate\b/)) {
  130.                         zlib.deflate(data, function (err, cdata) {
  131.                             if (err) {
  132.                                 sendBody(data);
  133.                             } else {
  134.                                 headers['Content-Encoding'] =  'deflate';
  135.                                 sendBody(cdata);
  136.                             }
  137.                         });
  138.                     } else if (acceptEncoding.match(/\bgzip\b/)) {
  139.                         zlib.gzip(data, function (err, cdata) {
  140.                             if (err) {
  141.                                 sendBody(data);
  142.                             } else {
  143.                                 headers['Content-Encoding'] =  'gzip';
  144.                                 sendBody(cdata);
  145.                             }
  146.                         });
  147.                     } else {
  148.                         sendBody(data);
  149.                     }
  150.                 }
  151.             });
  152.         }
  153.     });
  154. };
  155.  
  156. var httpServer = http.createServer(function (req, res) {
  157.    
  158.     var uri = url.parse(req.url, true);
  159.    
  160.     var pathname = decodeURI(uri.pathname.replace(/\/\//g, "/"));
  161.     var pathlist = pathname.substr(1).split("/");
  162.  
  163.     var specialCommand = true;
  164.    
  165.     switch (pathlist[0]) {
  166.  
  167.         case 'firmware':
  168.  
  169.             switch (pathlist[1]) {
  170.                 case 'version':
  171.                     res.writeHead(200, {'Content-Type': 'text/plain'});
  172.                     exec('/opt/vc/bin/vcgencmd version', function (err, stdout, stderr) {
  173.                         res.end(stdout);
  174.                     });
  175.                 break;
  176.  
  177.                 default:
  178.                     notFound(res);
  179.                 break;
  180.             }
  181.  
  182.            
  183.  
  184.             break;
  185.  
  186.  
  187.         default:
  188.             specialCommand = false;
  189.             break;
  190.  
  191.     }
  192.     if (specialCommand) {
  193.         return;
  194.     }
  195.  
  196.    
  197.     httpGetFile(pathname, req, res);
  198.    
  199. }).listen(PORT, function () {
  200.     console.log('http server @ '+PORT);
  201. });
  202.  
  203.  
  204.  
  205. var broadcast = function (text) {
  206.     for(var i=0; i < sockets.length; i+=1) {
  207.         if (sockets[i].readyState === 1) {
  208.             sockets[i].send(text);
  209.         }
  210.     }
  211. };
  212.  
  213. var wss = new WebSocketServer({
  214.     server: httpServer
  215. });
  216. wss.on('connection', function (ws) {
  217.     //console.log(ws.upgradeReq.url);
  218.     var remoteAddress = ws._socket.remoteAddress;
  219.     console.log(remoteAddress+" joined");
  220.     sockets.push(ws);
  221.     broadcastInfo();
  222.  
  223.     ws.on('close', function (reasonCode, reasonText) {
  224.         console.log(remoteAddress+" left");
  225.         var index = sockets.indexOf(ws);
  226.  
  227.         sockets.splice(index, 1);
  228.     });
  229.  
  230.     ws.on('error', function (err) {
  231.         console.log(remoteAddress+" got error: ", err);
  232.         var index = sockets.indexOf(ws);
  233.  
  234.         sockets.splice(index, 1);
  235.     });
  236.  
  237. });
  238.  
  239.  
  240. function broadcastInfo () {
  241.     if (sockets.length > 0) {
  242.  
  243.         var info = {
  244.            
  245.         };
  246.         var c = 0;
  247.  
  248.         function cb (key, data) {
  249.             info[key] = data;
  250.            
  251.             if (++c === 5) {
  252.                 broadcast(JSON.stringify(info));
  253.             }
  254.  
  255.         };
  256.  
  257.         fs.readFile("/sys/class/thermal/thermal_zone0/temp", function (err, data) {
  258.             cb('temp', parseInt(data.toString().trim(), 10));
  259.         });
  260.         fs.readFile("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", function (err, data) {
  261.             cb('freq', parseInt(data.toString().trim(), 10));
  262.         });
  263.         exec("free -mo", function (error, stdout, stderr) {
  264.             var line2 = stdout.split("\n")[1];
  265.             var numbers = [];
  266.             line2.replace(/\s+([0-9]+)/g, function (raw, val) {
  267.                 numbers.push(+val);
  268.             });
  269.            
  270.             var used = numbers[1] - numbers[4] - numbers[5];
  271.             var total = numbers[0];
  272.            
  273.  
  274.             cb('usedmem', used);
  275.             cb('totalmem', total);
  276.  
  277.         });
  278.        
  279.         exec("ps aux | awk '{sum +=$3}; END {print sum}'", function (error, stdout, stderr) {
  280.             cb('cpu', parseFloat(stdout));
  281.         });
  282.  
  283.  
  284.     }
  285. };
  286.  
  287. setInterval(broadcastInfo, 2*1000);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement