diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index a80e1ed6..f29c5c54 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2988,7 +2988,6 @@ exports.motorAction = async (req, reply) => { } ); - clearInterval(motorIntervals[motorId]); // Stop the motor if condition met delete motorIntervals[motorId]; // Remove from interval object @@ -5762,44 +5761,48 @@ 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 + clean: false, + reconnectPeriod: 2000, }); const subscribedTopics = new Set(); -const activeDevices = new Set(); // Keep track of active devices +const activeDevices = new Set(); +const DEVICE_TIMEOUT = 10 * 60 * 1000; // 10 minutes client.on('connect', () => { console.log('✅ Connected to MQTT broker'); - // **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}`); - } + if (err) console.error(`❌ Error resubscribing to ${topic}:`, err); + else console.log(`🔄 Resubscribed to ${topic}`); }); }); - // **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'); - } + if (err) console.error('❌ Error subscribing to announcement topic:', err); + else console.log('📡 Subscribed to water/iot-data/announce'); }); }); +client.on('offline', () => { + console.log('⚠️ MQTT Broker Offline. Attempting to reconnect...'); + if (!client.connected) client.reconnect(); +}); + +client.on('close', () => { + console.log('⚠️ MQTT Connection Closed. Attempting to reconnect...'); + if (!client.connected) client.reconnect(); +}); + +client.on('error', (err) => console.error('❌ MQTT Error:', err)); + client.on('message', async (topic, message) => { console.log(`📩 Message received on topic ${topic}: ${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."); @@ -5811,31 +5814,32 @@ client.on('message', async (topic, message) => { if (!subscribedTopics.has(deviceTopic)) { client.subscribe(deviceTopic, { qos: 1 }, (err) => { - if (err) { - console.error(`❌ Error subscribing to ${deviceTopic}:`, err); - } else { + 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); + setTimeout(() => { + if (subscribedTopics.has(deviceTopic)) { + console.log(`🔄 Unsubscribing from inactive device: ${deviceTopic}`); + client.unsubscribe(deviceTopic); + subscribedTopics.delete(deviceTopic); + activeDevices.delete(hw_Id); + } + }, DEVICE_TIMEOUT); } }); - } 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/')) { setImmediate(() => { - console.log(`🚀 Entering processIotData() for topic: ${topic}`); + console.log(`🚀 Processing IoT Data for topic: ${topic}`); const hw_Id = topic.split('/')[2]; - processIotData(hw_Id, data); + setImmediate(() => processIotData(hw_Id, data)); }); } } catch (err) { @@ -5843,10 +5847,6 @@ client.on('message', async (topic, message) => { } }); -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 { console.log(`📡 Processing IoT Data for hw_Id: ${hw_Id}`, JSON.stringify(data, null, 2)); @@ -5858,7 +5858,7 @@ async function processIotData(hw_Id, data) { const { Motor_status, tanks } = data.objects; const currentDate = new Date(); - const date = currentDate.toISOString(); // ISO string for date + const date = currentDate.toISOString(); const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); const tankDocuments = tanks.map(tank => ({ @@ -5868,31 +5868,19 @@ async function processIotData(hw_Id, data) { time })); - const iotTankData = new IotData({ - hardwareId: hw_Id, - Motor_status, - tanks: tankDocuments, - date, - time - }); - await iotTankData.save(); - - // Delete excess records (keep only the latest three records) - const recordsToKeep = 3; - const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) - .sort({ date: -1, time: -1 }) - .skip(recordsToKeep); + const iotTankData = new IotData({ hardwareId: hw_Id, Motor_status, tanks: tankDocuments, date, time }); - for (const record of recordsToDelete) { - await record.remove(); - } + // **Save IoT Data & Clean Up Old Records in Parallel** + await Promise.all([ + iotTankData.save(), + IotData.deleteMany({ hardwareId: hw_Id }).sort({ date: -1, time: -1 }).skip(3) + ]); - // Process each tank - for (const tank of tanks) { + const tankOperations = tanks.map(async (tank) => { const { Id: tankhardwareId, level: tankHeight } = tank; const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); - if (!existingTank) continue; + if (!existingTank) return; const customerId = existingTank.customerId; const tank_name = existingTank.tankName; @@ -5903,61 +5891,56 @@ async function processIotData(hw_Id, data) { const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); - console.log(`🚰 Tank [${tankhardwareId}] - Level: ${tankHeight}, Calculated Water Level: ${waterLevel}`); - - if (tankHeight > 0 && waterLevel >= 0) { - existingTank.waterlevel = waterLevel; - await existingTank.save(); - - for (const outputConnection of existingTank.connections.outputConnections) { - const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type }); - if (linkedTank) { - for (const inputConnection of linkedTank.connections.inputConnections) { - if (inputConnection.inputConnections === tank_name) { - inputConnection.water_level = waterLevel; - await linkedTank.save(); - } + existingTank.waterlevel = waterLevel; + await existingTank.save(); + + // **Process Output Connections** + for (const outputConnection of existingTank.connections.outputConnections) { + const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type }); + if (linkedTank) { + for (const inputConnection of linkedTank.connections.inputConnections) { + if (inputConnection.inputConnections === tank_name) { + inputConnection.water_level = waterLevel; + await linkedTank.save(); } } } } - } + }); - // Update motor status - const status = Motor_status; + await Promise.all(tankOperations); + + // **Update Motor Status** const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); - if (!motorTank) { - console.log('⚠️ Motor not found for specified motor_id'); - return; - } + if (motorTank) { + const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); - const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); - if (inputConnection) { - inputConnection.motor_status = status; - - 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 startInstanceId = `${hw_Id}${currentTime}`; - inputConnection.motor_stop_status = "2"; - inputConnection.motor_on_type = "forced_manual"; - inputConnection.startTime = currentTime; - inputConnection.start_instance_id = startInstanceId; - } + if (inputConnection) { + inputConnection.motor_status = Motor_status; - 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; - } + if (inputConnection.motor_stop_status === "1" && Motor_status === 2 && inputConnection.motor_on_type !== "forced_manual") { + const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); + inputConnection.motor_stop_status = "2"; + 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) { + 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; + } - await motorTank.save(); + await motorTank.save(); + } + } else { + console.log('⚠️ Motor not found for specified motor_id'); } console.log(`✅ Data processed successfully for hw_Id: ${hw_Id}`); - } catch (err) { console.error('❌ Error processing IoT data:', err.message); }