From ff24a2157fe71e8968b17397c0fe709076b89650 Mon Sep 17 00:00:00 2001 From: Varun Date: Mon, 10 Mar 2025 14:56:41 +0530 Subject: [PATCH] changes --- src/controllers/tanksController.js | 82 +++++++++++++++--------------- 1 file changed, 42 insertions(+), 40 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 6c79b761..6fd92d5c 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -5881,9 +5881,12 @@ exports.getBlockData = async (req, reply) => { // } // } // }); - const mqtt = require('mqtt'); -const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker + +// Connect to MQTT broker +const client = mqtt.connect('mqtt://35.207.198.4:1883'); + + client.on('connect', () => { console.log('Connected to MQTT broker'); @@ -5900,32 +5903,30 @@ client.on('message', async (topic, message) => { console.log(`Message received on topic ${topic}:`, message.toString()); try { - const data = JSON.parse(message.toString()); - const { hw_Id, Motor_status, tanks } = data.objects; + const topicParts = topic.split('/'); // ['water', 'iot-data', '140924'] + const hw_Id = topicParts[2]; // Extract hardwareId from topic if (!hw_Id) { - console.error('Invalid message format: Missing hw_Id'); + console.error('Invalid topic format: Missing hw_Id'); return; } - // Extract device-specific topic - const expectedTopic = `water/iot-data/${hw_Id}`; - if (topic !== expectedTopic) { - console.log(`Unexpected topic. Received: ${topic}, Expected: ${expectedTopic}`); - return; - } + const data = JSON.parse(message.toString()); + const { Motor_status, tanks } = data.objects; + + console.log(`Processing data for hardwareId: ${hw_Id}`); // Get the current date and time in the required format - 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 currentTime = moment().tz('Asia/Kolkata'); + const date = currentTime.format('YYYY-MM-DD'); // Adjust format if needed + const time = currentTime.format('HH:mm:ss'); - // Create array of tank documents with current date and time + // Create tank documents const tankDocuments = tanks.map(tank => ({ tankhardwareId: tank.Id, tankHeight: tank.level, date, - time + time, })); // Save IoT data @@ -5934,7 +5935,7 @@ client.on('message', async (topic, message) => { Motor_status, tanks: tankDocuments, date, - time + time, }); await iotTankData.save(); @@ -5944,9 +5945,7 @@ client.on('message', async (topic, message) => { .sort({ date: -1, time: -1 }) .skip(recordsToKeep); - for (const record of recordsToDelete) { - await record.remove(); - } + await Promise.all(recordsToDelete.map(record => record.remove())); // Process tanks and update water level for (const tank of tanks) { @@ -5957,21 +5956,26 @@ client.on('message', async (topic, message) => { 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; - const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); + // Convert height and calculate water level + const tankHeightInCm = parseInt(existingTank.height.replace(/,/g, ''), 10) * 30.48; + const tank_height = Math.round(tankHeightInCm); const waterLevelHeight = tank_height - tankHeight; const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); + const waterLevel = Math.max(0, waterLevelHeight * waterCapacityPerCm); - const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); + console.log(`${tankHeight} - Processed in MQTT subscriber`); - console.log(tankHeight, "this is located in tank controllers at iot-data mqtt sub"); - if (tankHeight > 0 && waterLevel >= 0) { + if (tankHeight > 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 }); + 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) { @@ -5985,34 +5989,31 @@ client.on('message', async (topic, message) => { } // 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'); + console.log(`Motor not found for motor_id: ${hw_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_status = Motor_status; + + if (inputConnection.motor_stop_status === "1" && Motor_status === 2 && inputConnection.motor_on_type !== "forced_manual") { inputConnection.motor_stop_status = "2"; inputConnection.motor_on_type = "forced_manual"; - inputConnection.startTime = currentTime; + inputConnection.startTime = currentTime.format('DD-MMM-YYYY - HH:mm'); } - - if (inputConnection.motor_stop_status === "2" && status === 1) { - const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); + + if (inputConnection.motor_stop_status === "2" && Motor_status === 1) { inputConnection.motor_stop_status = "1"; - inputConnection.stopTime = currentTime; + inputConnection.stopTime = currentTime.format('DD-MMM-YYYY - HH:mm'); } - + await motorTank.save(); } - console.log(`Data processed successfully for hardwareId: ${hw_Id}`); + console.log(`Processed successfully for hardwareId: ${hw_Id}`); } catch (err) { console.error('Error processing message:', err.message); } @@ -6021,6 +6022,7 @@ client.on('message', async (topic, message) => { + const sendMotorNotifications = async () => { // console.log("🔄 Checking for motor notifications...");