source now in separate modules;
Implemented MQTT coms. Using Tasmota for ESP8266; IR working reliably
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,2 +1,3 @@
|
|||||||
/node_modules
|
/node_modules
|
||||||
/.vscode
|
/.vscode
|
||||||
|
access.log
|
||||||
|
|||||||
1
ac.js
1
ac.js
@@ -88,6 +88,7 @@ function GetState()
|
|||||||
{
|
{
|
||||||
return state.toString('hex').toUpperCase();
|
return state.toString('hex').toUpperCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
function GenerateTimingString()
|
function GenerateTimingString()
|
||||||
{
|
{
|
||||||
var arr = [AcTimes.HdrMark, AcTimes.HdrSpace, AcTimes.BitMark];
|
var arr = [AcTimes.HdrMark, AcTimes.HdrSpace, AcTimes.BitMark];
|
||||||
|
|||||||
425
dht.js
425
dht.js
@@ -4,156 +4,64 @@
|
|||||||
const util = require('util');
|
const util = require('util');
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const bodyParser = require('body-parser');
|
const bodyParser = require('body-parser');
|
||||||
|
|
||||||
|
const request = require('request');
|
||||||
|
const got = require('got');
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
const cors = require('cors');
|
const cors = require('cors');
|
||||||
const helmet = require('helmet');
|
const helmet = require('helmet');
|
||||||
const morgan = require('morgan');
|
const morgan = require('morgan');
|
||||||
const cron = require('node-cron');
|
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
|
//!https endpoint
|
||||||
var fs = require("fs");
|
var fs = require("fs");
|
||||||
var http = require('http');
|
var http = require('http');
|
||||||
var https = require('https');
|
var https = require('https');
|
||||||
try{
|
try{
|
||||||
var _privateKey = fs.readFileSync('/etc/letsencrypt/live/iot.d-popov.com/privkey.pem', 'utf8');
|
var SECURE_KEY = "/etc/letsencrypt/live/iot.d-popov.com/privkey.pem"; //__dirname + '/../../test/secure/tls-key.pem';
|
||||||
var _certificate = fs.readFileSync('/etc/letsencrypt/live/iot.d-popov.com/cert.pem', 'utf8');
|
var SECURE_CERT = "/etc/letsencrypt/live/iot.d-popov.com/cert.pem";
|
||||||
|
var _privateKey = fs.readFileSync(SECURE_KEY, 'utf8');
|
||||||
|
var _certificate = fs.readFileSync(SECURE_CERT, 'utf8');
|
||||||
var credentials = {key: _privateKey, cert: _certificate};
|
var credentials = {key: _privateKey, cert: _certificate};
|
||||||
}catch(ex){console.log("can't load certificates.");}
|
}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
|
// defining the Express app
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
// adding Helmet to enhance your API's security
|
|
||||||
app.use(helmet());
|
app.use(helmet());
|
||||||
|
|
||||||
app.use(bodyParser.urlencoded({ extended: true }));
|
app.use(bodyParser.urlencoded({ extended: true }));
|
||||||
app.use(bodyParser.json());
|
app.use(bodyParser.json());
|
||||||
app.use(express.static('public'));
|
app.use(express.static('public'));
|
||||||
|
|
||||||
// enabling CORS for all requests
|
|
||||||
app.use(cors());
|
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.set('view engine', 'ejs');
|
||||||
app.use(require('express-ejs-layouts'));//https://www.npmjs.com/package/express-ejs-layouts
|
app.use(require('express-ejs-layouts'));//https://www.npmjs.com/package/express-ejs-layouts
|
||||||
|
|
||||||
// adding morgan to log HTTP requests
|
// adding morgan to log HTTP requests
|
||||||
app.use(morgan('combined'));
|
app.use(morgan('combined'));
|
||||||
|
|
||||||
//defining endpoints
|
//defining endpoints
|
||||||
//!UI
|
//!UI
|
||||||
|
var auth = require('./src/auth.js');
|
||||||
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');
|
var ac = require('./ac.js');
|
||||||
|
var db = require('./src/db');
|
||||||
|
var ir = require('./src/devices/ir');
|
||||||
|
var u = require('./src/utils');
|
||||||
|
|
||||||
app.get('/accontrol', ensureLoggedIn, function(req, res){
|
|
||||||
|
|
||||||
|
app.use(auth.init());
|
||||||
|
app.get('/', function(req, res){ res.redirect('/n/login');});
|
||||||
|
|
||||||
|
app.get('/accontrol', auth.ensureLoggedIn_Orig,
|
||||||
|
function(req, res){
|
||||||
res.render('accontrol',{model:{data:req.body, user:req.user, command:"", info:""}});
|
res.render('accontrol',{model:{data:req.body, user:req.user, command:"", info:""}});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
app.post('/accontrol', ensureLoggedIn, function(req, res){
|
app.post('/accontrol',
|
||||||
|
//ensureLoggedIn,
|
||||||
|
function(req, res){
|
||||||
|
console.log("POST accontrol");
|
||||||
var sess=req.session;
|
var sess=req.session;
|
||||||
var model = { model: {user: req.user, data: req.body} };
|
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("power:" + req.body.power); console.log("heat:" + req.body.heat); console.log("temp:" + req.body.temp);
|
||||||
@@ -167,10 +75,13 @@ app.post('/accontrol', ensureLoggedIn, function(req, res){
|
|||||||
ac.Tlc112.SetFan(ac.FanSpeed.Med);
|
ac.Tlc112.SetFan(ac.FanSpeed.Med);
|
||||||
|
|
||||||
var code = ac.Tlc112.GetCommand();
|
var code = ac.Tlc112.GetCommand();
|
||||||
|
|
||||||
|
mqtt_client.publish('cmnd/', 'controller')
|
||||||
//break it
|
//break it
|
||||||
//code = code.substring(150);
|
//code = code.substring(150);
|
||||||
//console.log("RAW: " + code);
|
//console.log("RAW: " + code);
|
||||||
if(SendIRCommand(code))
|
// if(ir.SendCmd("http://192.168.1.126/irraw", code))
|
||||||
|
if(ir.SendCmd("http://192.168.1.126", code))
|
||||||
{
|
{
|
||||||
console.log("OK. Temp: " + req.body.temp);
|
console.log("OK. Temp: " + req.body.temp);
|
||||||
BroadcastWS(ac.Tlc112.GetState());
|
BroadcastWS(ac.Tlc112.GetState());
|
||||||
@@ -183,23 +94,7 @@ app.post('/accontrol', ensureLoggedIn, function(req, res){
|
|||||||
// res.render('accontrol',{model: {data: req.body, user: req.user, command: "", info: model.info}});
|
// res.render('accontrol',{model: {data: req.body, user: req.user, command: "", info: model.info}});
|
||||||
});
|
});
|
||||||
|
|
||||||
function SendIRCommand(code){
|
app.get('/chart', auth.ensureLoggedIn_Orig,
|
||||||
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){
|
function(req, res){
|
||||||
res.render('chart', { user: req.user });
|
res.render('chart', { user: req.user });
|
||||||
});
|
});
|
||||||
@@ -207,92 +102,13 @@ app.post('/accontrol', ensureLoggedIn, function(req, res){
|
|||||||
//Authentication --
|
//Authentication --
|
||||||
|
|
||||||
//! ESP HANDLERS
|
//! 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');
|
const { parse } = require('querystring');
|
||||||
var moment = require('moment');
|
var moment = require('moment');
|
||||||
var Sync = require('sync');
|
// var Sync = require('sync');
|
||||||
|
|
||||||
app.use('/dht', (req, res) => {
|
app.use('/dht', ir.html_handle_dht);
|
||||||
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){
|
function BroadcastWS(msg){
|
||||||
wss.clients.forEach(function each(client) {
|
wss.clients.forEach(function each(client) {
|
||||||
@@ -302,88 +118,42 @@ function BroadcastWS(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) => {
|
app.get("/device/:field_name", function (req, res) {
|
||||||
dht = con.query("SELECT * FROM devicemessages WHERE field_name=? OR ? IS NULL",
|
db.devicemessages.findByName(req.params.field_name, function (err, data) {
|
||||||
[req.params.field_name, req.params.field_name], (err, data) => {
|
if (!err) { res.send(data); }
|
||||||
//dht = con.query("SELECT * FROM devicemessages", (err, data) => {
|
else { console.log("error: ", err); }
|
||||||
if (!err) {
|
|
||||||
res.send(data);
|
|
||||||
} else {
|
|
||||||
console.log("error: ", err);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
app.put('/device/:device_id/:field_name/:field_value', (req, res) => {
|
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];
|
db.devicemessages.insert( req.params.device_id, req.params.field_name, req.params.field_value,
|
||||||
let sql = `INSERT INTO devicemessages(device_id,field_name,field_value,timestamp)
|
function (err, data) {
|
||||||
VALUES (?,?,?,NOW());`;
|
if (!err) { res.send(data); }
|
||||||
con.query(sql,params, (err, r) => {
|
else { console.log("error: ", err); }
|
||||||
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
|
//!Startup
|
||||||
|
|
||||||
var httpServer = http.createServer(app);
|
var wws;
|
||||||
if(credentials){
|
if(credentials){
|
||||||
var httpsServer = https.createServer(credentials, app);
|
var httpsServer = https.createServer(credentials, app);
|
||||||
httpsServer.listen(8443, () => {
|
httpsServer.listen(8443, () => {
|
||||||
console.log('HTTPS server listening on port 8443');
|
console.log('HTTPS server listening on port 8443');
|
||||||
});
|
});
|
||||||
|
wss = new WebSocket.Server({ server: httpsServer });
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var httpServer = http.createServer(app);
|
||||||
|
httpServer.listen(82, () => {
|
||||||
|
console.log('HTTP server listening on port 82');
|
||||||
|
});
|
||||||
|
wss = new WebSocket.Server({ port: 8080 });//not secure
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
// # ┌────────────── second (optional)
|
||||||
// # │ ┌──────────── minute
|
// # │ ┌──────────── minute
|
||||||
@@ -396,9 +166,12 @@ const wss = new WebSocket.Server({ server: httpsServer })//{ port: 8080 })
|
|||||||
// # * * * * * *
|
// # * * * * * *
|
||||||
cron.schedule(' */30 * * * *', () => {//cron.schedule('*/5 * * * * *', () => {
|
cron.schedule(' */30 * * * *', () => {//cron.schedule('*/5 * * * * *', () => {
|
||||||
console.log(new Date().toISOString() + ' running a task every 30 minutes');
|
console.log(new Date().toISOString() + ' running a task every 30 minutes');
|
||||||
StoreSensorReadingsAsync();
|
//StoreSensorReadings();
|
||||||
|
db.devicemessages.getFromDht('http://192.168.1.126/json');
|
||||||
}).start();
|
}).start();
|
||||||
|
|
||||||
|
//db.devicemessages.getFromDht('http://192.168.1.126/json');
|
||||||
|
|
||||||
wss.on('connection', ws => {
|
wss.on('connection', ws => {
|
||||||
ws.on('message', message => {
|
ws.on('message', message => {
|
||||||
console.log(`Received message => ${message}`)
|
console.log(`Received message => ${message}`)
|
||||||
@@ -406,48 +179,64 @@ wss.on('connection', ws => {
|
|||||||
ws.send('ho!')
|
ws.send('ho!')
|
||||||
})
|
})
|
||||||
|
|
||||||
//StoreSensorReadings();
|
|
||||||
|
|
||||||
async function StoreSensorReadingsAsync()
|
var mosca = require('mosca')
|
||||||
{
|
var mqtt_settings = {
|
||||||
console.log("StoreSensorReadingsAsync");
|
port:1884,
|
||||||
try {
|
secure : {
|
||||||
await new Promise(function(resolve, reject) {
|
port: 8444,
|
||||||
request('http://192.168.1.126/json', { json: true }, (err, res, body) => {
|
keyPath: SECURE_KEY,
|
||||||
if(err) { return reject(err); }
|
certPath: SECURE_CERT,
|
||||||
else {
|
|
||||||
SaveSensorReading(JSON.stringify(body))
|
|
||||||
resolve(body);
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
var mqtt = new mosca.Server(mqtt_settings);
|
||||||
|
mqtt.on('ready', function(){
|
||||||
|
console.log("MQTT ready on port " + mqtt_settings.port);
|
||||||
|
})
|
||||||
|
mqtt.on('clientConnected', function(){
|
||||||
|
console.log("MQTT client connected !");
|
||||||
});
|
});
|
||||||
});
|
|
||||||
} catch(error) {
|
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function SaveSensorReading(data)
|
var mqtt = require('mqtt')
|
||||||
|
var mqtt_client = mqtt.connect('mqtt://192.168.1.131')
|
||||||
|
mqtt_client.on('connect', function () {
|
||||||
|
console.log("MQTT connected. subscribing to topics");
|
||||||
|
mqtt_client.subscribe('tele/tasmota/STATE');
|
||||||
|
mqtt_client.subscribe('tele/tasmota/RESULT');//IR
|
||||||
|
mqtt_client.subscribe('tele/tasmota/INFO2');
|
||||||
|
mqtt_client.subscribe('tele/tasmota/SENSOR');//DHT
|
||||||
|
|
||||||
|
mqtt_client.subscribe('tasmota_3FD92D');
|
||||||
|
mqtt_client.subscribe('tele');
|
||||||
|
mqtt_client.subscribe('dht');
|
||||||
|
mqtt_client.subscribe('ir');
|
||||||
|
mqtt_client.publish('tasmota', 'controller')
|
||||||
|
});
|
||||||
|
// https://github.com/pauloromeira/Sonoff-Tasmota/wiki/Commands
|
||||||
|
//https://stevessmarthomeguide.com/setting-up-the-sonoff-tasmota-mqtt-switch/
|
||||||
|
mqtt_client.on('message', function (topic, message) {
|
||||||
|
var context = message.toString();
|
||||||
|
console.log("MMQT> " + topic + " : " + context);
|
||||||
|
if(topic === "tele/tasmota/SENSOR")
|
||||||
{
|
{
|
||||||
var params = [0, "A23_DHT", data];
|
var j = JSON.parse(message);
|
||||||
let sql = `INSERT INTO devicemessages(device_id,field_name,field_value,timestamp)
|
console.log("JSON> " + util.inspect(j));
|
||||||
VALUES (?,?,?,NOW());`;
|
if(j.DHT11 && j.DHT11.Humidity !== null)
|
||||||
con.query(sql,params,(err, r) => {
|
{
|
||||||
if (err) {
|
var msg = {
|
||||||
console.log("SQL: ", err);
|
dht:{
|
||||||
|
hum: j.DHT11.Humidity,
|
||||||
|
temp: j.DHT11.Temperature,
|
||||||
|
dew: j.DHT11.DewPoint
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
db.devicemessages.insert( 0, "A23_DHT", JSON.stringify(msg), function (err, data) {
|
||||||
|
if (!err) { console.log("success: "+ data);}
|
||||||
|
else { console.log("error: " + err); }
|
||||||
|
});
|
||||||
}else {
|
}else {
|
||||||
console.log("inserted record: ", { id: r.insertId, ...params });
|
console.log("got wrong DHT data: " + message );
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
}
|
|
||||||
|
|||||||
2972
package-lock.json
generated
2972
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -19,6 +19,8 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"body-parser": "^1.19.0",
|
"body-parser": "^1.19.0",
|
||||||
"connect-ensure-login": "^0.1.1",
|
"connect-ensure-login": "^0.1.1",
|
||||||
|
"cookie-auth": "^2.4.2",
|
||||||
|
"cookie-parser": "^1.4.5",
|
||||||
"cors": "2.8.5",
|
"cors": "2.8.5",
|
||||||
"deasync": "^0.1.19",
|
"deasync": "^0.1.19",
|
||||||
"ejs": "^3.0.2",
|
"ejs": "^3.0.2",
|
||||||
@@ -32,19 +34,20 @@
|
|||||||
"moment-timezone": "^0.5.13",
|
"moment-timezone": "^0.5.13",
|
||||||
"mongoose": "^5.9.7",
|
"mongoose": "^5.9.7",
|
||||||
"morgan": "^1.10.0",
|
"morgan": "^1.10.0",
|
||||||
|
"mosca": "^2.8.3",
|
||||||
"mysql": "^2.18.1",
|
"mysql": "^2.18.1",
|
||||||
"mysql2": "^2.1.0",
|
"mysql2": "^2.1.0",
|
||||||
"node-cron": "^2.0.3",
|
"node-cron": "^2.0.3",
|
||||||
"node-uuid": "^1.4.8",
|
"node-uuid": "^1.4.8",
|
||||||
"passport": "^0.4.1",
|
"passport": "^0.4.1",
|
||||||
"passport-auth0": "^1.3.2",
|
"passport-auth0": "^1.3.2",
|
||||||
|
"passport-cookie": "^1.0.6",
|
||||||
"passport-local": "^1.0.0",
|
"passport-local": "^1.0.0",
|
||||||
"plaintextparser": "^1.0.3",
|
"plaintextparser": "^1.0.3",
|
||||||
"request": "^2.88.2",
|
"request": "^2.88.2",
|
||||||
"sequelize": "^5.21.6",
|
"sequelize": "^5.21.6",
|
||||||
"sequelize-cli": "^5.5.1",
|
"sequelize-cli": "^5.5.1",
|
||||||
"swagger-ui-express": "^2.0.13",
|
"swagger-ui-express": "^2.0.13",
|
||||||
"sync": "^0.2.5",
|
|
||||||
"sync-request": "^4.0.2",
|
"sync-request": "^4.0.2",
|
||||||
"vash": "^0.13.0",
|
"vash": "^0.13.0",
|
||||||
"ws": "^7.2.3"
|
"ws": "^7.2.3"
|
||||||
|
|||||||
141
src/auth.js
Normal file
141
src/auth.js
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
|
||||||
|
// module.exports = function ensureLoggedIn(req, res, next) {
|
||||||
|
// if (req.isAuthenticated()) { return next(null); }
|
||||||
|
// res.redirect('/login');
|
||||||
|
// };
|
||||||
|
const util = require('util');
|
||||||
|
var app = require('express')();
|
||||||
|
|
||||||
|
var db = require('./db');
|
||||||
|
var passport = require('passport');
|
||||||
|
var Strategy = require('passport-local').Strategy;
|
||||||
|
var CookieStrategy = require('passport-cookie').Strategy;
|
||||||
|
|
||||||
|
var session = require('express-session');
|
||||||
|
const cookierParser = require('cookie-parser');
|
||||||
|
|
||||||
|
var ensureLoggedIn = require("connect-ensure-login").ensureLoggedIn("/n/login");
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
ensureLoggedIn_Orig: ensureLoggedIn,
|
||||||
|
ensureLoggedIn_P: function (req, res, next){passport.authenticate('local', {
|
||||||
|
successRedirect: '/n/accontrol',
|
||||||
|
failureRedirect: '/n/login' })},
|
||||||
|
passport: passport,
|
||||||
|
ensureLoggedIn_New: function (req, res, next) {
|
||||||
|
if (req.isAuthenticated()) {
|
||||||
|
console.log("auth OK");
|
||||||
|
return next(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("auth redirect");
|
||||||
|
res.redirect('/login');
|
||||||
|
},
|
||||||
|
ensureLoggedIn: function (options) {
|
||||||
|
if (typeof options == 'string') {
|
||||||
|
options = { redirectTo: options }
|
||||||
|
}
|
||||||
|
options = options || {};
|
||||||
|
|
||||||
|
var url = options.redirectTo || '/login';
|
||||||
|
var setReturnTo = (options.setReturnTo === undefined) ? true : options.setReturnTo;
|
||||||
|
return function(req, res, next) {
|
||||||
|
console.log("auth:" + req.isAuthenticated);
|
||||||
|
if (!req.isAuthenticated || !req.isAuthenticated()) {
|
||||||
|
if (setReturnTo && req.session) {
|
||||||
|
req.session.returnTo = req.originalUrl || req.url;
|
||||||
|
}
|
||||||
|
return res.redirect(url);
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
init: function () {
|
||||||
|
|
||||||
|
//! 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);
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
|
||||||
|
// passport.use(new CookieStrategy(
|
||||||
|
// function(token, done) {
|
||||||
|
// User.findByToken({ token: token }, function(err, user) {
|
||||||
|
// if (err) { return done(err); }
|
||||||
|
// if (!user) { return done(null, false); }
|
||||||
|
// return done(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) {
|
||||||
|
console.log("serializeUser:"+ util.inspect(user) );
|
||||||
|
cb(null, user.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
passport.deserializeUser(function(id, cb) {
|
||||||
|
console.log("deserializeUser:"+ id );
|
||||||
|
db.users.findById(id, function (err, user) {
|
||||||
|
if (err) { return cb(err); }
|
||||||
|
cb(null, user);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
app.use(session({
|
||||||
|
key: 'user_sid',
|
||||||
|
secret: 'че_първият_ще генерира-грешка',
|
||||||
|
resave: true,
|
||||||
|
saveUninitialized: false,
|
||||||
|
cookie: {
|
||||||
|
expires: 600000
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
app.use(cookierParser('abcdef-12345'))
|
||||||
|
|
||||||
|
app.use(passport.initialize());
|
||||||
|
app.use(passport.session());
|
||||||
|
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
};
|
||||||
69
src/db/database.js
Normal file
69
src/db/database.js
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
|
||||||
|
const Sequelize = require("sequelize")
|
||||||
|
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 sqlz = new Sequelize('iot', 'iot', '!iot_popovi',{dialect: 'mysql'})
|
||||||
|
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
|
||||||
|
});
|
||||||
|
|
||||||
|
var DeviceMessage = sqlz.define('devicemessage', {
|
||||||
|
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
|
||||||
|
device_id: { type: Sequelize.INTEGER, allowNull: false},
|
||||||
|
//id,"device_id","field_name","field_value","timestamp"
|
||||||
|
field_name: { type: Sequelize.STRING(120), allowNull: false},
|
||||||
|
field_value: { type: Sequelize.TEXT, allowNull: false},
|
||||||
|
timestamp: { type: Sequelize.DATE, allowNull: false},
|
||||||
|
});
|
||||||
|
|
||||||
|
var DeviceCommand = sqlz.define("command", {
|
||||||
|
device: { type: Sequelize.STRING},
|
||||||
|
command: {type: Sequelize.TEXT},
|
||||||
|
info: {type: Sequelize.STRING},
|
||||||
|
ac_power: Sequelize.BOOLEAN,
|
||||||
|
ac_mode: Sequelize.ENUM('Auto', 'Heat', 'Cool', "Fan"),
|
||||||
|
ac_fan: Sequelize.ENUM('Auto', 'Low', 'Med', "Hi"),
|
||||||
|
ac_temp: Sequelize.FLOAT,
|
||||||
|
ac_turbo: Sequelize.BOOLEAN,
|
||||||
|
ac_swing: Sequelize.BOOLEAN,
|
||||||
|
ac_display: Sequelize.BOOLEAN,
|
||||||
|
ac_econo: Sequelize.BOOLEAN,
|
||||||
|
ac_health: Sequelize.BOOLEAN,
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
sqlz.sync(
|
||||||
|
//{ force: true }
|
||||||
|
)
|
||||||
|
.then(() => {
|
||||||
|
console.log(`Database & tables created!`)
|
||||||
|
})
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
init: function() {
|
||||||
|
//console.log(DeviceCommand.rawAttributes.states.values);
|
||||||
|
sqlz.sync();
|
||||||
|
},
|
||||||
|
sqlz,
|
||||||
|
Device,
|
||||||
|
DeviceCommand,
|
||||||
|
DeviceMessage
|
||||||
|
//etc
|
||||||
|
}
|
||||||
56
src/db/devicemessages.js
Normal file
56
src/db/devicemessages.js
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
//devicemessages
|
||||||
|
var mysql = require('mysql');
|
||||||
|
var con = mysql.createConnection({
|
||||||
|
host : 'localhost',
|
||||||
|
user : 'iot',
|
||||||
|
password : '!iot_popovi',
|
||||||
|
database : 'iot'
|
||||||
|
});
|
||||||
|
|
||||||
|
const got = require('got');
|
||||||
|
|
||||||
|
exports.findByName = function(fieldName, cb) {
|
||||||
|
process.nextTick(function() {
|
||||||
|
con.query("SELECT * FROM devicemessages WHERE field_name=? OR ? IS NULL",
|
||||||
|
[fieldName, fieldName], (err, data) => {
|
||||||
|
if (!err) {
|
||||||
|
cb(null, data);
|
||||||
|
} else {
|
||||||
|
cb(new Error('SQL Error: ' + err));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.insert = function(device_id, field_name, value, cb){
|
||||||
|
var params = [device_id, field_name,value];
|
||||||
|
let sql = `INSERT INTO devicemessages(device_id,field_name,field_value,timestamp)
|
||||||
|
VALUES (?,?,?,NOW());`;
|
||||||
|
con.query(sql,params,(err, r) => {
|
||||||
|
//if(!cb) {return;}
|
||||||
|
if (err) {
|
||||||
|
console.log("error: ", err);
|
||||||
|
cb && cb(new Error('SQL Error: ' + err));
|
||||||
|
}else{
|
||||||
|
console.log("inserted record: ", { id: r.insertId});
|
||||||
|
cb && cb(null, { id: r.insertId, ...params });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
exports.getFromDht = function(url, cb)
|
||||||
|
{
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const dht = await got('http://192.168.1.126/json')
|
||||||
|
var j = JSON.parse(body);
|
||||||
|
if(j.dht && j.dht.hum <= 100 && j.dht.hum >= 0){
|
||||||
|
exports.insert(0, "A23_DHT", dht.body, cb);
|
||||||
|
}else {
|
||||||
|
console.log("Skip! Got invalid data from DHT: " + dht);
|
||||||
|
}
|
||||||
|
} catch (ex) {
|
||||||
|
console.log("DHT exception:" + ex);
|
||||||
|
cb && cb(new Error('SQL Error: ' + ex));
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
23
src/db/index.js
Normal file
23
src/db/index.js
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// //!database
|
||||||
|
var data = 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);
|
||||||
|
// });
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
exports.devicemessages = require('./devicemessages');
|
||||||
|
exports.users = require('./users');
|
||||||
28
src/db/users.js
Normal file
28
src/db/users.js
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
var records = [
|
||||||
|
{ id: 1, username: 'me', password: 'A23', displayName: 'admin', emails: [ { value: 'jack@example.com' } ] }
|
||||||
|
, { id: 2, username: 'db', password: 'doby', displayName: 'DB', emails: [ { value: 'jill@example.com' } ] }
|
||||||
|
, { id: 3, username: 'popov', password: 'Zelenakrav@', displayName: 'Doby', emails: [ { value: 'db@example.com' } ] }
|
||||||
|
];
|
||||||
|
|
||||||
|
exports.findById = function(id, cb) {
|
||||||
|
process.nextTick(function() {
|
||||||
|
var idx = id - 1;
|
||||||
|
if (records[idx]) {
|
||||||
|
cb(null, records[idx]);
|
||||||
|
} else {
|
||||||
|
cb(new Error('User ' + id + ' does not exist'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.findByUsername = function(username, cb) {
|
||||||
|
process.nextTick(function() {
|
||||||
|
for (var i = 0, len = records.length; i < len; i++) {
|
||||||
|
var record = records[i];
|
||||||
|
if (record.username === username) {
|
||||||
|
return cb(null, record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cb(null, null);
|
||||||
|
});
|
||||||
|
}
|
||||||
139
src/devices/ir.js
Normal file
139
src/devices/ir.js
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
|
||||||
|
const util = require('util');
|
||||||
|
const { parse } = require('querystring');
|
||||||
|
var moment = require('moment');
|
||||||
|
const got = require('got');
|
||||||
|
const request = require('request');
|
||||||
|
|
||||||
|
function GetDht() {
|
||||||
|
var result;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
var ret = await got('http://192.168.1.126/cm?cmnd=status%2010');
|
||||||
|
console.log("DHT: "+ util.inspect(ret.body));
|
||||||
|
var j = JSON.parse(ret.body);
|
||||||
|
console.log("JSON> " + util.inspect(j));
|
||||||
|
if(j.StatusSNS && j.StatusSNS.DHT11 && j.StatusSNS.DHT11.Humidity !== null)
|
||||||
|
{
|
||||||
|
result = {
|
||||||
|
dht:{
|
||||||
|
hum: j.StatusSNS.DHT11.Humidity,
|
||||||
|
temp: j.StatusSNS.DHT11.Temperature,
|
||||||
|
dew: j.StatusSNS.DHT11.DewPoint
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
while(result === undefined) {
|
||||||
|
require('deasync').runLoopOnce();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
exports.SendCmd = function (url, cmd)
|
||||||
|
{
|
||||||
|
url = url +"/cm?cmnd=irsend%200,"+cmd;
|
||||||
|
console.log("IR_SEND_RAW:" + url);
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
ret = await got(url);
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
// request.get(url,
|
||||||
|
// function (error, response, body) {
|
||||||
|
// if (!error && response.statusCode == 200) {
|
||||||
|
// console.log("GOT '" + util.inspect(body) + "'");
|
||||||
|
// return true;
|
||||||
|
// }else{
|
||||||
|
// console.log("ERROR on SendIRCommand:" + util.inspect(error));
|
||||||
|
// return false;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// );
|
||||||
|
|
||||||
|
// request.post(url, { form: { cmd: cmd } },
|
||||||
|
// function (error, response, body) {
|
||||||
|
// if (!error && response.statusCode == 200) {
|
||||||
|
// console.log("GOT '" + util.inspect(body) + "'");
|
||||||
|
// return true;
|
||||||
|
// }else{
|
||||||
|
// console.log("ERROR on SendIRCommand:" + util.inspect(error));
|
||||||
|
// return false;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// );
|
||||||
|
}
|
||||||
|
module.exports.html_handle_dht = function (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(req.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(req.params.uptime), 'milliseconds');
|
||||||
|
// var _message = req.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);
|
||||||
|
res.send(response);
|
||||||
|
} catch (error) {
|
||||||
|
console.log("DHT Error:" + error);
|
||||||
|
}
|
||||||
|
console.log("got current conditions??");
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'ir':
|
||||||
|
console.log("got IR message!");
|
||||||
|
console.log(req.body);
|
||||||
|
console.log(util.inspect(req.params));
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
4
src/utils.js
Normal file
4
src/utils.js
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
String.prototype.replaceAll = function(search, replacement) {
|
||||||
|
var target = this;
|
||||||
|
return target.replace(new RegExp(search, 'g'), replacement);
|
||||||
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<h2>AC Control for <%= model.user.username %></h2>
|
<h2>AC Control for <% if (model.user) {model.user.username; } %></h2>
|
||||||
<h4 id="current">Retrieving current conditions...</h4>
|
<h4 id="current">Retrieving current conditions...</h4>
|
||||||
<!-- class="form-inline" -->
|
<!-- class="form-inline" -->
|
||||||
<form id="accontrol" action="/n/accontrol" method="POST">
|
<form id="accontrol" action="/n/accontrol" method="POST">
|
||||||
@@ -59,7 +59,7 @@ INFO:
|
|||||||
window.onload = function () {
|
window.onload = function () {
|
||||||
$.getJSON("/n/dht?e=now", function(data){
|
$.getJSON("/n/dht?e=now", function(data){
|
||||||
if(data && data.dht){
|
if(data && data.dht){
|
||||||
$('#current').text( "A23 Currently is " + data.dht.temp + "°C, " + data.dht.hum +"% RH" );
|
$('#current').text( "A23 Currently is " + data.dht.temp + "°C, " + data.dht.hum +"% RH. Dew Point at:" + data.dht.dew );
|
||||||
}else {
|
}else {
|
||||||
//chart.title.set("text", "A23 conditions");
|
//chart.title.set("text", "A23 conditions");
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user