diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 2daefeea..0e6fe57d 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -5896,7 +5896,6 @@ exports.getBlockData = async (req, reply) => { const mqtt = require('mqtt'); - require('dotenv').config(); // **Persistent MQTT Connection** @@ -5909,8 +5908,6 @@ const client = mqtt.connect('mqtt://35.207.198.4:1883', { const subscribedTopics = new Set(); const activeDevices = new Set(); // Keep track of active devices - - client.on('connect', () => { console.log('✅ Connected to MQTT broker'); @@ -5936,7 +5933,7 @@ client.on('connect', () => { }); 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 { const data = JSON.parse(message.toString()); @@ -5960,15 +5957,22 @@ client.on('message', async (topic, message) => { 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 data messages asynchronously to avoid blocking** + // **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); }); @@ -5984,115 +5988,113 @@ 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)); + + if (!data.objects || !data.objects.tanks) { + console.error(`❌ Missing 'tanks' in data for hw_Id: ${hw_Id}`); + return; + } + const { Motor_status, tanks } = data.objects; - console.log(`📡 Processing data for hw_Id: ${hw_Id}`); const currentDate = new Date(); - const date = currentDate.toISOString(); // ISO string for date - const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); // Time in 'HH:MM:SS' + const date = currentDate.toISOString(); // ISO string for date + const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); - // Create array of tank documents with current date and time - const tankDocuments = tanks.map(tank => ({ - tankhardwareId: tank.Id, // Updated to match the new format - tankHeight: tank.level, // Updated to match the new format - date, - time - })); + const tankDocuments = tanks.map(tank => ({ + tankhardwareId: tank.Id, + tankHeight: tank.level, + date, + time + })); - + const iotTankData = new IotData({ + hardwareId: hw_Id, + Motor_status, + tanks: tankDocuments, + date, + time + }); + await iotTankData.save(); - // Save IoT data for the received tanks - const iotTankData = new IotData({ - hardwareId: hw_Id, // Updated variable name - 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); + + for (const record of recordsToDelete) { + await record.remove(); + } - // Delete excess records (keep only the latest three records) - const recordsToKeep = 3; - const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) // Updated variable name - .sort({ date: -1, time: -1 }) - .skip(recordsToKeep); + // Process each tank + for (const tank of tanks) { + const { Id: tankhardwareId, level: tankHeight } = tank; + const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); - for (const record of recordsToDelete) { - await record.remove(); - } + if (!existingTank) continue; - // Process each tank to update water level and connections - for (const tank of tanks) { - const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format - // Find the corresponding tank in the Tank schema using hardwareId and tankhardwareId - const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); // Updated variable name - if (!existingTank) continue; - - const customerId = existingTank.customerId; - const tank_name = existingTank.tankName; - - // Calculate water level using tank height and capacity - const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; // Convert height to cm - const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); - const waterLevelHeight = tank_height - tankHeight; - const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); - - const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level - - // Update water level in the existing tank - console.log(tankHeight,"this is located in tank controllers at iot-data mqtt sub ") - if (tankHeight>0 && waterLevel >= 0) { - existingTank.waterlevel = waterLevel; - await existingTank.save(); - - // Update linked tanks (input/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; // Update water level for linked tank - await linkedTank.save(); // Save updated linked tank - } + const customerId = existingTank.customerId; + const tank_name = existingTank.tankName; + + const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; + const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); + const waterLevelHeight = tank_height - tankHeight; + 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(); } } } } } + } - // Update motor status - const status = Motor_status; - const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); // Updated variable name + // Update motor status + const status = Motor_status; + const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); - if (!motorTank) { - console.log('Motor not found for the specified motor_id'); - return; + if (!motorTank) { + console.log('⚠️ Motor not found for specified motor_id'); + return; + } + + 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'); + inputConnection.motor_stop_status = "2"; + inputConnection.motor_on_type = "forced_manual"; + inputConnection.startTime = currentTime; } - // Find the inputConnection for the motor and update motor status - const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name - if (inputConnection) { - inputConnection.motor_status = status; // Update motor 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'); - inputConnection.motor_stop_status = "2"; - inputConnection.motor_on_type = "forced_manual"; - inputConnection.startTime = currentTime; - } - - 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; - } - - await motorTank.save(); // Save the updated tank + 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; } - console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name + await motorTank.save(); + } + console.log(`✅ Data processed successfully for hw_Id: ${hw_Id}`); - } catch (err) { + } catch (err) { console.error('❌ Error processing IoT data:', err.message); } }