changes in mqtt

master
Varun 9 months ago
parent 845729fbb2
commit 5c7ab91a5e

@ -3381,7 +3381,7 @@ exports.IotDevice = async (req, reply) => {
} }
}; };
console.log("this is for testing push")
exports.IotDeviceforstandalonedevice = async (req, reply) => { exports.IotDeviceforstandalonedevice = async (req, reply) => {
try { try {
@ -4624,17 +4624,40 @@ exports.getBlockData = async (req, reply) => {
const mqtt = require('mqtt'); const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker
// Temporary generic client ID to start
let client;
let isConnected = false;
const connectToBroker = (hw_Id) => {
if (!client) {
client = mqtt.connect('mqtt://35.207.198.4:1883', { clientId: `iot-client-${hw_Id}` });
client.on('connect', () => {
isConnected = true;
console.log(`Connected to MQTT broker as client iot-client-${hw_Id}`);
client.subscribe('water/iot-data', { qos: 1 }, (err) => {
if (err) {
console.error('Error subscribing to topic:', err);
} else {
console.log('Subscribed to water/iot-data topic');
}
});
});
client.on('close', () => {
isConnected = false;
console.log('Disconnected from MQTT broker');
});
}
};
// Handling incoming MQTT messages
client = mqtt.connect('mqtt://35.207.198.4:1883', { clientId: `temp-client-${Math.random().toString(16).slice(2, 10)}` });
client.on('connect', () => { client.on('connect', () => {
console.log('Connected to MQTT broker'); console.log('Connected temporarily to MQTT broker');
client.subscribe('water/iot-data', (err) => { client.subscribe('water/iot-data', { qos: 1 });
if (err) {
console.error('Error subscribing to topic:', err);
} else {
console.log('Subscribed to water/iot-data topic');
}
});
}); });
// Handling incoming MQTT messages // Handling incoming MQTT messages
@ -4645,6 +4668,9 @@ client.on('message', async (topic, message) => {
try { try {
const data = JSON.parse(message.toString()); const data = JSON.parse(message.toString());
const { hw_Id, Motor_status, tanks } = data.objects; // Updated variable names according to new format const { hw_Id, Motor_status, tanks } = data.objects; // Updated variable names according to new format
if (!isConnected) {
connectToBroker(hw_Id); // Reconnect with the correct hw_Id
}
// Get the current date and time in the required format // Get the current date and time in the required format
const currentDate = new Date(); const currentDate = new Date();

Loading…
Cancel
Save