Skip to content
Snippets Groups Projects
diagrams.js 1.56 KiB
Newer Older
Kasalehlia's avatar
Kasalehlia committed
var Mustache = require('mustache');
var httpreq = require('httpreq');

var TEMPLATES = {main: ''};
require('fs').readFile('modules/diagrams/main.mustache', 'utf-8', function (err, data) {
    TEMPLATES.main = data;
});
require('fs').readFile('modules/diagrams/data.mustache', 'utf-8', function (err, data) {
    TEMPLATES.data = data;
});

function fetchData(id, cb) {
    var url = "http://shiny.tinyhost.de/php/getdata.php?time=1&id[]="+id;
    httpreq.get(url, {binary: true}, function (err, res) {
        try {
            cb(res.body.toString().split('\n'));
        } catch(e) {}
    });
}

DATA = {power: '[]', devices: '[]'};

function handleData(prop, data) {
    var line,out = []
    for (var i = 1; i < data.length-1; i++) {
        line = data[i].split(',');
        if (line.length === 2) {
            out.push([ (new Date(line[0])).getTime() , parseFloat(line[1]) ])
        }
    }
    DATA[prop] = JSON.stringify(out);
}

function update(cb) {
    var counter = 0;
    var next = function () {
        if (++counter === 2) {
            cb();
        }
    }
    fetchData(1, function (data) {
        handleData('power', data);
        next();
    }); //power
    fetchData(4, function (data) {
        handleData('devices', data);
        next();
    }); //devices
}

module.exports = function (io) {
    setInterval(function () {
        update(function () {
            io.emit('diagrams.data', Mustache.render(TEMPLATES.data, DATA));
        });
    }, 5000);
    io.on('connect', function (sock) {
        sock.emit('diagrams', Mustache.render(TEMPLATES.main, {}));
    });
}