From 126075f5aaa63c1e017960cbde105cc596345f83 Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Thu, 20 Mar 2025 14:02:50 +0530 Subject: [PATCH] low and critical alert notifications --- src/controllers/tanksController.js | 170 +++++++++++++++++++++++------ 1 file changed, 139 insertions(+), 31 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index da99af8d..d8985a2f 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1780,6 +1780,40 @@ eventEmitter.on("sendMotorStopNotification", async (hw_Id, customerId, fcmTokens } }); +eventEmitter.on('sendLowWaterNotification', async (customerId, fcmTokens, hw_Id, tankName, blockName, lowWaterLevel, currentWaterLevel, currentWaterPercentage) => { + try { + const message = + `⚠️ Warning: Low water level detected!\n` + + `🛢️ Tank Name: '${tankName}'\n` + + `🏢 Block Name: '${blockName}'\n` + + `📉 Low Water Threshold: '${lowWaterLevel} liters'\n` + + `📌 Current Water Level: '${currentWaterLevel} liters'\n` + + `📅 Date & Time: '${new Date().toLocaleString()}'`; + + await sendNotification(hw_Id, customerId, fcmTokens, 'Low Water Alert', message); + console.log("✅ Low water notification sent successfully."); + } catch (error) { + console.error("❌ Error sending low water notification:", error); + } +}); + +eventEmitter.on('sendCriticalLowWaterNotification', async (customerId, fcmTokens, hw_Id, tankName, blockName, criticalLowWaterLevel, currentWaterLevel, currentWaterPercentage) => { + try { + const message = + `🚨 Critical Alert: Water level is **critically low!**\n` + + `🛢️ Tank Name: '${tankName}'\n` + + `🏢 Block Name: '${blockName}'\n` + + `🔴 Critical Low Threshold: '${criticalLowWaterLevel} liters'\n` + + `📌 Current Water Level: '${currentWaterLevel} liters'\n` + + `📅 Date & Time: '${new Date().toLocaleString()}'`; + + await sendNotification(hw_Id, customerId, fcmTokens, 'Critical Water Alert', message); + console.log("✅ Critical low water notification sent successfully."); + } catch (error) { + console.error("❌ Error sending critical low water notification:", error); + } +}); + // eventEmitter.on('sendLowWaterNotification', (fcmTokens, message) => { @@ -2138,7 +2172,10 @@ const sendNotification = async (hw_Id, customerId, fcmIds, title, body) => { const response = await admin.messaging().send({ token, notification: { title, body }, - data: { hw_Id, target: "/tank_levels" }, + data: { + hw_Id: String(hw_Id), + target: "/tank_levels" + }, }); console.log(`✅ Notification sent successfully to token: ${token}`); @@ -2789,38 +2826,38 @@ exports.getPumpsAndUsers = async (req, reply) => { -const monitorWaterLevels = async () => { - try { - const tanks = await Tank.find({}); - - // Iterate through each tank - for (const tank of tanks) { - // Fetch users associated with the customerId of the tank - const users = await User.find({ customerId: tank.customerId }); - const fcmTokens = users - .map(user => user.fcmIds) - .filter(fcmIds => fcmIds) - .flat(); // Flatten if there are multiple fcmIds for each user - - // Ensure that fcmTokens exist before proceeding - if (fcmTokens.length > 0) { - const customerId = tank.customerId; - const tankName = tank.tankName; // Assuming tank has a 'name' field - const tankLocation = tank.tankLocation; // Assuming tank has a 'location' field +// const monitorWaterLevels = async () => { +// try { +// const tanks = await Tank.find({}); - // Call the function to check water levels and send notifications - //await checkWaterLevelsAndNotify(customerId, tankName, tankLocation, fcmTokens); - } else { - //console.log(`No FCM tokens found for customerId ${tank.customerId}`); - } - } - } catch (error) { - console.error('Error monitoring water levels:', error); - } -}; +// // Iterate through each tank +// for (const tank of tanks) { +// // Fetch users associated with the customerId of the tank +// const users = await User.find({ customerId: tank.customerId }); +// const fcmTokens = users +// .map(user => user.fcmIds) +// .filter(fcmIds => fcmIds) +// .flat(); // Flatten if there are multiple fcmIds for each user + +// // Ensure that fcmTokens exist before proceeding +// if (fcmTokens.length > 0) { +// const customerId = tank.customerId; +// const tankName = tank.tankName; // Assuming tank has a 'name' field +// const tankLocation = tank.tankLocation; // Assuming tank has a 'location' field + +// // Call the function to check water levels and send notifications +// //await checkWaterLevelsAndNotify(customerId, tankName, tankLocation, fcmTokens); +// } else { +// //console.log(`No FCM tokens found for customerId ${tank.customerId}`); +// } +// } +// } catch (error) { +// console.error('Error monitoring water levels:', error); +// } +// }; -// Schedule the task to run every 30 minutes -setInterval(monitorWaterLevels, 30 * 60 * 1000); +// // Schedule the task to run every 30 minutes +// setInterval(monitorWaterLevels, 30 * 60 * 1000); const motorIntervals = {}; async function calculateTotalPumpedWater(customerId, motorId, start_instance_id) { @@ -3262,6 +3299,77 @@ async function stopMotor(motorId, customerId, start_instance_id) { +const monitorWaterLevels = async () => { + try { + // console.log("⏳ Monitoring water levels..."); + + const tanks = await Tank.find(); // Fetch all tanks + //console.log("Fetched Tanks:", tanks.length); + + for (const tank of tanks) { + + +//console.log(fcmTokens) + //console.log(`🔍 Tank: ${tank.tankName} | Water Level: ${tank.waterlevel} | FCM Tokens:`, fcmTokens); + + const { + _id, + customerId, // Move this to the top + motor_id, + tankName, + blockName, + waterlevel: currentWaterLevel, + capacity, + auto_min_percentage, + reserved_percentage, + notificationSentLow, + notificationSentCritical, + } = tank; + + const users = await User.find({ customerId }); + const fcmTokens = users + .map(user => user.fcmIds) + .filter(fcmIds => Array.isArray(fcmIds) && fcmIds.length > 0) // Ensure it's an array + .flat(); + + if (!fcmTokens || fcmTokens.length === 0) { + //console.error("❌ No valid FCM tokens found for customerId:", customerId); + continue; // Skip this tank + } + const lowWaterLevel = (auto_min_percentage / 100) * capacity; // Low threshold in liters + const criticalLowWaterLevel = (reserved_percentage / 100) * capacity; // Critical threshold in liters + const currentWaterPercentage = (currentWaterLevel / capacity) * 100; // Current percentage + // const lowWaterLevel = 9483; // Low threshold in liters + // const criticalLowWaterLevel = 9483; + if (currentWaterLevel <= criticalLowWaterLevel) { + if (!notificationSentCritical) { + console.log("🚨 Sending Critical Low Water Notification..."); + eventEmitter.emit("sendCriticalLowWaterNotification", customerId, fcmTokens, motor_id, tankName, blockName, criticalLowWaterLevel, currentWaterLevel, currentWaterPercentage); + await Tank.updateOne({ _id }, { notificationSentCritical: true, notificationSentLow: true }); + } + } + else if (currentWaterLevel <= lowWaterLevel) { + if (!notificationSentLow) { + console.log("⚠️ Sending Low Water Notification..."); + eventEmitter.emit("sendLowWaterNotification", customerId, fcmTokens, motor_id, tankName, blockName, lowWaterLevel, currentWaterLevel, currentWaterPercentage); + await Tank.updateOne({ _id }, { notificationSentLow: true }); + } + } + else if (currentWaterLevel > lowWaterLevel && (notificationSentLow || notificationSentCritical)) { + console.log("🔄 Water level restored. Resetting flags."); + await Tank.updateOne({ _id }, { notificationSentCritical: false, notificationSentLow: false }); + } + + } + } catch (error) { + console.error("❌ Error monitoring water levels:", error); + } +}; + +setInterval(monitorWaterLevels, 1000); + + + // async function stopMotor(motorId, customerId, start_instance_id) { // const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); // await Tank.updateOne(