low and critical alert notifications

master^2
Bhaskar 7 months ago
parent 62832705fb
commit 126075f5aa

@ -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) => { // eventEmitter.on('sendLowWaterNotification', (fcmTokens, message) => {
@ -2138,7 +2172,10 @@ const sendNotification = async (hw_Id, customerId, fcmIds, title, body) => {
const response = await admin.messaging().send({ const response = await admin.messaging().send({
token, token,
notification: { title, body }, 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}`); console.log(`✅ Notification sent successfully to token: ${token}`);
@ -2789,38 +2826,38 @@ exports.getPumpsAndUsers = async (req, reply) => {
const monitorWaterLevels = async () => { // const monitorWaterLevels = async () => {
try { // try {
const tanks = await Tank.find({}); // 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
// Call the function to check water levels and send notifications // // Iterate through each tank
//await checkWaterLevelsAndNotify(customerId, tankName, tankLocation, fcmTokens); // for (const tank of tanks) {
} else { // // Fetch users associated with the customerId of the tank
//console.log(`No FCM tokens found for customerId ${tank.customerId}`); // const users = await User.find({ customerId: tank.customerId });
} // const fcmTokens = users
} // .map(user => user.fcmIds)
} catch (error) { // .filter(fcmIds => fcmIds)
console.error('Error monitoring water levels:', error); // .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 // // Schedule the task to run every 30 minutes
setInterval(monitorWaterLevels, 30 * 60 * 1000); // setInterval(monitorWaterLevels, 30 * 60 * 1000);
const motorIntervals = {}; const motorIntervals = {};
async function calculateTotalPumpedWater(customerId, motorId, start_instance_id) { 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) { // async function stopMotor(motorId, customerId, start_instance_id) {
// const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); // const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
// await Tank.updateOne( // await Tank.updateOne(

Loading…
Cancel
Save