Newer
Older
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
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, {}));
});
}