Lots of remote changes.
dht is now processing commands! hurray!
This commit is contained in:
276
dht.js
276
dht.js
@@ -1,6 +1,7 @@
|
||||
// ./src/index.js
|
||||
|
||||
// importing the dependencies
|
||||
const util = require('util');
|
||||
const express = require('express');
|
||||
const bodyParser = require('body-parser');
|
||||
const cors = require('cors');
|
||||
@@ -9,7 +10,81 @@ const morgan = require('morgan');
|
||||
const cron = require('node-cron');
|
||||
const request = require('request');
|
||||
const got = require('got');
|
||||
const Sequelize = require("sequelize")
|
||||
|
||||
//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");
|
||||
@@ -29,56 +104,164 @@ var con = mysql.createConnection({
|
||||
password : '!iot_popovi',
|
||||
database : 'iot'
|
||||
});
|
||||
var sqlz = new Sequelize('iot', 'iot', '!iot_popovi',{dialect: 'mysql'})
|
||||
|
||||
const mongoose = require('mongoose');
|
||||
const Schema = mongoose.Schema;
|
||||
|
||||
let DeviceMessageSchema = new Schema({
|
||||
_id: {type: Number, required: true},
|
||||
device_id: {type: String, required: true, max: 100}
|
||||
});
|
||||
|
||||
let DevicesSchema = new Schema({
|
||||
id: {type: Number, required: true},
|
||||
url: {type: String, required: true, max: 100}
|
||||
});
|
||||
|
||||
var Device = sqlz.define('device', {
|
||||
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
|
||||
name: Sequelize.STRING,
|
||||
baseurl: Sequelize.TEXT,
|
||||
apikey: Sequelize.TEXT,
|
||||
//config: Sequelize.JSON,
|
||||
lastseen: Sequelize.DATE
|
||||
});
|
||||
|
||||
sqlz.sync();
|
||||
|
||||
|
||||
// defining the Express app
|
||||
const app = express();
|
||||
var httpServer = http.createServer(app);
|
||||
var httpsServer = https.createServer(credentials, app);
|
||||
|
||||
// defining an array to work as the database (temporary solution)
|
||||
const ads = [
|
||||
{title: 'Hello, world (again)!'}
|
||||
];
|
||||
|
||||
// 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'));
|
||||
//app.use(morgan('combined'));
|
||||
|
||||
// defining endpoints
|
||||
|
||||
//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){
|
||||
console.log("viewing /accontrol as authenticated user:"+ req.user);
|
||||
res.render('accontrol', { model: { user: req.user, data:{} }});
|
||||
});
|
||||
|
||||
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);
|
||||
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 --
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
app.use('/ir', bodyParser.text(), function(rq, rs) {
|
||||
console.log("REQ:"+rq.headers);
|
||||
console.log("BODY:"+rq.body);
|
||||
rs.sendStatus(200);
|
||||
});
|
||||
|
||||
// app.post('/ir', (req, res) => {
|
||||
// (async (res) => {
|
||||
// try {
|
||||
// //console.log(req.params);
|
||||
// console.log("REQ:"+req.body);
|
||||
// console.log(`post/${util.inspect(req.body,false,null)}`);
|
||||
// res.sendStatus(200);
|
||||
// } catch (error) {
|
||||
// console.log("IR Error:" + error); //..response.body);
|
||||
// }
|
||||
// })(res);
|
||||
// });
|
||||
|
||||
// defining an endpoint to return all ads
|
||||
app.get('/dht', (req, res) => { (async (res) => {
|
||||
try {
|
||||
const response = await got('http://192.168.1.126/json')
|
||||
@@ -126,16 +309,37 @@ app.put('/dht/:device_id/:field_name/:field_value', (req, res) => {
|
||||
|
||||
});
|
||||
|
||||
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);
|
||||
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 device = Device.build({
|
||||
|
||||
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);}
|
||||
// )
|
||||
@@ -157,7 +361,7 @@ cron.schedule(' */30 * * * *', () => {//cron.schedule('*/5 * * * * *', () =>
|
||||
StoreSensorReadingsAsync();
|
||||
}).start();
|
||||
|
||||
StoreSensorReadings();
|
||||
//StoreSensorReadings();
|
||||
|
||||
async function StoreSensorReadingsAsync()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user