initial commit: dht client
This commit is contained in:
211
dht.js
Normal file
211
dht.js
Normal file
@@ -0,0 +1,211 @@
|
||||
// ./src/index.js
|
||||
|
||||
// importing the dependencies
|
||||
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 Sequelize = require("sequelize")
|
||||
|
||||
//!https endpoint
|
||||
var fs = require("fs");
|
||||
var http = require('http');
|
||||
var https = require('https');
|
||||
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};
|
||||
|
||||
|
||||
|
||||
//!database
|
||||
var mysql = require('mysql');
|
||||
var con = mysql.createConnection({
|
||||
host : 'localhost',
|
||||
user : 'iot',
|
||||
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.json());
|
||||
|
||||
// enabling CORS for all requests
|
||||
app.use(cors());
|
||||
|
||||
// adding morgan to log HTTP requests
|
||||
app.use(morgan('combined'));
|
||||
|
||||
// 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')
|
||||
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');
|
||||
|
||||
});
|
||||
|
||||
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({
|
||||
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);
|
||||
} })();
|
||||
}
|
||||
Reference in New Issue
Block a user