From 992eab6eba3e2768280582ee578eab305c082edc Mon Sep 17 00:00:00 2001 From: Varun Date: Tue, 18 Mar 2025 15:26:23 +0530 Subject: [PATCH] changes --- src/controllers/tanksController.js | 159 +++++++++++++++-------------- 1 file changed, 82 insertions(+), 77 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index f40ef152..041f792b 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -5896,93 +5896,98 @@ exports.getBlockData = async (req, reply) => { const mqtt = require('mqtt'); require('dotenv').config(); -// **Persistent MQTT Connection** -const client = mqtt.connect('mqtt://35.207.198.4:1883', { - clientId: `mqtt_server_${Math.random().toString(16).substr(2, 8)}`, - clean: false, // Ensures MQTT retains subscriptions - reconnectPeriod: 2000, // Reconnect every 2 seconds -}); +const activeClients = new Map(); // Store active clients per hw_Id -const subscribedTopics = new Set(); -const activeDevices = new Set(); // Keep track of active devices +// Start a persistent temp client to listen for multiple devices +const tempClientId = `mqtt_temp_${Math.random().toString(16).substr(2, 8)}`; +const tempClient = connectMQTT(tempClientId, true); -client.on('connect', () => { - console.log('āœ… Connected to MQTT broker'); +// Function to create an MQTT client +function connectMQTT(clientId, isTemp = false, hw_Id = null) { + console.log(`šŸ”„ Connecting to MQTT with clientId: ${clientId}`); - // **Ensure re-subscriptions after reconnect** - subscribedTopics.forEach(topic => { - client.subscribe(topic, { qos: 1 }, (err) => { - if (err) { - console.error(`āŒ Error resubscribing to ${topic}:`, err); - } else { - console.log(`šŸ”„ Resubscribed to ${topic}`); - } - }); + const newClient = mqtt.connect('mqtt://35.207.198.4:1883', { + clientId, + clean: false, // Ensures session persistence + reconnectPeriod: 2000, // Reconnect every 2 seconds + keepalive: 60, // Maintain connection }); - // **Subscribe to new device announcements** - client.subscribe('water/iot-data/announce', { qos: 1 }, (err) => { - if (err) { - console.error('āŒ Error subscribing to announcement topic:', err); - } else { - console.log('šŸ“” Subscribed to water/iot-data/announce'); + newClient.on('connect', () => { + console.log(`āœ… Connected to MQTT broker as ${clientId}`); + + if (isTemp) { + // Temporary client listens for multiple device announcements + newClient.subscribe('water/iot-data/announce', { qos: 1 }, (err) => { + if (err) { + console.error('āŒ Error subscribing to announcement topic:', err); + } else { + console.log('šŸ“” Subscribed to water/iot-data/announce'); + } + }); + } else if (hw_Id) { + // If this is the actual device client, subscribe to its topic + const deviceTopic = `water/iot-data/${hw_Id}`; + newClient.subscribe(deviceTopic, { qos: 1 }, (err) => { + if (err) { + console.error(`āŒ Error subscribing to ${deviceTopic}:`, err); + } else { + console.log(`āœ… Subscribed to ${deviceTopic}`); + logActiveClients(); // Log clients after each new device connects + } + }); } }); -}); -client.on('message', async (topic, message) => { - console.log(`šŸ“© Message received on topic ${topic}: ${message.toString()}`); + newClient.on('message', async (topic, message) => { + console.log(`šŸ“© Message received on topic ${topic}: ${message.toString()}`); - try { - const data = JSON.parse(message.toString()); + try { + const data = JSON.parse(message.toString()); - // **Handle device announcements** - if (topic === 'water/iot-data/announce') { - if (!data.objects || !data.objects.hw_Id) { - console.error("āŒ Invalid announcement format. Missing hw_Id."); - return; - } + if (topic === 'water/iot-data/announce' && isTemp) { + if (!data.objects || !data.objects.hw_Id) { + console.error("āŒ Invalid announcement format. Missing hw_Id."); + return; + } - const hw_Id = data.objects.hw_Id; - const deviceTopic = `water/iot-data/${hw_Id}`; + const hw_Id = data.objects.hw_Id; + console.log(`šŸ”„ New Device Found! hw_Id: ${hw_Id}`); - if (!subscribedTopics.has(deviceTopic)) { - client.subscribe(deviceTopic, { qos: 1 }, (err) => { - if (err) { - console.error(`āŒ Error subscribing to ${deviceTopic}:`, err); - } else { - console.log(`āœ… Subscribed to ${deviceTopic}`); - subscribedTopics.add(deviceTopic); - activeDevices.add(hw_Id); - console.log('šŸ“” Active Devices:', Array.from(activeDevices)); - - // āœ… **Now also process data** - processIotData(hw_Id, data); - } + // If this device hasn't been connected yet, create a client for it + if (!activeClients.has(hw_Id)) { + console.log(`šŸ”„ Creating new MQTT client for hw_Id: ${hw_Id}`); + activeClients.set(hw_Id, connectMQTT(`mqtt_client_${hw_Id}`, false, hw_Id)); + } + } + + if (topic.startsWith('water/iot-data/')) { + setImmediate(() => { + console.log(`šŸš€ Processing IoT Data for topic: ${topic}`); + const deviceHwId = topic.split('/')[2]; + processIotData(deviceHwId, data); }); - } else { - console.log(`šŸ”„ Already subscribed to ${deviceTopic}, processing data.`); - processIotData(hw_Id, data); } - return; + } catch (err) { + console.error('āŒ Error processing message:', err.message); } + }); - // **Process IoT Data for device topics** - if (topic.startsWith('water/iot-data/')) { - setImmediate(() => { - console.log(`šŸš€ Entering processIotData() for topic: ${topic}`); - const hw_Id = topic.split('/')[2]; - processIotData(hw_Id, data); - }); - } - } catch (err) { - console.error('āŒ Error processing message:', err.message); - } -}); + newClient.on('error', (err) => console.error('āŒ MQTT Error:', err)); + newClient.on('close', () => console.log(`āš ļø MQTT Connection Closed for ${clientId}`)); + newClient.on('offline', () => console.log(`āš ļø MQTT Broker Offline for ${clientId}`)); + + return newClient; +} + +// Function to log active MQTT clients +function logActiveClients() { + console.log(`\nšŸ“” Active MQTT Clients:`); + activeClients.forEach((client, hw_Id) => { + console.log(` šŸ”¹ Client ID: mqtt_client_${hw_Id}`); + }); +} -client.on('error', (err) => console.error('āŒ MQTT Error:', err)); -client.on('close', () => console.log('āš ļø MQTT Connection Closed.')); -client.on('offline', () => console.log('āš ļø MQTT Broker Offline.')); async function processIotData(hw_Id, data) { try { @@ -6098,14 +6103,14 @@ async function processIotData(hw_Id, data) { } -function logSets() { - console.log("Subscribed Topics:", Array.from(subscribedTopics)); - console.log("Active Devices:", Array.from(activeDevices)); - console.log("motorIntervals:", motorIntervals); -} +// function logSets() { +// console.log("Subscribed Topics:", Array.from(subscribedTopics)); +// console.log("Active Devices:", Array.from(activeDevices)); +// console.log("motorIntervals:", motorIntervals); +// } -// Call logSets every 30 seconds -setInterval(logSets, 30000); +// // Call logSets every 30 seconds +// setInterval(logSets, 30000);