sockets work

This commit is contained in:
William Mantly 2024-01-23 21:17:27 -05:00
parent 375ec679f2
commit e91bb70b33
7 changed files with 37 additions and 5 deletions

4
.env_localDB Normal file
View File

@ -0,0 +1,4 @@
DB_name="eco_saver"
DB_storage="database_test.sqlite"
DB_dialect="sqlite"
DB_logginf=false

View File

@ -5,6 +5,7 @@ const app = express();
const port = 3000;
const ejs = require("ejs");
module.exports = app;
app.use(express.json());
app.set("json spaces", 2);
@ -17,6 +18,9 @@ const limiter = rateLimit({
legacyHeaders: false, // Disable the `X-RateLimit-*` headers.
});
// Hold list of functions to run when the server is ready
app.onListen = [function(){console.log('Express is ready')}];
// Apply the rate limiting middleware to all requests.
app.use(limiter);
@ -84,4 +88,3 @@ app.use(function (err, req, res, next) {
});
module.exports = app ;

View File

@ -93,4 +93,8 @@ function onListening() {
: 'port ' + addr.port;
console.log('Listening on ' + bind);
// execute list of functions when app is ready
for(let listener of app.onListen){
listener()
}
}

View File

@ -19,7 +19,6 @@ const sequelize = new Sequelize(
ssl: {
ca: fs.readFileSync(path.resolve(__dirname, '../cert/DigiCertGlobalRootCA.crt.pem')),
},
},
},
);

View File

@ -1,6 +1,8 @@
const { Op, Sequelize } = require("sequelize");
const { sequelize } = require("../database/mySql.js");
const { sensorDataModel } = require("../database/model/sensorDataModel.js");
const { Op, Sequelize } = require("sequelize");
const socket = require('../functions/socket');
// const { io } = require('../app')
//helper function to convert month name to month number
//https://stackoverflow.com/questions/13566552/easiest-way-to-convert-month-name-to-month-number-in-js-jan-01
@ -24,6 +26,10 @@ async function addSensorData(id_sensor, id_location, sensordata) {
locationid: id_location,
measurement: sensordata,
});
socket.emit('sensordata:new', sensorData)
return sensorData;
}
async function updateSensorData(id, id_sensor, id_location, sensordata) {

View File

@ -0,0 +1,16 @@
const app = require("../app");
const socket = {};
app.onListen.push(function(){
socket.emit = (topic, data) => app.io.emit(topic, data);
app.io.on('connection', (socket) => {
console.log('User connected via WebsSocket')
});
app.io.on('disconnect', (socket) => {
console.log('User disconnect via WebsSocket')
});
});
module.exports = socket;

View File

@ -24,8 +24,8 @@ router.get("/", async (req, res, next) => {
router.post("/new", async (req, res, next) => {
try {
const { id_sensor, id_location, sensordata } = req.body;
await addSensorData(id_sensor, id_location, sensordata);
res.sendStatus(200).json({ message: "SensorData " + id + " added" });
let data = await addSensorData(id_sensor, id_location, sensordata);
res.json({ message: "SensorData " + data.id + " added", ...data });
} catch (error) {
console.error(error);
next(error);