Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- process.stdout.write("Loading modules: http");var http = require('http');
- process.stdout.write(", url");var url = require('url');
- process.stdout.write(", path");var path = require('path');
- process.stdout.write(", fs");var fs = require('fs');
- process.stdout.write(", mime");var mime = require('mime');
- process.stdout.write(", os");var os = require('os');
- process.stdout.write(", child_process");var exec = require('child_process').exec;
- process.stdout.write(", zlib");var zlib = require('zlib');
- process.stdout.write(", ws");var WebSocketServer = require('ws').Server;
- process.stdout.write(", DONE!\n");
- var PORT = 7000;
- var sockets = [];
- function getRelativePath(filepath) {
- return path.join(__dirname, filepath)
- };
- function notFound(res) {
- res.writeHead(404, {'Content-Type': 'text/plain;charset=utf-8'});
- res.end('404 Not found');
- };
- function getServerInfo () {
- 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";
- };
- function httpGetFile(reqpath, req, res, skipCache) {
- var pathname = reqpath;
- if (reqpath.substr(-1) === "/") {
- pathname += "index.html";
- skipCache = true;
- }
- var filename = path.join(__dirname, './static/', pathname);
- var dirname = path.join(__dirname, './static', reqpath);
- fs.stat(filename, function (err, stats) {
- if (err) {
- if (reqpath.substr(-1) === "/") {
- fs.readdir(dirname, function (err, files) {
- if (err) {
- res.writeHead(403, {'Content-Type': 'text/html;charset=utf-8'});
- res.end('<pre>403 Not allowed to read directory contents\n<strong>'+reqpath+'</strong><hr>'+getServerInfo()+'</pre>');
- return;
- }
- res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
- res.write("<code>Listing directory <strong>"+reqpath+"</strong><br/><br/>\n\n");
- for (var i = 0; i < files.length; i++) {
- res.write("<a href=\""+files[i]+"\">"+files[i]+"</a><br/>\n")
- }
- res.write("<hr>");
- res.write(getServerInfo());
- res.end("</code>");
- });
- } else {
- res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'});
- res.end('<pre>404 Not found\n<strong>'+reqpath+'</strong><hr>'+getServerInfo()+'</pre>');
- }
- return;
- } else {
- }
- if (reqpath.substr(-1) !== "/" && stats.isDirectory()) {
- res.writeHead(302, {'Content-Type': 'text/plain;charset=utf-8', 'Location': reqpath+'/'});
- res.end('302 Redirection');
- return;
- }
- var isCached = false;
- if (req.headers['if-modified-since'] && !skipCache) {
- var req_date = new Date(req.headers['if-modified-since']);
- if (stats.mtime <= req_date && req_date <= Date.now()) {
- res.writeHead(304, {
- 'Last-Modified': stats.mtime
- });
- res.end();
- isCached = true;
- }
- }
- if (!isCached) {
- var type = mime.lookup(filename);
- var headers = {
- 'Content-Type': type+';charset=utf-8'
- };
- if (!skipCache) {
- headers['Last-Modified'] = stats.mtime;
- }
- var stream = fs.createReadStream(filename);
- var acceptEncoding = req.headers['accept-encoding'] || '';
- fs.readFile(filename, function (err, data) {
- function sendBody (buf) {
- headers['Content-Length'] = buf.length;
- res.writeHead(200, headers);
- res.end(buf);
- }
- if (err) {
- if (reqpath.substr(-1) !== "/") {
- res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'});
- res.end('<pre>404 Not found\n<strong>'+reqpath+'</strong>\n\nThis should not happen (dir).</pre>');
- } else {
- res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'});
- res.end('<pre>404 Not found\n<strong>'+reqpath+'</strong>\n\nThis should not happen (file).</pre>');
- }
- } else {
- if (acceptEncoding.match(/\bdeflate\b/)) {
- zlib.deflate(data, function (err, cdata) {
- if (err) {
- sendBody(data);
- } else {
- headers['Content-Encoding'] = 'deflate';
- sendBody(cdata);
- }
- });
- } else if (acceptEncoding.match(/\bgzip\b/)) {
- zlib.gzip(data, function (err, cdata) {
- if (err) {
- sendBody(data);
- } else {
- headers['Content-Encoding'] = 'gzip';
- sendBody(cdata);
- }
- });
- } else {
- sendBody(data);
- }
- }
- });
- }
- });
- };
- var httpServer = http.createServer(function (req, res) {
- var uri = url.parse(req.url, true);
- var pathname = decodeURI(uri.pathname.replace(/\/\//g, "/"));
- var pathlist = pathname.substr(1).split("/");
- var specialCommand = true;
- switch (pathlist[0]) {
- case 'firmware':
- switch (pathlist[1]) {
- case 'version':
- res.writeHead(200, {'Content-Type': 'text/plain'});
- exec('/opt/vc/bin/vcgencmd version', function (err, stdout, stderr) {
- res.end(stdout);
- });
- break;
- default:
- notFound(res);
- break;
- }
- break;
- default:
- specialCommand = false;
- break;
- }
- if (specialCommand) {
- return;
- }
- httpGetFile(pathname, req, res);
- }).listen(PORT, function () {
- console.log('http server @ '+PORT);
- });
- var broadcast = function (text) {
- for(var i=0; i < sockets.length; i+=1) {
- if (sockets[i].readyState === 1) {
- sockets[i].send(text);
- }
- }
- };
- var wss = new WebSocketServer({
- server: httpServer
- });
- wss.on('connection', function (ws) {
- //console.log(ws.upgradeReq.url);
- var remoteAddress = ws._socket.remoteAddress;
- console.log(remoteAddress+" joined");
- sockets.push(ws);
- broadcastInfo();
- ws.on('close', function (reasonCode, reasonText) {
- console.log(remoteAddress+" left");
- var index = sockets.indexOf(ws);
- sockets.splice(index, 1);
- });
- ws.on('error', function (err) {
- console.log(remoteAddress+" got error: ", err);
- var index = sockets.indexOf(ws);
- sockets.splice(index, 1);
- });
- });
- function broadcastInfo () {
- if (sockets.length > 0) {
- var info = {
- };
- var c = 0;
- function cb (key, data) {
- info[key] = data;
- if (++c === 5) {
- broadcast(JSON.stringify(info));
- }
- };
- fs.readFile("/sys/class/thermal/thermal_zone0/temp", function (err, data) {
- cb('temp', parseInt(data.toString().trim(), 10));
- });
- fs.readFile("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", function (err, data) {
- cb('freq', parseInt(data.toString().trim(), 10));
- });
- exec("free -mo", function (error, stdout, stderr) {
- var line2 = stdout.split("\n")[1];
- var numbers = [];
- line2.replace(/\s+([0-9]+)/g, function (raw, val) {
- numbers.push(+val);
- });
- var used = numbers[1] - numbers[4] - numbers[5];
- var total = numbers[0];
- cb('usedmem', used);
- cb('totalmem', total);
- });
- exec("ps aux | awk '{sum +=$3}; END {print sum}'", function (error, stdout, stderr) {
- cb('cpu', parseFloat(stdout));
- });
- }
- };
- setInterval(broadcastInfo, 2*1000);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement