master^2
Varun 7 months ago
parent 827b9406e9
commit 992eab6eba

@ -5896,93 +5896,98 @@ exports.getBlockData = async (req, reply) => {
const mqtt = require('mqtt'); const mqtt = require('mqtt');
require('dotenv').config(); require('dotenv').config();
// **Persistent MQTT Connection** const activeClients = new Map(); // Store active clients per hw_Id
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 subscribedTopics = new Set(); // Start a persistent temp client to listen for multiple devices
const activeDevices = new Set(); // Keep track of active devices const tempClientId = `mqtt_temp_${Math.random().toString(16).substr(2, 8)}`;
const tempClient = connectMQTT(tempClientId, true);
client.on('connect', () => { // Function to create an MQTT client
console.log('✅ Connected to MQTT broker'); function connectMQTT(clientId, isTemp = false, hw_Id = null) {
console.log(`🔄 Connecting to MQTT with clientId: ${clientId}`);
// **Ensure re-subscriptions after reconnect** const newClient = mqtt.connect('mqtt://35.207.198.4:1883', {
subscribedTopics.forEach(topic => { clientId,
client.subscribe(topic, { qos: 1 }, (err) => { clean: false, // Ensures session persistence
if (err) { reconnectPeriod: 2000, // Reconnect every 2 seconds
console.error(`❌ Error resubscribing to ${topic}:`, err); keepalive: 60, // Maintain connection
} else {
console.log(`🔄 Resubscribed to ${topic}`);
}
});
}); });
// **Subscribe to new device announcements** newClient.on('connect', () => {
client.subscribe('water/iot-data/announce', { qos: 1 }, (err) => { console.log(`✅ Connected to MQTT broker as ${clientId}`);
if (err) {
console.error('❌ Error subscribing to announcement topic:', err); if (isTemp) {
} else { // Temporary client listens for multiple device announcements
console.log('📡 Subscribed to water/iot-data/announce'); 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) => { newClient.on('message', async (topic, message) => {
console.log(`📩 Message received on topic ${topic}: ${message.toString()}`); console.log(`📩 Message received on topic ${topic}: ${message.toString()}`);
try { try {
const data = JSON.parse(message.toString()); const data = JSON.parse(message.toString());
// **Handle device announcements** if (topic === 'water/iot-data/announce' && isTemp) {
if (topic === 'water/iot-data/announce') { if (!data.objects || !data.objects.hw_Id) {
if (!data.objects || !data.objects.hw_Id) { console.error("❌ Invalid announcement format. Missing hw_Id.");
console.error("❌ Invalid announcement format. Missing hw_Id."); return;
return; }
}
const hw_Id = data.objects.hw_Id; const hw_Id = data.objects.hw_Id;
const deviceTopic = `water/iot-data/${hw_Id}`; console.log(`🔄 New Device Found! hw_Id: ${hw_Id}`);
if (!subscribedTopics.has(deviceTopic)) { // If this device hasn't been connected yet, create a client for it
client.subscribe(deviceTopic, { qos: 1 }, (err) => { if (!activeClients.has(hw_Id)) {
if (err) { console.log(`🔄 Creating new MQTT client for hw_Id: ${hw_Id}`);
console.error(`❌ Error subscribing to ${deviceTopic}:`, err); activeClients.set(hw_Id, connectMQTT(`mqtt_client_${hw_Id}`, false, hw_Id));
} else { }
console.log(`✅ Subscribed to ${deviceTopic}`); }
subscribedTopics.add(deviceTopic);
activeDevices.add(hw_Id); if (topic.startsWith('water/iot-data/')) {
console.log('📡 Active Devices:', Array.from(activeDevices)); setImmediate(() => {
console.log(`🚀 Processing IoT Data for topic: ${topic}`);
// ✅ **Now also process data** const deviceHwId = topic.split('/')[2];
processIotData(hw_Id, data); 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** newClient.on('error', (err) => console.error('❌ MQTT Error:', err));
if (topic.startsWith('water/iot-data/')) { newClient.on('close', () => console.log(`⚠️ MQTT Connection Closed for ${clientId}`));
setImmediate(() => { newClient.on('offline', () => console.log(`⚠️ MQTT Broker Offline for ${clientId}`));
console.log(`🚀 Entering processIotData() for topic: ${topic}`);
const hw_Id = topic.split('/')[2]; return newClient;
processIotData(hw_Id, data); }
});
} // Function to log active MQTT clients
} catch (err) { function logActiveClients() {
console.error('❌ Error processing message:', err.message); 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) { async function processIotData(hw_Id, data) {
try { try {
@ -6098,14 +6103,14 @@ async function processIotData(hw_Id, data) {
} }
function logSets() { // function logSets() {
console.log("Subscribed Topics:", Array.from(subscribedTopics)); // console.log("Subscribed Topics:", Array.from(subscribedTopics));
console.log("Active Devices:", Array.from(activeDevices)); // console.log("Active Devices:", Array.from(activeDevices));
console.log("motorIntervals:", motorIntervals); // console.log("motorIntervals:", motorIntervals);
} // }
// Call logSets every 30 seconds // // Call logSets every 30 seconds
setInterval(logSets, 30000); // setInterval(logSets, 30000);

Loading…
Cancel
Save