454 lines
13 KiB
JavaScript
454 lines
13 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');
|
|
|
|
const WebSocket = require('ws');
|
|
|
|
//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");
|
|
|
|
//! 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) {console.log('err:'+ util.inspect(err)); return cb(err); }
|
|
if (!user) { console.log('user is null:'); return cb(null, false); }
|
|
if (user.password != password) { console.log('wrong pass '); return cb(null, false); }
|
|
console.log('authenticated!');
|
|
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) {
|
|
console.log("user deser:"+ id );
|
|
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());
|
|
|
|
app.use(bodyParser.urlencoded({ extended: true }));
|
|
app.use(bodyParser.json());
|
|
app.use(express.static('public'));
|
|
|
|
// enabling CORS for all requests
|
|
app.use(cors());
|
|
|
|
//Authentication ++
|
|
app.use(session({
|
|
key: 'user_sid',
|
|
secret: 'че първият ще генерира грешка',
|
|
resave: true,
|
|
saveUninitialized: false,
|
|
cookie: {
|
|
expires: 600000
|
|
},
|
|
}));
|
|
app.use(passport.initialize());
|
|
app.use(passport.session());
|
|
//Authentication --
|
|
// app.use(function (req, res, next) {
|
|
// res.status(404).send("Can't find that!")
|
|
// });
|
|
|
|
//app.set('views', __dirname + '/views');
|
|
app.set('view engine', 'ejs');
|
|
app.use(require('express-ejs-layouts'));//https://www.npmjs.com/package/express-ejs-layouts
|
|
|
|
// adding morgan to log HTTP requests
|
|
app.use(morgan('combined'));
|
|
|
|
//defining endpoints
|
|
//!UI
|
|
|
|
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');
|
|
});
|
|
|
|
var ac = require('./ac.js');
|
|
|
|
app.get('/accontrol', ensureLoggedIn, function(req, res){
|
|
res.render('accontrol',{model:{data:req.body, user:req.user, command:"", info:""}});
|
|
});
|
|
|
|
|
|
app.post('/accontrol', ensureLoggedIn, function(req, res){
|
|
var sess=req.session;
|
|
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);
|
|
if(!req.body.temp){req.body.temp = 23;}
|
|
console.log("temp:" + req.body.temp); console.log("econo:" + req.body.econo); console.log("swing:" + req.body.swing);
|
|
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);
|
|
ac.Tlc112.SetSwingVertical( req.body.swing);
|
|
ac.Tlc112.SetFan(ac.FanSpeed.Med);
|
|
|
|
var code = ac.Tlc112.GetCommand();
|
|
//break it
|
|
//code = code.substring(150);
|
|
//console.log("RAW: " + code);
|
|
if(SendIRCommand(code))
|
|
{
|
|
console.log("OK. Temp: " + req.body.temp);
|
|
BroadcastWS(ac.Tlc112.GetState());
|
|
}else{
|
|
model.info = "Error executing command. Server resturned:" + req.statusCode;
|
|
BroadcastWS("Error sending IR command");
|
|
}
|
|
//console.log("req.user:" + util.inspect( req.user));
|
|
res.render('accontrol', model);
|
|
// res.render('accontrol',{model: {data: req.body, user: req.user, command: "", info: model.info}});
|
|
});
|
|
|
|
function SendIRCommand(code){
|
|
console.log("RAW:" + code);
|
|
request.post(
|
|
'http://192.168.1.126/irraw', { form: { cmd: code } },
|
|
function (error, response, body) {
|
|
if (!error && response.statusCode == 200) {
|
|
console.log("GOT '" + body + "'");
|
|
return true;
|
|
}else{
|
|
console.log("ERROR on SendIRCommand:" + util.inspect(error));
|
|
return false;
|
|
}
|
|
}
|
|
);
|
|
}
|
|
|
|
app.get('/chart', ensureLoggedIn,
|
|
function(req, res){
|
|
res.render('chart', { user: req.user });
|
|
});
|
|
|
|
//Authentication --
|
|
|
|
//! ESP HANDLERS
|
|
function GetDht() {
|
|
var ret;
|
|
(async () => {
|
|
try {
|
|
ret = await got('http://192.168.1.126/json');
|
|
} catch (error) {
|
|
console.log(error.response.body);
|
|
}
|
|
})();
|
|
while(ret === undefined) {
|
|
require('deasync').runLoopOnce();
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
const { parse } = require('querystring');
|
|
var moment = require('moment');
|
|
var Sync = require('sync');
|
|
|
|
app.use('/dht', (req, res) => {
|
|
try {
|
|
console.log("body:"+util.inspect(req.body));
|
|
var cmd = req.param('e');
|
|
console.log("cmd:" + cmd);
|
|
//console.log("HEADERS:" + util.inspect(req.headers));
|
|
switch(cmd)
|
|
{
|
|
//if(rq.method =="GET")
|
|
case 'setup':
|
|
console.log("/setup> Device is online: " + req.headers.mac);
|
|
break;
|
|
|
|
case 'ping':
|
|
var t = moment.duration(parseInt(req.param('uptime')), 'milliseconds');
|
|
var _message = req.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");
|
|
res.send(t.hours() + "h " + t.minutes() + "m " + t.seconds() +"s");
|
|
break;
|
|
|
|
case "now":
|
|
console.log("getting current conditions");
|
|
try {
|
|
const response = GetDht();
|
|
console.log(response.body);
|
|
res.send(response.body);
|
|
} catch (error) {
|
|
console.log("DHT Error:" + error);
|
|
}
|
|
console.log("got current conditions??");
|
|
break;
|
|
|
|
case 'ir':
|
|
console.log("got IR message!");
|
|
console.log(body);
|
|
try{
|
|
ob = JSON.parse(body);
|
|
if(ob.times)
|
|
{
|
|
console.log("GOT TIMING INFO:");
|
|
if(!ob.ir){
|
|
if(SendIRCommand(ob.times)) { res.sendStatus(200);}
|
|
else { res.sendStatus(500); }
|
|
} else {
|
|
console.log("It is from the IR reader. Ignoring...");
|
|
}
|
|
}
|
|
BroadcastWS(ob.info.replaceAll('\n','<br/>') + "<br/><br/>" + ob.descr.replaceAll(',', '<br/>') );
|
|
}catch(ex){
|
|
}
|
|
if(req.param('info') && req.param('descr') )
|
|
{
|
|
console.log("Got Url encoded IR message");
|
|
BroadcastWS(req.param('info').replaceAll('\n','<br/>') + "<br/><br/>" + req.param('descr').replaceAll(',', '<br/>'));
|
|
}
|
|
break;
|
|
}
|
|
res.sendStatus(200);
|
|
} catch (error) {
|
|
console.log("ESP Error:" + error);
|
|
//res.end();
|
|
//res.send(error);
|
|
}
|
|
});
|
|
|
|
function BroadcastWS(msg){
|
|
wss.clients.forEach(function each(client) {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(moment().format() +" : "+ msg);
|
|
}
|
|
});
|
|
}
|
|
|
|
String.prototype.replaceAll = function(search, replacement) {
|
|
var target = this;
|
|
return target.replace(new RegExp(search, 'g'), replacement);
|
|
};
|
|
|
|
app.get("/device/: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('/device/: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 });
|
|
});
|
|
});
|
|
|
|
|
|
//!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');
|
|
});
|
|
|
|
// store a reference to the original request function
|
|
// const originalRequest = httpsServer.request;
|
|
// // override the function
|
|
// httpsServer.request = function wrapMethodRequest(req) {
|
|
// console.log(req.host, req.body);
|
|
// // do something with the req here
|
|
// // ...
|
|
// // call the original 'request' function
|
|
// return originalRequest.apply(this, arguments);
|
|
// }
|
|
|
|
|
|
const wss = new WebSocket.Server({ server: httpsServer })//{ port: 8080 })
|
|
|
|
// //!database
|
|
// 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();
|
|
|
|
wss.on('connection', ws => {
|
|
ws.on('message', message => {
|
|
console.log(`Received message => ${message}`)
|
|
})
|
|
ws.send('ho!')
|
|
})
|
|
|
|
//StoreSensorReadings();
|
|
|
|
async function StoreSensorReadingsAsync()
|
|
{
|
|
console.log("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 {
|
|
SaveSensorReading(JSON.stringify(body))
|
|
resolve(body);
|
|
}
|
|
});
|
|
});
|
|
} catch(error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
|
|
function SaveSensorReading(data)
|
|
{
|
|
var params = [0, "A23_DHT", data];
|
|
let sql = `INSERT INTO devicemessages(device_id,field_name,field_value,timestamp)
|
|
VALUES (?,?,?,NOW());`;
|
|
con.query(sql,params,(err, r) => {
|
|
if (err) {
|
|
console.log("SQL: ", err);
|
|
}else{
|
|
console.log("inserted record: ", { id: r.insertId, ...params });
|
|
}
|
|
});
|
|
}
|
|
|
|
function StoreSensorReadings()
|
|
{
|
|
console.log("StoreSensorReadings");
|
|
(async () => {
|
|
try {
|
|
const dht = await got('http://192.168.1.126/json')
|
|
SaveSensorReading(dht.body);
|
|
} catch (error) { console.log("DHT Error:" + error); //..response.body);
|
|
}
|
|
})();
|
|
}
|