Added Min/Max/Avg to single temperature output

This commit is contained in:
seiichiro 2015-02-08 21:11:46 +01:00
parent 8f51247037
commit 167e7f2cee

View file

@ -23,42 +23,30 @@ exports.getAll = function(req, res) {
}); });
} }
function getTempRecursive(rows, data, res) {
if (rows.length > 0) {
var cur = rows.shift();
var db = new sqlite3.Database(file);
db.get("SELECT avg(value) as avg, max(value) as max, timestamp from temp_" + cur.id + ";", function(err, row) {
if (row !== undefined) {
cur.avg = row.avg;
cur.max = row.max;
cur.tsmax = row.timestamp;
db.get("SELECT min(value) as min, timestamp from temp_" + cur.id + ";", function(err, row) {
if (row !== undefined) {
cur.min = row.min;
cur.tsmin = row.timestamp;
db.close();
data.push(cur);
getTempRecursive(rows, data, res);
}
});
}
});
} else {
res.status(200).send(data);
}
}
exports.getTemp = function(req, res) { exports.getTemp = function(req, res) {
var db = new sqlite3.Database(file); var db = new sqlite3.Database(file);
var data = [];
db.serialize(function() { db.serialize(function() {
db.get("SELECT name, lasttemp, lastupd FROM sensors WHERE id = ?;", req.params.id, function(err, row) { db.get("SELECT id, name, lasttemp as temp, lastupd as ts FROM sensors WHERE id = ?;", req.params.id, function(err, row) {
if (row !== undefined) { if (row !== undefined) {
res.type("application/json"); data = row;
res.status(200).send({"name": row.name, "temp": row.lasttemp, "ts": row.lastupd}); db.get("SELECT avg(value) as avg, max(value) as max, timestamp from temp_" + data.id + ";", function(err, row) {
db.close(); if (row !== undefined) {
data.avg = row.avg;
data.max = row.max;
data.tsmax = row.timestamp;
db.get("SELECT min(value) as min, timestamp from temp_" + data.id + ";", function(err, row) {
if (row !== undefined) {
data.min = row.min;
data.tsmin = row.timestamp;
db.close();
res.type("application/json");
res.status(200).send(data);
}
});
}
});
} else { } else {
db.close(); db.close();
res.status(400).send({"errid": 3, "errtxt": "Sensor does not exist"}); res.status(400).send({"errid": 3, "errtxt": "Sensor does not exist"});
@ -129,3 +117,34 @@ exports.updTemp = function(req, res) {
}); });
}); });
} }
// Helper Functions
function getTempRecursive(rows, data, res) {
if (rows.length > 0) {
var cur = rows.shift();
var db = new sqlite3.Database(file);
db.get("SELECT avg(value) as avg, max(value) as max, timestamp from temp_" + cur.id + ";", function(err, row) {
if (row !== undefined) {
cur.avg = row.avg;
cur.max = row.max;
cur.tsmax = row.timestamp;
db.get("SELECT min(value) as min, timestamp from temp_" + cur.id + ";", function(err, row) {
if (row !== undefined) {
cur.min = row.min;
cur.tsmin = row.timestamp;
db.close();
data.push(cur);
getTempRecursive(rows, data, res);
}
});
}
});
} else {
res.status(200).send(data);
}
}