changes reverted in mqtt

master^2
Varun 7 months ago
parent 992eab6eba
commit 55b207f076

@ -5893,79 +5893,88 @@ exports.getBlockData = async (req, reply) => {
const mqtt = require('mqtt');
require('dotenv').config();
const activeClients = new Map(); // Store active clients per hw_Id
// 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);
// Function to create an MQTT client const mqtt = require('mqtt');
function connectMQTT(clientId, isTemp = false, hw_Id = null) { require('dotenv').config();
console.log(`🔄 Connecting to MQTT with clientId: ${clientId}`);
const newClient = mqtt.connect('mqtt://35.207.198.4:1883', { // **Persistent MQTT Connection**
clientId, const client = mqtt.connect('mqtt://35.207.198.4:1883', {
clean: false, // Ensures session persistence clientId: `mqtt_server_${Math.random().toString(16).substr(2, 8)}`,
clean: false, // Ensures MQTT retains subscriptions
reconnectPeriod: 2000, // Reconnect every 2 seconds reconnectPeriod: 2000, // Reconnect every 2 seconds
keepalive: 60, // Maintain connection
}); });
newClient.on('connect', () => { const subscribedTopics = new Set();
console.log(`✅ Connected to MQTT broker as ${clientId}`); const activeDevices = new Set(); // Keep track of active devices
if (isTemp) { client.on('connect', () => {
// Temporary client listens for multiple device announcements console.log('✅ Connected to MQTT broker');
newClient.subscribe('water/iot-data/announce', { qos: 1 }, (err) => {
// **Ensure re-subscriptions after reconnect**
subscribedTopics.forEach(topic => {
client.subscribe(topic, { qos: 1 }, (err) => {
if (err) { if (err) {
console.error('❌ Error subscribing to announcement topic:', err); console.error(`❌ Error resubscribing to ${topic}:`, err);
} else { } else {
console.log('📡 Subscribed to water/iot-data/announce'); console.log(`🔄 Resubscribed to ${topic}`);
} }
}); });
} else if (hw_Id) { });
// If this is the actual device client, subscribe to its topic
const deviceTopic = `water/iot-data/${hw_Id}`; // **Subscribe to new device announcements**
newClient.subscribe(deviceTopic, { qos: 1 }, (err) => { client.subscribe('water/iot-data/announce', { qos: 1 }, (err) => {
if (err) { if (err) {
console.error(`❌ Error subscribing to ${deviceTopic}:`, err); console.error('❌ Error subscribing to announcement topic:', err);
} else { } else {
console.log(`✅ Subscribed to ${deviceTopic}`); console.log('📡 Subscribed to water/iot-data/announce');
logActiveClients(); // Log clients after each new device connects
} }
}); });
}
}); });
newClient.on('message', async (topic, message) => { client.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());
if (topic === 'water/iot-data/announce' && isTemp) { // **Handle device announcements**
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;
console.log(`🔄 New Device Found! hw_Id: ${hw_Id}`); const deviceTopic = `water/iot-data/${hw_Id}`;
// If this device hasn't been connected yet, create a client for it if (!subscribedTopics.has(deviceTopic)) {
if (!activeClients.has(hw_Id)) { client.subscribe(deviceTopic, { qos: 1 }, (err) => {
console.log(`🔄 Creating new MQTT client for hw_Id: ${hw_Id}`); if (err) {
activeClients.set(hw_Id, connectMQTT(`mqtt_client_${hw_Id}`, false, hw_Id)); 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);
} }
});
} else {
console.log(`🔄 Already subscribed to ${deviceTopic}, processing data.`);
processIotData(hw_Id, data);
}
return;
} }
// **Process IoT Data for device topics**
if (topic.startsWith('water/iot-data/')) { if (topic.startsWith('water/iot-data/')) {
setImmediate(() => { setImmediate(() => {
console.log(`🚀 Processing IoT Data for topic: ${topic}`); console.log(`🚀 Entering processIotData() for topic: ${topic}`);
const deviceHwId = topic.split('/')[2]; const hw_Id = topic.split('/')[2];
processIotData(deviceHwId, data); processIotData(hw_Id, data);
}); });
} }
} catch (err) { } catch (err) {
@ -5973,21 +5982,9 @@ function connectMQTT(clientId, isTemp = false, hw_Id = null) {
} }
}); });
newClient.on('error', (err) => console.error('❌ MQTT Error:', err)); client.on('error', (err) => console.error('❌ MQTT Error:', err));
newClient.on('close', () => console.log(`⚠️ MQTT Connection Closed for ${clientId}`)); client.on('close', () => console.log('⚠️ MQTT Connection Closed.'));
newClient.on('offline', () => console.log(`⚠️ MQTT Broker Offline for ${clientId}`)); client.on('offline', () => console.log('⚠️ MQTT Broker Offline.'));
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}`);
});
}
async function processIotData(hw_Id, data) { async function processIotData(hw_Id, data) {
try { try {
@ -6103,6 +6100,9 @@ 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));

Loading…
Cancel
Save