ashok 9 months ago
commit 9b7e478ddd

@ -5896,113 +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,
reconnectPeriod: 2000,
});
const subscribedTopics = new Set(); // Start a persistent temp client to listen for multiple devices
const activeDevices = new Set(); const tempClientId = `mqtt_temp_${Math.random().toString(16).substr(2, 8)}`;
const DEVICE_TIMEOUT = 10 * 60 * 1000; // 10 minutes 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}`);
subscribedTopics.forEach(topic => { const newClient = mqtt.connect('mqtt://35.207.198.4:1883', {
client.subscribe(topic, { qos: 1 }, (err) => { clientId,
if (err) console.error(`❌ Error resubscribing to ${topic}:`, err); clean: false, // Ensures session persistence
else console.log(`🔄 Resubscribed to ${topic}`); reconnectPeriod: 2000, // Reconnect every 2 seconds
}); keepalive: 60, // Maintain connection
}); });
client.subscribe('water/iot-data/announce', { qos: 1 }, (err) => { newClient.on('connect', () => {
if (err) console.error('❌ Error subscribing to announcement topic:', err); console.log(`✅ Connected to MQTT broker as ${clientId}`);
else console.log('📡 Subscribed to water/iot-data/announce');
});
});
client.on('offline', () => { if (isTemp) {
console.log('⚠️ MQTT Broker Offline. Attempting to reconnect...'); // Temporary client listens for multiple device announcements
if (!client.connected) client.reconnect(); 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('close', () => { newClient.on('message', async (topic, message) => {
console.log('⚠️ MQTT Connection Closed. Attempting to reconnect...'); console.log(`📩 Message received on topic ${topic}: ${message.toString()}`);
if (!client.connected) client.reconnect();
});
client.on('error', (err) => console.error('❌ MQTT Error:', err)); try {
const data = JSON.parse(message.toString());
client.on('message', async (topic, message) => { if (topic === 'water/iot-data/announce' && isTemp) {
console.log(`📩 Message received on topic ${topic}: ${message.toString()}`); if (!data.objects || !data.objects.hw_Id) {
console.error("❌ Invalid announcement format. Missing hw_Id.");
return;
}
try { const hw_Id = data.objects.hw_Id;
const data = JSON.parse(message.toString()); console.log(`🔄 New Device Found! hw_Id: ${hw_Id}`);
if (topic === 'water/iot-data/announce') { // If this device hasn't been connected yet, create a client for it
if (!data.objects || !data.objects.hw_Id) { if (!activeClients.has(hw_Id)) {
console.error("❌ Invalid announcement format. Missing hw_Id."); console.log(`🔄 Creating new MQTT client for hw_Id: ${hw_Id}`);
return; activeClients.set(hw_Id, connectMQTT(`mqtt_client_${hw_Id}`, false, hw_Id));
}
} }
const hw_Id = data.objects.hw_Id; if (topic.startsWith('water/iot-data/')) {
const deviceTopic = `water/iot-data/${hw_Id}`; setImmediate(() => {
console.log(`🚀 Processing IoT Data for topic: ${topic}`);
if (!subscribedTopics.has(deviceTopic)) { const deviceHwId = topic.split('/')[2];
client.subscribe(deviceTopic, { qos: 1 }, (err) => { processIotData(deviceHwId, data);
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));
setTimeout(() => {
if (subscribedTopics.has(deviceTopic) && activeDevices.has(hw_Id)) { // Check if still active
console.log(`🔄 Unsubscribing from inactive device: ${deviceTopic}`);
client.unsubscribe(deviceTopic);
subscribedTopics.delete(deviceTopic);
activeDevices.delete(hw_Id);
}
}, DEVICE_TIMEOUT);
}
}); });
} }
return; } catch (err) {
console.error('❌ Error processing message:', err.message);
} }
});
if (topic.startsWith('water/iot-data/')) { newClient.on('error', (err) => console.error('❌ MQTT Error:', err));
setImmediate(() => { newClient.on('close', () => console.log(`⚠️ MQTT Connection Closed for ${clientId}`));
console.log(`🚀 Processing IoT Data for topic: ${topic}`); newClient.on('offline', () => console.log(`⚠️ MQTT Broker Offline for ${clientId}`));
// Extract hw_Id from received data first, fallback to topic split
const hw_Id = data.objects?.hw_Id || topic.split('/')[2];
if (!hw_Id) {
console.error("❌ hw_Id missing in received data:", JSON.stringify(data, null, 2));
return;
}
console.log("Extracted hw_Id:", hw_Id); return newClient;
}
// Ensure data is valid before processing // Function to log active MQTT clients
if (!data || !data.objects) { function logActiveClients() {
console.error("❌ Invalid data received:", JSON.stringify(data, null, 2)); console.log(`\n📡 Active MQTT Clients:`);
return; activeClients.forEach((client, hw_Id) => {
} console.log(` 🔹 Client ID: mqtt_client_${hw_Id}`);
});
}
// Process IoT data asynchronously
setImmediate(() => processIotData(hw_Id, data));
});
}
} catch (err) {
console.error('❌ Error processing message:', err.message);
}
});
async function processIotData(hw_Id, data) { async function processIotData(hw_Id, data) {
try { try {
@ -6015,7 +6000,7 @@ async function processIotData(hw_Id, data) {
const { Motor_status, tanks } = data.objects; const { Motor_status, tanks } = data.objects;
const currentDate = new Date(); const currentDate = new Date();
const date = currentDate.toISOString(); const date = currentDate.toISOString(); // ISO string for date
const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' });
const tankDocuments = tanks.map(tank => ({ const tankDocuments = tanks.map(tank => ({
@ -6025,19 +6010,31 @@ async function processIotData(hw_Id, data) {
time time
})); }));
const iotTankData = new IotData({ hardwareId: hw_Id, Motor_status, tanks: tankDocuments, date, time }); const iotTankData = new IotData({
hardwareId: hw_Id,
Motor_status,
tanks: tankDocuments,
date,
time
});
await iotTankData.save();
// **Save IoT Data & Clean Up Old Records in Parallel** // Delete excess records (keep only the latest three records)
await Promise.all([ const recordsToKeep = 3;
iotTankData.save(), const recordsToDelete = await IotData.find({ hardwareId: hw_Id })
IotData.deleteMany({ hardwareId: hw_Id }).sort({ date: -1, time: -1 }).skip(3) .sort({ date: -1, time: -1 })
]); .skip(recordsToKeep);
const tankOperations = tanks.map(async (tank) => { for (const record of recordsToDelete) {
await record.remove();
}
// Process each tank
for (const tank of tanks) {
const { Id: tankhardwareId, level: tankHeight } = tank; const { Id: tankhardwareId, level: tankHeight } = tank;
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
if (!existingTank) return; if (!existingTank) continue;
const customerId = existingTank.customerId; const customerId = existingTank.customerId;
const tank_name = existingTank.tankName; const tank_name = existingTank.tankName;
@ -6048,70 +6045,72 @@ async function processIotData(hw_Id, data) {
const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10);
existingTank.waterlevel = waterLevel; console.log(`🚰 Tank [${tankhardwareId}] - Level: ${tankHeight}, Calculated Water Level: ${waterLevel}`);
await existingTank.save();
if (tankHeight > 0 && waterLevel >= 0) {
// **Process Output Connections** existingTank.waterlevel = waterLevel;
for (const outputConnection of existingTank.connections.outputConnections) { await existingTank.save();
const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type });
if (linkedTank) { for (const outputConnection of existingTank.connections.outputConnections) {
for (const inputConnection of linkedTank.connections.inputConnections) { const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type });
if (inputConnection.inputConnections === tank_name) { if (linkedTank) {
inputConnection.water_level = waterLevel; for (const inputConnection of linkedTank.connections.inputConnections) {
await linkedTank.save(); if (inputConnection.inputConnections === tank_name) {
inputConnection.water_level = waterLevel;
await linkedTank.save();
}
} }
} }
} }
} }
}); }
await Promise.all(tankOperations);
// **Update Motor Status** // Update motor status
const status = Motor_status;
const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id });
console.log(motorTank,"motortank")
if (motorTank) {
const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
if (inputConnection) { if (!motorTank) {
console.log("it entered inputconnection",Motor_status,inputConnection.motor_status ) console.log('⚠️ Motor not found for specified motor_id');
inputConnection.motor_status = Motor_status; return;
}
if (inputConnection.motor_stop_status === "1" && Motor_status === 2 && inputConnection.motor_on_type !== "forced_manual") { const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); if (inputConnection) {
inputConnection.motor_stop_status = "2"; inputConnection.motor_status = status;
inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = currentTime;
inputConnection.start_instance_id = `${hw_Id}${currentTime}`;
}
if (inputConnection.motor_stop_status === "2" && Motor_status === 1) { if (inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") {
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
inputConnection.motor_stop_status = "1"; inputConnection.motor_stop_status = "2";
inputConnection.motor_on_type = "manual"; inputConnection.motor_on_type = "forced_manual";
inputConnection.stopTime = currentTime; inputConnection.startTime = currentTime;
} }
await motorTank.save(); if (inputConnection.motor_stop_status === "2" && status === 1) {
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
inputConnection.motor_stop_status = "1";
inputConnection.motor_on_type = "manual";
inputConnection.stopTime = currentTime;
} }
} else {
console.log('⚠️ Motor not found for specified motor_id'); await motorTank.save();
} }
console.log(`✅ Data processed successfully for hw_Id: ${hw_Id}`); console.log(`✅ Data processed successfully for hw_Id: ${hw_Id}`);
} catch (err) { } catch (err) {
console.error('❌ Error processing IoT data:', err.message); console.error('❌ Error processing IoT data:', err.message);
} }
} }
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 // function logSets() {
setInterval(logSets, 30000); // 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);

Loading…
Cancel
Save