From ab8b71fa0bfe8f5e63c5a598e203e004df8be6a4 Mon Sep 17 00:00:00 2001 From: Varun Date: Mon, 17 Mar 2025 11:52:08 +0530 Subject: [PATCH 1/7] changes in motoraction --- src/controllers/tanksController.js | 312 +++++++++-------------------- 1 file changed, 91 insertions(+), 221 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 0e3f9f9a..1c5e6b2a 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2838,215 +2838,66 @@ async function calculateTotalPumpedWater(customerId, motorId, start_instance_id) exports.motorAction = async (req, reply) => { try { - const customerId = req.params.customerId; - const action = req.body.action; - const motorId = req.body.motor_id; - const start_instance_id = req.body.start_instance_id; - - // Define thresholds for water levels - const lowWaterThreshold = 5; // Low water level percentage threshold - //const highWaterThreshold = 90; // High water level percentage threshold - const highWaterThreshold = 70; // High water level percentage threshold - const veryHighWaterThreshold = 80; // Very High water level percentage threshold - const criticalHighWaterThreshold = 85; - // Ensure motor_id is provided - if (!motorId) { - throw new Error("Motor ID is required."); - } + const { customerId } = req.params; + const { action, motor_id: motorId, start_instance_id, phone, threshold_type, manual_threshold_time, manual_threshold_litres } = req.body; + + if (!motorId) throw new Error("Motor ID is required."); - // Get user FCM tokens const users = await User.findOne({ customerId }); - console.log("users",users) - - let loggedInUser = null; + if (!users) return reply.status(404).send({ error: "User not found" }); - if (users) { - if (users.phone === req.body.phone) { - loggedInUser = { role: "Customer", name: users.username, phone: users.phone }; - } else if (users.staff && users.staff.staff) { - const staffMember = users.staff.staff.find(staff => staff.phone === req.body.phone); - if (staffMember) { - loggedInUser = { role: "Staff", name: staffMember.name, phone: staffMember.phone }; - } - } - } + let loggedInUser = users.phone === phone ? + { role: "Customer", name: users.username, phone: users.phone } : + users.staff?.staff?.find(staff => staff.phone === phone) ? + { role: "Staff", name: users.staff.staff.find(staff => staff.phone === phone).name, phone } : null; - if (!loggedInUser) { - console.log("User not found. Cannot proceed with motorStart event."); - return reply.status(404).send({ error: "User not found" }); // ✅ FIX: Ensure a response is returned - } + if (!loggedInUser) return reply.status(404).send({ error: "User not found" }); - const fcmToken = users.fcmIds ? users.fcmIds.filter(fcmIds => fcmIds) : []; - - // const fcmToken = users.map(user => user.fcmIds).filter(fcmIds => fcmIds); - console.log(fcmToken) + const fcmToken = users.fcmIds ? users.fcmIds.filter(id => id) : []; const receiverTank = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() }); - console.log(receiverTank) - const currentWaterLevel = parseInt(receiverTank.waterlevel, 10); - const waterLevelThresholds = { low: 30, veryLow: 20, criticallyLow: 10 }; - const typeOfWater = receiverTank.typeOfWater; - console.log(typeOfWater,"typeOfWater") - - // Determine the motor stop status based on the action - let motorStopStatus; - const blockName = req.body.from || "Unknown Block"; // Provide a fallback if `from` is missing - const tankName = req.body.to || "Unknown Tank"; // Provide a fallback if `to` is missing - const stopTime = req.body.stopTime - const motorOnType = "manual"; - const manual_threshold_time = req.body.manual_threshold_time; - let hasNotifiedStart = false; - let hasNotifiedStop = false; - if (action === "start") { - motorStopStatus = "2"; - const startTime = req.body.startTime; - await Tank.updateOne( - { customerId, "connections.inputConnections.motor_id": motorId }, - { $set: { "connections.inputConnections.$.motor_stop_status": motorStopStatus } } - ); - const thresholdTimeMs = req.body.manual_threshold_time * 60 * 1000; // Convert minutes to milliseconds - const stopCriteria = - motorOnType === "time" - ? `${req.body.manual_threshold_time} minutes` - : `${req.body.manual_threshold_litres} litres`; - try { - eventEmitter.emit( - "motorStart", - customerId, - fcmToken, - tankName, - blockName, - startTime, - "Mobile APP", - manual_threshold_time, - typeOfWater, - motorId, - loggedInUser.phone, - ); - - reply.code(200).send({ message: "Motor started successfully." }); - } catch (error) { - console.error("Error in handleMotorStart:", error); - reply.code(500).send({ error: "Internal Server Error" }); - } - - // Start checking water level every 30 minutes - if (!waterLevelCheckInterval) { - waterLevelCheckInterval = setInterval(async () => { - await checkWaterLevel(customerId, motorId, fcmToken, receiverTank); - }, 30 * 60 * 1000); // 30 minutes - } - await Tank.updateOne( - { customerId, "connections.inputConnections.motor_id": motorId }, - { $set: { "connections.inputConnections.$.motor_stop_status": "2", - "connections.inputConnections.$.manual_threshold_time": manual_threshold_time, - "connections.inputConnections.$.threshold_type": "time", - "connections.inputConnections.$.motor_on_type": "manual" } } - ); - - reply.code(200).send({ message: "Motor started successfully." }); - - } else if (action === "stop") { - motorStopStatus = "1"; // If action is stop, set stop status to "1" - - try { - + if (!receiverTank) throw new Error("Receiver tank not found."); - const totalWaterPumped = await calculateTotalPumpedWater(customerId, motorId, start_instance_id); - - eventEmitter.emit("motorStop", customerId, fcmToken, tankName, blockName, stopTime, "Mobile APP", totalWaterPumped, typeOfWater, motorId, - loggedInUser.phone,); - - reply.code(200).send({ message: "Motor stopped successfully." }); - } catch (error) { - console.error("Error in handleMotorStop:", error); - reply.code(500).send({ error: "Internal Server Error" }); - } + const typeOfWater = receiverTank.typeOfWater; + let motorStopStatus = action === "start" ? "2" : "1"; + const blockName = req.body.from || "Unknown Block"; + const tankName = req.body.to || "Unknown Tank"; - - await Tank.updateOne( - { customerId, "connections.inputConnections.motor_id": motorId }, - { - $set: { - "connections.inputConnections.$.motor_stop_status": "1", - "connections.inputConnections.$.motor_on_type": motorOnType } - } - ); - // Clear the interval when the motor is stopped - if (waterLevelCheckInterval) { - clearInterval(waterLevelCheckInterval); - waterLevelCheckInterval = null; // Reset the interval ID - } - } else { - throw new Error("Invalid action provided."); + if (action === "start") { + + if (motorIntervals[motorId]) { + clearInterval(motorIntervals[motorId]); + delete motorIntervals[motorId]; } - - // If action is stop, immediately update motor status and perform stop operations - if (action === "stop") { - console.log("enterted stop") + + const startTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); + + const newMotorData = new MotorData({ + customerId, + motor_id: motorId, + start_instance_id, + supplierTank: req.body.from, + receiverTank: req.body.to, + supplier_type: req.body.from_type, + receiver_type: req.body.to_type, + startTime, + receiverInitialwaterlevel: parseInt(receiverTank.waterlevel.replace(/,/g, ''), 10) + }); + await newMotorData.save(); + await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, - { - $set: { - "connections.inputConnections.$.motor_stop_status": "1", - "connections.inputConnections.$.motor_on_type": "manual", - "connections.inputConnections.$.stopTime": req.body.stopTime, - "connections.inputConnections.$.threshold_type": null, - "connections.inputConnections.$.manual_threshold_time": null, - "connections.inputConnections.$.manual_threshold_percentage": null - } - } + { $set: { + "connections.inputConnections.$.motor_stop_status": "2", + "connections.inputConnections.$.manual_threshold_time": manual_threshold_time, + "connections.inputConnections.$.threshold_type": threshold_type, + "connections.inputConnections.$.motor_on_type": "manual" + }} ); - if (motorIntervals[motorId]) { - console.log(motorIntervals[motorId],"deleted") - clearInterval(motorIntervals[motorId]); // Clear the interval - delete motorIntervals[motorId]; // Remove the interval from the object - } + + eventEmitter.emit("motorStart", customerId, fcmToken, tankName, blockName, startTime, "Mobile APP", manual_threshold_time, typeOfWater, motorId, loggedInUser.phone); this.publishMotorStopStatus(motorId, motorStopStatus); - - // Send immediate response to the client - reply.code(200).send({ message: "Motor stopped successfully." }); - - // Perform stop operations in the background - (async () => { - - console.log(start_instance_id,"start_instance_id",customerId,"customerId",motorId,"motorId") - const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id }); - if (motorData) { - console.log("entered if in stop") - const receiverTank = await Tank.findOne({ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() }); - const receiverFinalWaterLevel = parseInt(receiverTank.waterlevel, 10); - const quantityDelivered = receiverFinalWaterLevel - parseInt(motorData.receiverInitialwaterlevel, 10); - const water_pumped_till_now = parseInt(receiverTank.total_water_added_from_midnight, 10); - const totalwaterpumped = quantityDelivered + water_pumped_till_now; - - await Tank.findOneAndUpdate( - { customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() }, - { $set: { total_water_added_from_midnight: totalwaterpumped } } - ); - - await MotorData.updateOne( - { customerId, motor_id: motorId, start_instance_id: start_instance_id }, - { - $set: { - stopTime: req.body.stopTime, - receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), - quantity_delivered: quantityDelivered.toString() - } - } - ); - } - })(); - - return; // Return early to avoid executing the start logic - } else { - await Tank.updateOne( - { customerId, "connections.inputConnections.motor_id": motorId }, - { $set: { "connections.inputConnections.$.motor_stop_status": "2" } } - ); - } - - // Check threshold settings if action is start - if (action === "start") { + reply.code(200).send({ message: "Motor started successfully." }); + if (req.body.threshold_type === "time") { // Create a new MotorData entry const receiverTank = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() }); @@ -3147,26 +2998,7 @@ exports.motorAction = async (req, reply) => { } } ); - // eventEmitter.emit('sendLowWaterNotification', fcmToken, receiverTank); - // console.log(motorIntervals[motorId],"deleted automatically") // Emit low water level notification - // clearInterval(motorIntervals[motorId]); // Clear interval - // delete motorIntervals[motorId]; - - // await checkWaterLevelsAndNotify(customerId, tankName, supplierTank.tankLocation, fcmToken); - // if (currentWaterPercentage >= highWaterThreshold && !notificationSentStatus.highWater) { - // eventEmitter.emit('sendHighWaterNotification', fcmToken, `Water level has reached high levels.`); - // notificationSentStatus.highWater = true; // Set flag to true to prevent duplicate notifications - // } - - // if (currentWaterPercentage >= veryHighWaterThreshold && !notificationSentStatus.veryHighWater) { - // eventEmitter.emit('sendVeryHighWaterNotification', fcmToken, `Water level has reached very high levels.`); - // notificationSentStatus.veryHighWater = true; // Set flag to true to prevent duplicate notifications - // } - // if (currentWaterPercentage >= criticalHighWaterThreshold && !notificationSentStatus.criticallyHighWater) { - // eventEmitter.emit('sendCriticalHighWaterNotification', fcmToken, `Water level has reached critically high levels.`); - // notificationSentStatus.criticallyHighWater = true; // Set flag to true to prevent duplicate notifications - // } clearInterval(motorIntervals[motorId]); // Stop the motor if condition met delete motorIntervals[motorId]; // Remove from interval object @@ -3210,7 +3042,8 @@ exports.motorAction = async (req, reply) => { }, 30000); // Check every minute } - }else if (req.body.threshold_type === "litres") { + } + else if (req.body.threshold_type === "litres") { console.log("entered litres") const receiver_tank_info7 = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() }); const supplier_tank_info7 = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() }); @@ -3316,17 +3149,54 @@ exports.motorAction = async (req, reply) => { } } - - + + } else if (action === "stop") { + await stopMotor(motorId, customerId, start_instance_id); + this.publishMotorStopStatus(motorId, motorStopStatus); + reply.code(200).send({ message: "Motor stopped successfully." }); } - // Respond with success message - reply.code(200).send({ message: `Motor ${action === "start" ? "started" : "stopped"} successfully.` }); - } catch (err) { throw boom.boomify(err); } }; +async function stopMotor(motorId, customerId, start_instance_id) { + const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); + await Tank.updateOne( + { customerId, "connections.inputConnections.motor_id": motorId }, + { $set: { + "connections.inputConnections.$.motor_stop_status": "1", + "connections.inputConnections.$.stopTime": currentTime, + "connections.inputConnections.$.threshold_type": null, + "connections.inputConnections.$.manual_threshold_time": null, + "connections.inputConnections.$.manual_threshold_percentage": null + }} + ); + + if (motorIntervals[motorId]) { + clearInterval(motorIntervals[motorId]); + delete motorIntervals[motorId]; + } + + eventEmitter.emit("motorStop", customerId, [], "", "", currentTime, "Mobile APP", 0, "", motorId, ""); + + const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id }); + if (motorData) { + const startTime = moment(motorData.startTime, 'DD-MMM-YYYY - HH:mm'); + const runtime = moment.duration(moment(currentTime, 'DD-MMM-YYYY - HH:mm').diff(startTime)).asSeconds(); + + const receiverTank = await Tank.findOne({ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() }); + const receiverFinalWaterLevel = parseInt(receiverTank.waterlevel.replace(/,/g, ''), 10); + const quantityDelivered = receiverFinalWaterLevel - parseInt(motorData.receiverInitialwaterlevel.replace(/,/g, ''), 10); + + await MotorData.updateOne( + { customerId, motor_id: motorId, start_instance_id }, + { $set: { stopTime: currentTime, receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), quantity_delivered: quantityDelivered.toString(), runtime: runtime } } + ); + } +} + + // exports.motorAction = async (req, reply) => { From b6225d24fb484abbf4e9abf3a55942521a6171b1 Mon Sep 17 00:00:00 2001 From: Varun Date: Mon, 17 Mar 2025 12:15:14 +0530 Subject: [PATCH 2/7] changes --- src/controllers/tanksController.js | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 1c5e6b2a..f1baa6f3 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2871,18 +2871,7 @@ exports.motorAction = async (req, reply) => { const startTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); - const newMotorData = new MotorData({ - customerId, - motor_id: motorId, - start_instance_id, - supplierTank: req.body.from, - receiverTank: req.body.to, - supplier_type: req.body.from_type, - receiver_type: req.body.to_type, - startTime, - receiverInitialwaterlevel: parseInt(receiverTank.waterlevel.replace(/,/g, ''), 10) - }); - await newMotorData.save(); + await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, From 168814079474e368759e3a63d4cb7d6ff86b6d2a Mon Sep 17 00:00:00 2001 From: Varun Date: Mon, 17 Mar 2025 13:27:11 +0530 Subject: [PATCH 3/7] changes --- src/controllers/tanksController.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index f1baa6f3..a80e1ed6 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2988,6 +2988,8 @@ exports.motorAction = async (req, reply) => { } ); + + clearInterval(motorIntervals[motorId]); // Stop the motor if condition met delete motorIntervals[motorId]; // Remove from interval object @@ -5933,12 +5935,15 @@ async function processIotData(hw_Id, data) { 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.motor_stop_status === "2" && status === 1) { From 0b107a6785d5b14aff70e9d19113a569b6961ea5 Mon Sep 17 00:00:00 2001 From: Varun Date: Mon, 17 Mar 2025 20:16:13 +0530 Subject: [PATCH 4/7] changes in water/iot-data/announce --- src/controllers/tanksController.js | 173 +++++++++++++---------------- 1 file changed, 78 insertions(+), 95 deletions(-) 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); } From 40ea912908be5f29c935764b719cc0f0f1d6d5b8 Mon Sep 17 00:00:00 2001 From: Varun Date: Tue, 18 Mar 2025 12:58:46 +0530 Subject: [PATCH 5/7] changes --- src/controllers/tanksController.js | 64 ++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index f29c5c54..94d80d0d 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2864,10 +2864,19 @@ exports.motorAction = async (req, reply) => { if (action === "start") { - if (motorIntervals[motorId]) { - clearInterval(motorIntervals[motorId]); - delete motorIntervals[motorId]; - } + if (motorIntervals[motorId]) { + console.log(`🔄 Clearing all existing intervals for motorId: ${motorId}`); + + // Clear and delete all intervals for the motorId + Object.keys(motorIntervals).forEach(key => { + if (key.startsWith(motorId)) { + clearInterval(motorIntervals[key]); + delete motorIntervals[key]; + } + }); + + console.log(`✅ All intervals cleared for motorId: ${motorId}`); + } const startTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); @@ -5822,13 +5831,14 @@ client.on('message', async (topic, message) => { console.log('📡 Active Devices:', Array.from(activeDevices)); setTimeout(() => { - if (subscribedTopics.has(deviceTopic)) { - console.log(`🔄 Unsubscribing from inactive device: ${deviceTopic}`); - client.unsubscribe(deviceTopic); - subscribedTopics.delete(deviceTopic); - activeDevices.delete(hw_Id); + 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); + }, DEVICE_TIMEOUT); + } }); } @@ -5838,10 +5848,28 @@ client.on('message', async (topic, message) => { if (topic.startsWith('water/iot-data/')) { setImmediate(() => { console.log(`🚀 Processing IoT Data for topic: ${topic}`); - const hw_Id = topic.split('/')[2]; + + // 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); + + // Ensure data is valid before processing + if (!data || !data.objects) { + console.error("❌ Invalid data received:", JSON.stringify(data, null, 2)); + return; + } + + // Process IoT data asynchronously setImmediate(() => processIotData(hw_Id, data)); }); } + } catch (err) { console.error('❌ Error processing message:', err.message); } @@ -5912,11 +5940,12 @@ async function processIotData(hw_Id, data) { // **Update Motor Status** 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) { + console.log("it entered inputconnection",Motor_status,inputConnection.motor_status ) inputConnection.motor_status = Motor_status; if (inputConnection.motor_stop_status === "1" && Motor_status === 2 && inputConnection.motor_on_type !== "forced_manual") { @@ -5946,6 +5975,17 @@ async function processIotData(hw_Id, data) { } } +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 +setInterval(logSets, 30000); + + + From 0ba2d740f5166b7c4f4d7218189b36b75b21fce9 Mon Sep 17 00:00:00 2001 From: Varun Date: Tue, 18 Mar 2025 13:13:53 +0530 Subject: [PATCH 6/7] changes --- src/controllers/tanksController.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 94d80d0d..ae584678 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2998,6 +2998,7 @@ exports.motorAction = async (req, reply) => { ); + clearInterval(motorIntervals[motorId]); // Stop the motor if condition met delete motorIntervals[motorId]; // Remove from interval object From ca6799566d60f44607068375deaef240123189f9 Mon Sep 17 00:00:00 2001 From: Varun Date: Tue, 18 Mar 2025 13:16:47 +0530 Subject: [PATCH 7/7] changes --- src/controllers/tanksController.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index ae584678..49151590 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2999,6 +2999,7 @@ exports.motorAction = async (req, reply) => { + clearInterval(motorIntervals[motorId]); // Stop the motor if condition met delete motorIntervals[motorId]; // Remove from interval object