SilvrAPI/routes/temp.js
2015-11-09 00:47:50 +00:00

75 lines
1.7 KiB
JavaScript

var express = require('express'), sqlite3 = require('sqlite3').verbose();
var router = express.Router();
var temp_db;
/* GET users listing. */
function createDB() {
console.log('Creating Temp db...');
temp_db = new sqlite3.Database('temp.sqlite3', createTable);
}
function createTable() {
console.log('Creating temp table...');
temp_db.run('CREATE TABLE IF NOT EXISTS temp (date text, reading real);');
}
function insertTempReading(time, reading) {
console.log('Inserting reading:' + reading);
// var sql = db.prepare('INSERT into temperature(date, reading) VALUES
// (?,?)',[time],[reading]);
temp_db.run('BEGIN TRANSACTION');
temp_db.run('INSERT into temp(date, reading) VALUES (?,?)',[time, reading]);
temp_db.run('END');
}
router.get('/', function(req, res, next) {
var now = new Date();
var t = req.query;
if (req.query != {} && req.query.temp != null)
{
// createDB();
console.log(req.query);
insertTempReading(now.toJSON(),parseFloat(req.query.temp) );
}
res.writeHead(200, {"ContentType": "application/json"});
//res.send(JSON.stringify(t));
res.end(JSON.stringify(t));
});
router.get('/all', function(req, res, next) {
"use strict";
temp_db.all('SELECT * from temp', function(err, rows) {
var out = [];
rows.forEach(function (row) {
console.log(row.date + ', ' + row.reading);
// var t = ;
// out.push({"date": Date(row.date), "reading":row.reading});
out.push({"date": row.date, "reading":row.reading});
});
res.writeHead(200, {"ContentType": "application/json"});
//res.send(JSON.stringify(t));
res.end(JSON.stringify(out));
});
});
module.exports = router;
createDB();