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

@ -0,0 +1,34 @@
const { iot_sensor_data } = require("./modules/IoT-sensor");
const client = require("./modules/mqtt");
function publishData() {
let data = iot_sensor_data();
// MQTT logic
client.publish("iot-data", JSON.stringify(data), { qos: 1 }, (err) => {
if (err) {
console.error("Error publishing message:", err);
} else {
console.log("Message published");
}
});
}
client.on("connect", () => {
console.log("Connected to MQTT broker");
publishData();
});
client.on("end", () => {
console.log("Disconnected from MQTT broker");
client.reconnect = true;
});
client.on("error", (err) => {
console.error("Error:", err);
client.end();
});
//every 15 minutes
//setInterval(publishData, 900000);
setInterval(publishData, 600);

View File

@ -51,15 +51,9 @@ function getRandomValue(min, max) {
return Math.random() * (max - min) + min;
}
async function iot_sensor_data() {
//5 minutes
setInterval(() => {
var json = generateRandomData();
console.log(json);
}, 600); //every 1 second
function iot_sensor_data() {
return generateRandomData();
}
iot_sensor_data()
module.exports = { iot_sensor_data }
module.exports = { iot_sensor_data };

View File

@ -3,43 +3,17 @@ const fs = require('fs');
const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '../../.env') })
// 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
protocol: 'mqtts',
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
// Publish a message
client.publish('your-topic', 'Hello MQTT with TLS!', { qos: 1 }, (err) => {
if (err) {
console.error('Error publishing message:', err);
} else {
console.log('Message published');
}
client.end(); // Close the connection after publishing
});
});
client.on('message', (topic, message) => {
console.log(`Received message on topic ${topic}: ${message}`);
client.end(); // Close the connection after receiving a message
});
client.on('error', (err) => {
console.error('Error:', err);
client.end(); // Close the connection in case of an error
});