completed IoT sensor

This commit is contained in:
newtbot
2023-12-27 00:34:59 +08:00
parent 4be58724d2
commit f8e9755c12
10 changed files with 139 additions and 67 deletions

View File

@ -4,8 +4,8 @@
*/
const express = require("express");
const helmet = require('helmet')
app.use(helmet())
const app = express();
app.use(helmet())
const port = 80;
//disable x-powered-by header for security reasons

View File

@ -2,36 +2,47 @@ const mqtt = require('mqtt');
const fs = require('fs');
const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '../../.env') })
const { validateData } = require("../functions/validateData.js");
// Configuration
const brokerUrl = 'mqtt://mqtt.teeseng.uk';
const options = {
port: 8883, // MQTT broker port with TLS
port: 8883,
username: process.env.MQTT_USER,
password: process.env.MQTT_PASS,
protocol: 'mqtts', // Use MQTT over TLS
key: fs.readFileSync(path.resolve(__dirname, '../../cert/privkey.pem')), // Private key for the client
cert: fs.readFileSync(path.resolve(__dirname, '../../cert/cert.pem')), // Client certificate
key: fs.readFileSync(path.resolve(__dirname, '../../cert/privkey.pem')),
cert: fs.readFileSync(path.resolve(__dirname, '../../cert/cert.pem')),
};
// Create MQTT client
const client = mqtt.connect(brokerUrl, options);
module.exports = client;
// Event handlers
client.on('connect', () => {
console.log('Connected to MQTT broker');
client.subscribe('your-topic'); // Subscribe to a topic
client.subscribe('iot-data');
});
client.on('message', (topic, message) => {
console.log(`Received message on topic ${topic}: ${message}`);
// Additional processing for received message
//console.log(`Received message on topic ${topic}: ${message}`);
let data = JSON.parse(message);
if (validateData(data)) {
//upload to db logic here
}
else {
console.log("Data is invalid");
}
});
client.on('error', (err) => {
console.error('Error:', err);
client.end(); // Close the connection in case of an error
client.end();
});
client.on('end', () => {
console.log('Disconnected from MQTT broker');
client.reconnect = true;
}
);