SilvrAPI/routes/temp.js
2016-02-17 11:20:09 +00:00

203 lines
5.4 KiB
JavaScript

var express = require('express'), fs = require('fs'), sqlite3 = require('sqlite3').verbose(), http=require('http');
var EventEmitter = require('events');
var log4js = require('log4js');
var logger = log4js.getLogger();
var router = express.Router();
var EventEmitter = require('events');
var busEmitter = new EventEmitter();
var WebSocketServer = require('websocket').server;
var temp_db;
var file = process.env.DB_HOME + '/' + "temp.db";
var exists;
/* GET users listing. */
function createDB() {
logger.debug('Creating Temp db...');
logger.debug(file);
if (!fs.existsSync(file)) {
logger.debug('creating db file');
fs.openSync(file, 'w');
temp_db = new sqlite3.Database(file, createTable);
temp_db.close();
}
else {
logger.info('Database already created.');
connectDB();
}
}
function startEventHandler() {
"use strict";
}
function connectDB() {
"use strict";
logger.debug('Connect db.');
temp_db = new sqlite3.Database(file);
//logger.debug(temp_db);
return temp_db;
}
function createTable() {
logger.debug('Creating temp table...');
temp_db.run('CREATE TABLE IF NOT EXISTS temp (date text, reading real);');
}
function closeDB() {
"use strict";
logger.debug('Closing db.');
temp_db.close();
}
function insertTempReading(time, reading) {
logger.debug('Inserting reading:' + reading);
temp_db.run('BEGIN TRANSACTION');
temp_db.run('INSERT into temp(date, reading) VALUES (?,?);', [time, reading]);
temp_db.run('commit');
busEmitter.emit("sendSocket", reading);
}
router.get('/', function (req, res, next) {
res.render('temp');
});
router.post('/', function (req, res, next) {
"use strict";
var t = req.body;
var now = new Date();
var dataJSON;
if (t.hasOwnProperty('data')) {
var data = JSON.parse(t.data.toString());
if (data.hasOwnProperty('temp')) {
busEmitter.emit("saveTempData", {time: now.toJSON(), value: parseFloat(data.temp)});
}
else {
logger.error('No temp data!');
}
}
else {
logger.error('No data block!');
}
res.writeHead(200, {"ContentType": "text/html"});
res.end('ok');
});
router.get('/all', function (req, res, next) {
"use strict";
logger.debug('Selecint all..');
//var db = connectDB();
temp_db.all('SELECT * from temp', function (err, rows) {
var out = [];
logger.debug(err);
logger.debug(rows);
rows.forEach(function (row) {
logger.debug(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();
var doInsertEvent = (obj) =>{
// logger.info('sendSocket: ' + JSON.stringify(obj));
insertTempReading(obj.time, obj.value);
}
busEmitter.on('saveTempData', doInsertEvent);
// Socket Stuff
logger.info('Configuring WebSocket Listener...');
logger.trace('Creating server...');
var server = http.createServer(function (request, response) {
logger.info((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
logger.trace('Creating listener...');
server.listen(8031, function () {
logger.info((new Date()) + ' Server is listening on port 8031');
});
logger.trace('Creating wsServer...');
var wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function (request) {
logger.trace('CREATING CONNECTION');
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
logger.error((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('', request.origin);
logger.debug((new Date()) + ' Connection accepted.');
var sendSocketHandler = (obj) => {
logger.info('sendSocket: ' + JSON.stringify(obj));
connection.sendUTF(JSON.stringify(obj));
}
busEmitter.on('sendSocket', sendSocketHandler);
connection.on('message', function (message) {
if (message.type === 'utf8') {
logger.debug('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
logger.debug('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function (reasonCode, description) {
logger.debug((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
busEmitter.removeListener('sendSocket', sendSocketHandler);
});
});;