456 lines
14 KiB
JavaScript
456 lines
14 KiB
JavaScript
// ./src/index.js
|
|
|
|
// importing the dependencies
|
|
const util = require('util');
|
|
const express = require('express');
|
|
const bodyParser = require('body-parser');
|
|
const cors = require('cors');
|
|
const helmet = require('helmet');
|
|
const morgan = require('morgan');
|
|
const cron = require('node-cron');
|
|
const request = require('request');
|
|
const got = require('got');
|
|
|
|
//auth ++
|
|
var session = require('express-session')
|
|
var passport = require('passport')
|
|
var Strategy = require('passport-local').Strategy;
|
|
var db = require('./db');
|
|
var ensureLoggedIn = require("connect-ensure-login").ensureLoggedIn("/n/login");
|
|
|
|
|
|
// passport.use(new Strategy(
|
|
// // {
|
|
// // usernameField: 'email',
|
|
// // passwordField: 'passwd',
|
|
// // session: false
|
|
// // },
|
|
// function(username, password, done) {
|
|
|
|
// console.log("executing auth strategy: local");
|
|
// if(username == "popov" & password == "test12345")
|
|
// {
|
|
// done(null, new {username:"popov"});
|
|
// }else
|
|
// {
|
|
// return done(null, false);
|
|
// }
|
|
// }
|
|
// ));
|
|
// passport.serializeUser(function(user, cb) {
|
|
|
|
// console.log("serializeUser()");
|
|
// cb(null, user.id);
|
|
// });
|
|
|
|
// passport.deserializeUser(function(id, cb) {
|
|
// console.log("de-serializeUser()");
|
|
// cb(null, new {username:"popov"});
|
|
// });
|
|
|
|
//! Configure the local strategy for use by Passport.
|
|
//
|
|
// The local strategy require a `verify` function which receives the credentials
|
|
// (`username` and `password`) submitted by the user. The function must verify
|
|
// that the password is correct and then invoke `cb` with a user object, which
|
|
// will be set at `req.user` in route handlers after authentication.
|
|
passport.use(new Strategy(
|
|
function(username, password, cb) {
|
|
console.log('requesting authentication for user '+ username);
|
|
db.users.findByUsername(username, function(err, user) {
|
|
if (err) { return cb(err); }
|
|
if (!user) { return cb(null, false); }
|
|
if (user.password != password) { return cb(null, false); }
|
|
return cb(null, user);
|
|
});
|
|
}));
|
|
|
|
|
|
// Configure Passport authenticated session persistence.
|
|
//
|
|
// In order to restore authentication state across HTTP requests, Passport needs
|
|
// to serialize users into and deserialize users out of the session. The
|
|
// typical implementation of this is as simple as supplying the user ID when
|
|
// serializing, and querying the user record by ID from the database when
|
|
// deserializing.
|
|
passport.serializeUser(function(user, cb) {
|
|
cb(null, user.id);
|
|
});
|
|
|
|
passport.deserializeUser(function(id, cb) {
|
|
db.users.findById(id, function (err, user) {
|
|
if (err) { return cb(err); }
|
|
cb(null, user);
|
|
});
|
|
});
|
|
|
|
// auth --
|
|
|
|
//!https endpoint
|
|
var fs = require("fs");
|
|
var http = require('http');
|
|
var https = require('https');
|
|
try{
|
|
var _privateKey = fs.readFileSync('/etc/letsencrypt/live/iot.d-popov.com/privkey.pem', 'utf8');
|
|
var _certificate = fs.readFileSync('/etc/letsencrypt/live/iot.d-popov.com/cert.pem', 'utf8');
|
|
var credentials = {key: _privateKey, cert: _certificate};
|
|
}catch(ex){console.log("can't load certificates.");}
|
|
|
|
|
|
//!database
|
|
var mysql = require('mysql');
|
|
var con = mysql.createConnection({
|
|
host : 'localhost',
|
|
user : 'iot',
|
|
password : '!iot_popovi',
|
|
database : 'iot'
|
|
});
|
|
|
|
|
|
|
|
|
|
// defining the Express app
|
|
const app = express();
|
|
|
|
// adding Helmet to enhance your API's security
|
|
app.use(helmet());
|
|
|
|
// using bodyParser to parse JSON bodies into JS objects
|
|
//app.use(bodyParser.text({ type: 'text/html' }))
|
|
//app.use(bodyParser.json({ type: 'application/*+json' }));
|
|
//app.use(bodyParser.text());
|
|
app.use(bodyParser.json());
|
|
app.use(bodyParser.urlencoded({ extended: true }));
|
|
app.use(express.static('public'))
|
|
// enabling CORS for all requests
|
|
app.use(cors());
|
|
//Authentication ++
|
|
app.use(session({
|
|
secret: 'че първият ще генерира грешка, ако изгледът не дефинира съдържание за този раздел',
|
|
resave: true,
|
|
saveUninitialized: false
|
|
}));
|
|
app.use(passport.initialize());
|
|
app.use(passport.session());
|
|
//Authentication --
|
|
|
|
//app.set('views', __dirname + '/views');
|
|
app.set('view engine', 'ejs');
|
|
app.use(require('express-ejs-layouts'));//https://www.npmjs.com/package/express-ejs-layouts
|
|
//app.set("layout extractScripts", true)
|
|
//app.set('view engine', 'vash');//https://www.npmjs.com/package/vash#layout-helpers
|
|
|
|
|
|
// adding morgan to log HTTP requests
|
|
//app.use(morgan('combined'));
|
|
|
|
// defining endpoints
|
|
|
|
app.get('/', function(req, res){
|
|
res.redirect('/n/login');
|
|
});
|
|
//Authentication ++
|
|
app.get('/login', function(req, res) {
|
|
res.render('login', { user: req.user });
|
|
});
|
|
|
|
app.post('/login',
|
|
passport.authenticate('local', {
|
|
successRedirect: '/n/accontrol',
|
|
failureRedirect: '/n/login' }),
|
|
// authenticated user.
|
|
function(req, res) {
|
|
|
|
console.log("logged in. session:" + req.session);
|
|
res.redirect(req.session);
|
|
}
|
|
);
|
|
app.get('/logout', function(req, res){
|
|
req.logout();
|
|
res.redirect('/n/login');
|
|
});
|
|
|
|
app.get('/accontrol', ensureLoggedIn, function(req, res){
|
|
res.render('accontrol',{model:{data:req.body, user:req.user, command:"", info:""}});
|
|
});
|
|
|
|
var ac = require('./ac.js');
|
|
app.post('/accontrol', ensureLoggedIn, function(req, res){
|
|
var model = { model: {user: req.user, data: req.body} };
|
|
console.log("power:"+ req.body.power);
|
|
console.log("heat:"+ req.body.heat);
|
|
console.log("temp:"+ req.body.temp);
|
|
console.log("econo:"+ req.body.econo);
|
|
ac.Tlc112.Init();
|
|
ac.Tlc112.SetPower(req.body.power);
|
|
ac.Tlc112.SetMode(req.body.heat? ac.Mode.Heat:ac.Mode.Cool);
|
|
ac.Tlc112.SetTemp( req.body.temp);
|
|
var code = ac.Tlc112.GetCommand();
|
|
request.post(
|
|
'http://192.168.1.126/ir',
|
|
{ form: { code: code, type: 30} },
|
|
function (error, response, body) {
|
|
if (!error && response.statusCode == 200) {
|
|
console.log("GOT " + body);
|
|
//var m = model;
|
|
//res.render('accontrol', {model:{data:req.body, user:req.user, command:com[0], info:com[0].info}});
|
|
}else{
|
|
model.info = "Error executing command " + model.command.info + ". Server resturned:" + req.statusCode
|
|
}
|
|
}
|
|
);
|
|
|
|
// var where = {ac_power: req.body.power?true:false};
|
|
// if(where.ac_power){
|
|
// where.ac_mode = req.body.heat?"Heat":"Cool";
|
|
// if(req.body.temp){ where.ac_temp = req.body.temp; }else{where.ac_temp = 23}
|
|
|
|
// //where.ac_econo = req.body.econo?true:false;
|
|
// //// if(req.body.turbo){ where.ac_turbo = req.body.turbo?true:false; }
|
|
// //// if(req.body.swing){ where.ac_swing = req.body.swing?true:false; }
|
|
// //// if(req.body.display){ where.ac_display = req.body.display?true:false; }
|
|
// //// if(req.body.health){ where.ac_health = req.body.health?true:false; }
|
|
// }
|
|
// data.DeviceCommand.findAll({ where: where }).then(function(com){
|
|
// console.log("FOUND "+ com.length + " RESULTS");
|
|
// if(com.length > 0)
|
|
// {
|
|
// model.command = com[0];
|
|
// model.info = model.command.info;
|
|
// console.log("executing command "+ model.info+ "");
|
|
// request.post(
|
|
// 'http://192.168.1.126/ir',
|
|
// { form: { cmd: "RAW:" + model.command.command } },
|
|
// function (error, response, body) {
|
|
// if (!error && response.statusCode == 200) {
|
|
// //console.log("GOT " + body);
|
|
// var m = model;
|
|
// res.render('accontrol', {model:{data:req.body, user:req.user, command:com[0], info:com[0].info}});
|
|
// }else{
|
|
// model.info = "Error executing command " + model.command.info + ". Server resturned:" + req.statusCode
|
|
// }
|
|
// }
|
|
// );
|
|
// } else
|
|
// {
|
|
// model.info = "Command not executed. Found " + com.length + "commands"
|
|
// res.render('accontrol', model);
|
|
// }
|
|
//});
|
|
});
|
|
|
|
|
|
app.get('/chart', ensureLoggedIn,
|
|
function(req, res){
|
|
res.render('chart', { user: req.user });
|
|
});
|
|
|
|
|
|
|
|
//Authentication --
|
|
const { parse } = require('querystring');
|
|
app.post('/dht/ping', (req, res) => { (async (res) => {
|
|
try {
|
|
console.log("HEADERS:" + req.headers); res.sendStatus(200);
|
|
} catch (error) {
|
|
console.log("PING Error:" + error); res.sendStatus(500);
|
|
} })(res);
|
|
});
|
|
|
|
var moment = require('moment');
|
|
|
|
app.use('/ir', bodyParser.text(), function(rq, rs) {
|
|
|
|
console.log("");
|
|
console.log("");
|
|
console.log("");
|
|
console.log("");
|
|
console.log("IR request:"+rq.method );
|
|
if(rq.method == "GET")
|
|
{
|
|
var cmd = rq.param('command');
|
|
console.log("GET CMD:"+cmd );
|
|
switch(cmd)
|
|
{
|
|
case 'ping':
|
|
var t = moment.duration(parseInt(rq.param('uptime')), 'milliseconds');
|
|
var _message = rq.param('ip') + " uptime " + t.hours() + "h " + t.minutes() + "m " + t.seconds() +"s";
|
|
// var t = moment.duration(parseInt(rq.params.uptime), 'milliseconds');
|
|
// var _message = rq.params.ip + " uptime " + t.hours() + "h " + t.minutes() + "m " + t.seconds() +"s";
|
|
console.log("ping from " + _message);
|
|
rs.send("pong=ok");
|
|
rs.end('End\n');
|
|
console.log("response ended");
|
|
break;
|
|
case 'on':
|
|
default:rs.send("OK");
|
|
}
|
|
}else {
|
|
let body = '';
|
|
rq.on('data', chunk => {
|
|
body += chunk.toString();
|
|
});
|
|
rq.on('end', () => {
|
|
console.log(">"+body);
|
|
var ob = parse(body);
|
|
console.log(ob);
|
|
rs.end('ok');
|
|
});
|
|
}
|
|
});
|
|
|
|
|
|
app.get('/dht', (req, res) => { (async (res) => {
|
|
try {
|
|
const response = await got('http://192.168.1.126/json')
|
|
res.send(response.body);
|
|
} catch (error) {
|
|
console.log("DHT Error:" + error); //..response.body);
|
|
} })(res);
|
|
});
|
|
|
|
app.get("/dht/:field_name", (req, res) => {
|
|
dht = con.query("SELECT * FROM devicemessages WHERE field_name=? OR ? IS NULL",
|
|
[req.params.field_name, req.params.field_name], (err, data) => {
|
|
//dht = con.query("SELECT * FROM devicemessages", (err, data) => {
|
|
if (!err) {
|
|
res.send(data);
|
|
} else {
|
|
console.log("error: ", err);
|
|
}
|
|
});
|
|
});
|
|
|
|
app.put('/dht/:device_id/:field_name/:field_value', (req, res) => {
|
|
var params = [req.params.device_id,req.params.field_name,req.params.field_value];
|
|
let sql = `INSERT INTO devicemessages(device_id,field_name,field_value,timestamp)
|
|
VALUES (?,?,?,NOW());`;
|
|
con.query(sql,params, (err, r) => {
|
|
if (err) {
|
|
console.log("error: ", err);
|
|
res.send( err);
|
|
return;
|
|
}
|
|
|
|
if (r.affectedRows == 0) {
|
|
// not found Customer with the id
|
|
res.send({ kind: "not_found" });
|
|
return;
|
|
}
|
|
|
|
console.log("inserted record: ", { id: r.insertId, ...params });
|
|
res.send( { id: r.insertId, ...params });
|
|
});
|
|
//con.end();
|
|
|
|
//fs.appendFileSync('dht.txt', 'data to append');
|
|
|
|
});
|
|
|
|
app.get('/ac', (req, res) => { (async (res) => {
|
|
try {
|
|
const response = await got('http://192.168.1.126/json')
|
|
res.send(response.body);
|
|
} catch (error) {
|
|
console.log("DHT Error:" + error); //..response.body);
|
|
} })(res);
|
|
});
|
|
|
|
|
|
//Startup
|
|
|
|
var httpServer = http.createServer(app);
|
|
if(credentials){
|
|
var httpsServer = https.createServer(credentials, app);
|
|
httpsServer.listen(8443, () => {
|
|
console.log('HTTPS server listening on port 8443');
|
|
});
|
|
}
|
|
|
|
httpServer.listen(81, () => {
|
|
console.log('HTTP server listening on port 81');
|
|
});
|
|
|
|
var data = require('./database.js');
|
|
//require('./database.js')();
|
|
//data.init();
|
|
|
|
var device = data.Device.build({
|
|
name: 'A23',
|
|
url: "http://192.168.1.126/"
|
|
});
|
|
|
|
// device.save().then().catch(
|
|
// err => {console.log(err);}
|
|
// )
|
|
//.success(function(savedTask) {
|
|
// console.log('device saved with id' + savedTask.id);
|
|
// });
|
|
|
|
// # ┌────────────── second (optional)
|
|
// # │ ┌──────────── minute
|
|
// # │ │ ┌────────── hour
|
|
// # │ │ │ ┌──────── day of month
|
|
// # │ │ │ │ ┌────── month
|
|
// # │ │ │ │ │ ┌──── day of week
|
|
// # │ │ │ │ │ │
|
|
// # │ │ │ │ │ │
|
|
// # * * * * * *
|
|
cron.schedule(' */30 * * * *', () => {//cron.schedule('*/5 * * * * *', () => {
|
|
console.log(new Date().toISOString() + ' running a task every 30 minutes');
|
|
StoreSensorReadingsAsync();
|
|
}).start();
|
|
|
|
//StoreSensorReadings();
|
|
|
|
async function StoreSensorReadingsAsync()
|
|
{
|
|
try {
|
|
await new Promise(function(resolve, reject) {
|
|
request('http://192.168.1.126/json', { json: true }, (err, res, body) => {
|
|
if(err) {
|
|
return reject(err);
|
|
}
|
|
else {
|
|
var params = [0, "A23_DHT", JSON.stringify(body)];
|
|
let sql = `INSERT INTO devicemessages(device_id,field_name,field_value,timestamp)
|
|
VALUES (?,?,?,NOW());`;
|
|
con.query(sql,params,(err, r) => {
|
|
if (err) {
|
|
console.log("error: ", err);
|
|
}else{
|
|
console.log("inserted record: ", { id: r.insertId, ...params });
|
|
}
|
|
});
|
|
resolve(body);
|
|
console.log(body);
|
|
}
|
|
});
|
|
});
|
|
} catch(error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
|
|
|
|
function StoreSensorReadings()
|
|
{
|
|
(async () => {
|
|
try {
|
|
const dht = await got('http://192.168.1.126/json')
|
|
|
|
var params = [0, "A23_DHT", dht.body];
|
|
let sql = `INSERT INTO devicemessages(device_id,field_name,field_value,timestamp)
|
|
VALUES (?,?,?,NOW());`;
|
|
con.query(sql,params,(err, r) => {
|
|
if (err) {
|
|
console.log(err);
|
|
}else{
|
|
console.log("inserted record: ", { id: r.insertId, ...params });
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.log("DHT Error:" + error); //..response.body);
|
|
} })();
|
|
}
|