SilvrAPI/routes/temp.js
2015-11-19 10:19:00 +00:00

157 lines
3.1 KiB
JavaScript

var express = require('express'), fs = require('fs'), sqlite3 = require('sqlite3').verbose();
var router = express.Router();
var temp_db;
var file = process.env.DB_HOME + '/' + "temp.db";
var exists;
/* GET users listing. */
function createDB() {
console.log('Creating Temp db...');
if (!fs.existsSync(file)) {
console.log('creating db file');
fs.openSync(file,'w');
temp_db = new sqlite3.Database(file, createTable);
temp_db.close();
}
}
function connectDB() {
"use strict";
console.log('Connect db.');
temp_db = new sqlite3.Database(file);
}
function createTable() {
console.log('Creating temp table...');
temp_db.run('CREATE TABLE IF NOT EXISTS temp (date text, reading real);');
}
function closeDB() {
"use strict";
console.log('Closing db.');
temp_db.close();
}
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;
console.log('t:');
console.log(JSON.stringify(t));
if (req.query != {} && req.query.temp != null)
{
// createDB();
console.log(req.query);
connectDB();
insertTempReading(now.toJSON(),parseFloat(req.query.temp) );
closeDB();
res.writeHead(200, {"ContentType": "application/json"});
//res.send(JSON.stringify(t));
res.end(JSON.stringify(t));
} else
{
res.render('temp', { });
}
});
router.get('/reading', function(req, res, next) {
var now = new Date();
var t = req.query;
console.log('t:');
console.log(JSON.stringify(t));
res.writeHead(200, {"ContentType": "application/json"});
//res.send(JSON.stringify(t));
res.end(JSON.stringify({}));
});
router.post('/', function(req, res, next) {
"use strict";
console.log('POST');
var t = req.query;
console.log('t:');
console.log(JSON.stringify(t));
if (t != {} && t.temp != null)
{
// createDB();
console.log(req.query);
connectDB();
insertTempReading(now.toJSON(),parseFloat(t.temp) );
closeDB();
}
res.writeHead(200, {"ContentType": "application/json"});
//res.send(JSON.stringify(t));
res.end(JSON.stringify({}));
});
router.get('/all', function(req, res, next) {
"use strict";
console.log('Selecint all..');
connectDB();
temp_db.all('SELECT * from temp', function(err, rows) {
var out = [];
console.log(err);
console.log(rows);
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));
closeDB();
});
});
module.exports = router;
createDB();