88 lines
2.5 KiB
JavaScript
88 lines
2.5 KiB
JavaScript
// ./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 request = require('request');
|
|
const WebSocket = require('ws');
|
|
var fs = require("fs");
|
|
var http = require('http');
|
|
// defining the Express app
|
|
const app = express();
|
|
var httpServer = http.createServer(app);
|
|
// 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'));
|
|
|
|
//!UI & resources
|
|
app.use(express.static('public'));
|
|
app.set('view engine', 'ejs');
|
|
app.use(require('express-ejs-layouts'));//https://www.npmjs.com/package/express-ejs-layouts
|
|
//defining endpoints
|
|
|
|
//!other sources
|
|
var auth = require('./src/auth.js');
|
|
var db = require('./src/db');
|
|
var mqtt = require('./src/mqtt.js');
|
|
|
|
|
|
const env = process.env.NODE_ENV || 'development';
|
|
console.log("ENV: %s", env);
|
|
const config = require(__dirname + '/config/config.json')[env];
|
|
config.gardenIP = process.env.GARDEN_IP || config.gardenIP
|
|
|
|
// defining HTTP endpoints
|
|
app.get('/', (req, res) => {
|
|
res.redirect('/garden');
|
|
// res.send([
|
|
// {title: 'Hello, world (again)!'}
|
|
// ]);
|
|
});
|
|
|
|
|
|
app.get('/garden/:days?', function(req, res){
|
|
res.render('chartGarden', {model:req.params});
|
|
});
|
|
|
|
app.get("/device/:field_name/:days?", function (req, res) {
|
|
db.devicemessages.findByName(req.params.field_name, req.params.days, function (err, data) {
|
|
if (!err) { res.send(data); }
|
|
else { console.log("error: ", err); }
|
|
});
|
|
});
|
|
|
|
|
|
//ToDo: do also MQTT
|
|
app.use('/water',function(req, res){
|
|
var time = req.query.t;
|
|
console.log("Watering cmd for: " + time);
|
|
request('http://'+config.gardenIP+'/tools?cmd=event,manualwatering='+ time, { json: true }, (err, res, body) => {
|
|
if (err) { return console.log("Problem watering: " + err); }
|
|
console.log("Watering cmd successfully sent!");
|
|
});
|
|
});
|
|
app.use('/waterStop',function(req, res){
|
|
request('http://'+config.gardenIP+'/tools?cmd=event,stopwatering', { json: true }, (err, res, body) => {
|
|
if (err) { return console.log("Problem watering: " + err); }
|
|
console.log("STOP watering cmd sent!");
|
|
});
|
|
});
|
|
|
|
|
|
// starting the server
|
|
//app.listen(3001, () => {
|
|
//console.log('listening on port 3001');
|
|
//});
|
|
|
|
httpServer.listen(2080, () => {
|
|
console.log('index.js: httpServer listening on port 2080');
|
|
});
|