threshold time notification

master^2
Bhaskar 8 months ago
parent a2d0193df9
commit 63899009a9

@ -1387,282 +1387,6 @@ const formatDate = (date) => {
};
// 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
// console.log(req.body.startTime)
// // Ensure motor_id is provided
// if (!motorId) {
// throw new Error("Motor ID is required.");
// }
// // Determine the motor stop status based on the action
// let motorStopStatus;
// if (action === "start") {
// motorStopStatus = "2"; // If action is start, set stop status to "2"
// } else if (action === "stop") {
// motorStopStatus = "1"; // If action is stop, set stop status to "1"
// } else {
// throw new Error("Invalid action provided.");
// }
// // Update the motor stop status immediately if action is stop
// if (action === "stop") {
// // Update the motor stop status and other fields
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// {
// $set: {
// "connections.inputConnections.$.motor_stop_status": "1",
// "connections.inputConnections.$.stopTime": req.body.stopTime,
// "connections.inputConnections.$.threshold_type": null,
// "connections.inputConnections.$.manual_threshold_time": null,
// "connections.inputConnections.$.manual_threshold_percentage": null
// }
// }
// );
// // Send immediate response to the client
// reply.code(200).send({ message: "Motor stopped successfully." });
// // Perform stop operations in the background
// (async () => {
// await delay(300000);
// // Update the existing motor data entry with stop details
// const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id });
// if (motorData) {
// 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 here to ensure the rest of the code is not executed for the stop action
// return;
// } else {
// // Update the motor stop status to "2" for start action
// 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") {
// if (req.body.threshold_type === "time") {
// // If threshold type is time, update threshold time
// // await Tank.updateOne(
// // { customerId, "connections.inputConnections.motor_id": motorId },
// // { $set: { "connections.inputConnections.$.manual_threshold_time": req.body.manual_threshold_time,startTime:req.body.startTime } }
// // );
// const receiver_tank_info7 = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() });
// const newMotorData = new MotorData({
// customerId: customerId,
// motor_id: motorId,
// start_instance_id: start_instance_id,
// supplierTank: req.body.from,
// receiverTank: req.body.to,
// supplier_type: req.body.from_type,
// receiver_type: req.body.to_type,
// startTime: req.body.startTime,
// receiverInitialwaterlevel:parseInt(receiver_tank_info7.waterlevel, 10)
// });
// await newMotorData.save();
// for await (const tank of Tank.find({ "connections.inputConnections.motor_id": motorId })) {
// const index = tank.connections.inputConnections.findIndex(connection => connection.motor_id === motorId);
// if (index !== -1) {
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// { $set: { [`connections.inputConnections.${index}.manual_threshold_time`]: req.body.manual_threshold_time, [`connections.inputConnections.${index}.startTime`]: req.body.startTime,[`connections.inputConnections.${index}.start_instance_id`]: start_instance_id } }
// );
// }
// }
// // Start monitoring water level based on threshold time
// const thresholdTime = moment().add(req.body.manual_threshold_time, 'minutes').toDate();
// const intervalId = setInterval(async () => {
// const splr_tank_info3 = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() });
// const splr_tank_info3_waterlevel = parseInt(splr_tank_info3.waterlevel, 10);
// //console.log(splr_tank_info3_waterlevel,"splr_tank_info3_waterlevel")
// const splr_tank_info3_capacity = parseInt(splr_tank_info3.capacity.replace(/,/g, ''), 10);
// // const splr_tank_info3_capacity = parseInt(splr_tank_info3.capacity, 10);
// // console.log(splr_tank_info3.capacity,splr_tank_info3_capacity,"splr_tank_info3_capacity")
// const splr_tank_info3_percentage = (splr_tank_info3_waterlevel / splr_tank_info3_capacity) * 100;
// // console.log(splr_tank_info3_percentage, "percentage for less than 20");
// if (new Date() >= thresholdTime || splr_tank_info3_percentage <= 20) {
// console.log(splr_tank_info3_percentage,)
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// {
// $set: {
// "connections.inputConnections.$.motor_stop_status": "1",
// "connections.inputConnections.$.threshold_type": null,
// "connections.inputConnections.$.manual_threshold_time": null,
// "connections.inputConnections.$.manual_threshold_percentage": null
// }
// }
// );
// clearInterval(intervalId);
// await delay(300000);
// const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id });
// if (motorData) {
// 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 } })
// const stopTime = formatDate(new Date());
// await MotorData.updateOne(
// { customerId, motor_id: motorId, start_instance_id: start_instance_id },
// {
// $set: {
// stopTime:stopTime,
// receiverfinalwaterlevel: receiverFinalWaterLevel.toString(),
// quantity_delivered: quantityDelivered.toString()
// }
// }
// );
// }
// }
// }, 60000);
// } 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 newMotorData = new MotorData({
// customerId: customerId,
// motor_id: motorId,
// start_instance_id: start_instance_id,
// supplierTank: req.body.from,
// receiverTank: req.body.to,
// supplier_type: req.body.from_type,
// receiver_type: req.body.to_type,
// startTime: req.body.startTime,
// receiverInitialwaterlevel:parseInt(receiver_tank_info7.waterlevel, 10)
// });
// await newMotorData.save();
// // If threshold type is percentage, calculate percentage threshold
// const receiver_tank_info = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() });
// const supplier_tank_info = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() });
// if (!receiver_tank_info) {
// throw new Error("Receiver tank not found.");
// }
// if (!supplier_tank_info) {
// throw new Error("Supplierr tank not found.");
// }
// const supplier_capacity = parseInt(supplier_tank_info.capacity, 10);
// const supplier_waterLevel = parseInt(supplier_tank_info.waterlevel, 10);
// const capacity = parseInt(receiver_tank_info.capacity, 10);
// const waterLevel = parseInt(receiver_tank_info.waterlevel, 10);
// const desired_percentage = parseInt(req.body.manual_threshold_litres.replace(/,/g, ''), 10);
// console.log(desired_percentage)
// const threshold_water_level = waterLevel+desired_percentage;
// const supplier_threshold = supplier_waterLevel-desired_percentage
// console.log(supplier_threshold,"supplier_threshold")
// for await (const tank of Tank.find({ "connections.inputConnections.motor_id": motorId })) {
// const index = tank.connections.inputConnections.findIndex(connection => connection.motor_id === motorId);
// if (index !== -1) {
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// { $set: { [`connections.inputConnections.${index}.manual_threshold_percentage`]: supplier_threshold.toString(), [`connections.inputConnections.${index}.startTime`]: req.body.startTime } }
// );
// }
// }
// // Update water level threshold
// // Start monitoring water level based on threshold percentage
// const intervalId = setInterval(async () => {
// // Check if water level has reached the threshold percentage
// const supplier_tank_info1 = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() });
// const current_water_level = parseInt(supplier_tank_info1.waterlevel, 10);
// if (current_water_level <= supplier_threshold) {
// // Stop the motor pump
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// {
// $set: {
// "connections.inputConnections.$.motor_stop_status": "1",
// "connections.inputConnections.$.threshold_type": null,
// "connections.inputConnections.$.manual_threshold_time": null,
// "connections.inputConnections.$.manual_threshold_percentage": null
// }
// }
// );
// clearInterval(intervalId); // Stop monitoring water level
// await delay(300000);
// const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id });
// if (motorData) {
// 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 stopTime = formatDate(new Date());
// await MotorData.updateOne(
// { customerId, motor_id: motorId, start_instance_id: start_instance_id },
// {
// $set: {
// stopTime:stopTime,
// receiverfinalwaterlevel: receiverFinalWaterLevel.toString(),
// quantity_delivered: quantityDelivered.toString()
// }
// }
// );
// }
// }
// }, 20000); // Check water level every minute
// }
// }
// // Respond with success message
// reply.code(200).send({ message: `Motor ${action === "start" ? "started" : "stopped"} successfully.` });
// } catch (err) {
// // Handle errors
// throw boom.boomify(err);
// }
// };
const admin = require('firebase-admin');
// Initialize Firebase Admin SDK (make sure this is done once in your app)
@ -1673,100 +1397,6 @@ admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
// // Handle motor start event
// eventEmitter.on('motorStart', async (fcmTokens) => {
// await sendNotification(fcmTokens, 'Motor Started', 'The motor has been started successfully.');
// });
// // Handle motor stop event
// eventEmitter.on('motorStop', async (fcmTokens) => {
// await sendNotification(fcmTokens, 'Motor Stopped', 'The motor has been stopped successfully.');
// });
// // Handle low water level event
// eventEmitter.on('lowWaterLevel', async (fcmTokens) => {
// await sendNotification(fcmTokens, 'Low Water Level', 'The water level is below 20%.');
// });
// // Handle high water level event
// eventEmitter.on('highWaterLevel', async (fcmTokens) => {
// await sendNotification(fcmTokens, 'High Water Level', 'The water level has reached above 90%.');
// });
// Handle motor start event with timestamp
// eventEmitter.on('motorStart', async (fcmTokens, timestamp, motorId, waterLevel) => {
// await sendNotification(fcmTokens, 'Motor Started', `Motor ID: ${motorId} started successfully at ${timestamp}. Current Water Level: ${waterLevel} Ltrs`);
// });
// eventEmitter.on(
// 'motorStart',
// async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName, startTime, motorOnType, stopCriteria, manual_threshold_time) => {
// try {
// // Retrieve the user information
// const users = await User.find({ fcmIds: { $in: fcmTokens } });
// console.log("users", users);
// const userNames = users.map(user => user.username).join(', ');
// console.log("userNames", userNames);
// const startMethod = motorOnType === "APP" ? "via the App" : "Manual";
// // Prepare the message
// const message =
// `🚰 Tank Name: '${tankName}'\n` +
// `🕒 Pump started at: '${startTime}'\n` +
// `👤 Started by : ${userNames}\n` +
// // `Pump started by: '${motorOnType.toUpperCase()}'\n` +
// `Mode : '${startMethod}'\n` +
// `Will stop at after: '${manual_threshold_time}' mins`;
// // Send the notification
// await sendNotification(fcmTokens, 'Arminta Water Management', message);
// } catch (error) {
// console.error('Error in motorStart event:', error);
// }
// }
// );
// Event listener for motorStart
// eventEmitter.on(
// 'motorStart',
// async (customerId, fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater) => {
// try {
// // Log the FCM tokens to check their format
// console.log("FCM Tokens:", fcmTokens);
// // Retrieve the user information
// const users = await User.find({ customerId: customerId, fcmIds: { $in: fcmTokens } });
// // console.log("users", users);
// const userNames = users.map(user => user.username).join(', ');
// // console.log("userNames", userNames);
// const startMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
// // Generate motor name dynamically based on tank name, block name, and type of water
// const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// // Get current date and time for the motor start time
// const currentDateTime = new Date();
// const formattedDate = currentDateTime.toLocaleDateString(); // Customize this format as needed
// const formattedTime = currentDateTime.toLocaleTimeString(); // Customize this format as needed
// // Prepare the message
// const message =
// `🚰 Motor Name: ${motorName}\n` +
// `🚰 Tank Name: '${tankName}'\n` +
// `🏢 Block Name: '${blockName}'\n` +
// `👤 Started by: ${userNames}\n` +
// `📱 Mode: '${startMethod}'\n` +
// `🕒 Pump started at: ${startTime} \n` +
// `Will stop after: '${manual_threshold_time}' mins`;
// // Send the notification
// await sendNotification(customerId, fcmTokens, 'Arminta Water Management', message);
// } catch (error) {
// console.error('Error in motorStart event:', error);
// }
// }
// );
eventEmitter.on(
"motorStart",
@ -1880,173 +1510,6 @@ eventEmitter.on(
);
//important
// eventEmitter.on("motorStart", async (customerId, fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater) => {
// try {
// console.log("Motor Start Event Triggered for:", customerId);
// const users = await User.find({ customerId, fcmIds: { $in: fcmTokens } });
// if (users.length === 0) {
// console.log(`No users found for customerId: ${customerId}`);
// return;
// }
// const userNames = users.map(user => user.username).join(", ");
// const startMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
// const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// const message =
// `🚰 Motor Name: ${motorName}\n` +
// `🚰 Tank Name: '${tankName}'\n` +
// `🏢 Block Name: '${blockName}'\n` +
// `👤 Started by: ${userNames}\n` +
// `📱 Mode: '${startMethod}'\n` +
// `🕒 Pump started at: ${startTime} \n` +
// `Will stop after: '${manual_threshold_time}' mins`;
// await sendNotification(customerId, fcmTokens, "Arminta Water Management", message);
// } catch (error) {
// console.error("Error in motorStart event:", error);
// }
// });
// Motor Stop Event important
// eventEmitter.on("motorStop", async (customerId, fcmTokens, tankName, blockName, stopTime, motorOnType, totalWaterPumped, typeOfWater) => {
// try {
// console.log("Motor Stop Event Triggered for:", customerId);
// const users = await User.find({ customerId, fcmIds: { $in: fcmTokens } });
// if (users.length === 0) {
// console.log(`No users found for customerId: ${customerId}`);
// return;
// }
// const userNames = users.map(user => user.username).join(", ");
// const stopMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
// const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// const message =
// `🚰 Motor Name: ${motorName}\n` +
// `🛢️ Tank Name: '${tankName}'\n` +
// `🏢 Block Name: '${blockName}'\n` +
// `👤 Stopped by: ${userNames}\n` +
// `📱 Mode: '${stopMethod}'\n` +
// `🕒 Pump stopped at: ${stopTime}\n` +
// `💧 Total water pumped: ${totalWaterPumped} liters\n`;
// await sendNotification(customerId, fcmTokens, "Arminta Water Management", message);
// } catch (error) {
// console.error("Error in motorStop event:", error);
// }
// });
// eventEmitter.on(
// "motorStart",
// async (customerId, fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater) => {
// try {
// // Flatten and clean up FCM tokens
// const flatFcmTokens = fcmTokens.flat();
// const validFcmTokens = flatFcmTokens.filter(token => typeof token === 'string' && token.trim() !== '');
// // Retrieve users with matching `customerId` and valid `fcmIds`
// const users = await User.find({
// customerId: customerId,
// fcmIds: { $in: validFcmTokens } // Ensure fcmId exists in the database
// });
// console.log("Users Found:", users);
// // Check if we found any users
// if (!users.length) {
// console.log("No users found for motorStart event.");
// return;
// }
// // Extract usernames and their valid FCM tokens
// const matchedTokens = users.flatMap(user => user.fcmIds.filter(token => validFcmTokens.includes(token)));
// console.log("Matched FCM Tokens:", matchedTokens);
// // Check if there are valid tokens to send notifications
// if (matchedTokens.length === 0) {
// console.log("No valid FCM tokens found for sending notifications.");
// return;
// }
// const startMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
// const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// // Prepare the message
// // const message = `Motor ${motorOnType} started in tank ${tankName} at ${startTime}.`;
// const message =
// `🚰 Motor Name: ${motorName}\n` +
// `🚰 Tank Name: '${tankName}'\n` +
// `🏢 Block Name: '${blockName}'\n` +
// `👤 Started by: ${userNames}\n` +
// `📱 Mode: '${startMethod}'\n` +
// `🕒 Pump started at: ${startTime} \n` +
// `Will stop after: '${manual_threshold_time}' mins`;
// // Send notification to the matched users
// await sendNotification(customerId, matchedTokens, "Motor Start Notification", message);
// } catch (error) {
// console.error("Error in motorStart event:", error);
// }
// }
// );
// Event listener for motorStop
// Event listener for motorStop
// eventEmitter.on(
// 'motorStop',
// async (customerId, fcmTokens, tankName, blockName, stopTime, motorOnType, totalWaterPumped, typeOfWater) => {
// try {
// // Log the FCM tokens to check their format
// console.log("FCM Tokens:", fcmTokens);
// // Retrieve the user information based on customerId
// const users = await User.find({ customerId: customerId, fcmIds: { $in: fcmTokens } });
// console.log("users", users);
// // If no users are found, log a message and return
// if (users.length === 0) {
// console.log(`No users found for customerId: ${customerId}`);
// return;
// }
// const userNames = users.map(user => user.username).join(', ');
// const stopMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
// // Generate motor name dynamically based on tank name, block name, and type of water
// const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// // Get current date and time for the motor stop time
// const currentDateTime = new Date();
// const formattedDate = currentDateTime.toLocaleDateString(); // Customize this format as needed
// const formattedTime = currentDateTime.toLocaleTimeString(); // Customize this format as needed
// // Prepare the message
// const message =
// `🚰 Motor Name: ${motorName}\n` +
// `🛢️ Tank Name: '${tankName}'\n` +
// `🏢 Block Name: '${blockName}'\n` +
// `👤 Stopped by: ${userNames}\n` +
// `📱 Mode: '${stopMethod}'\n` +
// `🕒 Pump stopped at: ${stopTime}\n` +
// `💧 Total water pumped: ${totalWaterPumped} liters\n`;
// // Send the notification
// await sendNotification(customerId, fcmTokens, 'Arminta Water Management', message);
// } catch (error) {
// console.error('Error in motorStop event:', error);
// }
// }
// );
eventEmitter.on(
'motorStartAutomatic',
async (fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater,threshold) => {
@ -2086,78 +1549,6 @@ eventEmitter.on(
);
// eventEmitter.on('motorStop', async (fcmTokens, tankName,stopTime, motorOnType) => {
// try {
// // Retrieve the user information
// const users = await User.find({ fcmIds: { $in: fcmTokens } });
// console.log("users",users)
// const userNames = users.map(user => user.username).join(', ');
// console.log("userNames",userNames)
// const stopMethod = motorOnType === "Mobile APP" ? "via the App" : "manual";
// // Prepare the message
// // const message = `Tank Name: '${tankName}', Pump stopped at '${stopTime}' by Initiated by user(s): ${userNames} '${motorOnType}'`;
// const message =
// `🚰 Tank Name: '${tankName}'\n` +
// `🕒 Pump stopped at: '${stopTime}'\n` +
// `👤 Initiated by : ${userNames}\n` +
// // `Motor Off Type: '${motorOnType}'`;
// `Motor Off Type: '${stopMethod}'`;
// // Send the notification
// await sendNotification(fcmTokens, 'Arminta Water Management', message);
// } catch (error) {
// console.error('Error in motorStart event:', error);
// }
// });
// Emit motor stop event with motorId
// eventEmitter.on('motorStop', async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName,stopTime,motorOnType) => {
// const message = `Water supply from '${blockName}' to '${tankName}' stopped at ${stopTime} by '${motorOnType}' mode. Current Water Level: ${waterLevel} Ltrs.`;
// await sendNotification(fcmTokens, 'Motor Stopped', message);
// });
// Event listener to handle notification
// eventEmitter.on('sendLowWaterNotification', async (fcmToken, tankInfo) => {
// const message = formatWaterLevelMessage(tankInfo, 'low');
// sendNotification(fcmToken, message);
// });
// eventEmitter.on('sendVeryLowWaterNotification', async (fcmToken, tankInfo) => {
// const message = formatWaterLevelMessage(tankInfo, 'very low');
// sendNotification(fcmToken, message);
// });
// eventEmitter.on('sendCriticalLowWaterNotification', async (fcmToken, tankInfo) => {
// const message = formatWaterLevelMessage(tankInfo, 'critically low');
// sendNotification(fcmToken, message);
// });
// const formatWaterLevelMessage = (tankInfo, levelType) => {
// const tankName = tankInfo.tankName;
// const tankLocation = tankInfo.tankLocation;
// const waterLevel = parseInt(tankInfo.waterlevel, 10);
// const capacity = parseInt(tankInfo.capacity, 10);
// const volumeInLitres = (capacity * waterLevel) / 100; // assuming the capacity is in litres
// let levelDescription = '';
// if (levelType === 'low') {
// levelDescription = `${waterLevel}% (${volumeInLitres.toFixed(2)} L)`;
// } else if (levelType === 'very low') {
// levelDescription = `${waterLevel}% (${volumeInLitres.toFixed(2)} L)`;
// } else if (levelType === 'critically low') {
// levelDescription = `${waterLevel}% (${volumeInLitres.toFixed(2)} L)`;
// }
// return `Water level in '${tankName}', located at '${tankLocation}', type of water: ${tankInfo.waterType} is ${levelType} at ${levelDescription}. Action: start motor now.`;
// };
// Emit low water level event with motorId
// eventEmitter.on('lowWaterLevel', async (fcmTokens, timestamp, motorId, waterLevel) => {
// await sendNotification(fcmTokens, 'Low Water Level', `Motor ID: ${motorId}, water level dropped below 20% at ${timestamp}. Current Water Level: ${waterLevel} Ltrs`);
// });
eventEmitter.on('sendHighWaterNotification', async (fcmTokens, tankInfo, startTime, stopTime) => {
const message = `Attention: Water level in '${tankInfo.tankName}' located at '${tankInfo.tankLocation}' is high at ${tankInfo.waterLevel}% (${tankInfo.volumeInLitres} L). Please stop the motor. Motor running from ${startTime} to ${stopTime}.`;
@ -2180,9 +1571,19 @@ eventEmitter.on('sendCriticalHighWaterNotification', async (fcmTokens, tankInfo,
// await sendNotification(fcmTokens, 'High Water Level', `Motor ID: ${motorId}, water level reached above 90% at ${timestamp}. Current Water Level: ${waterLevel} Ltrs`);
// });
eventEmitter.on('sendThresholdTimeNotification', async (fcmTokens, message) => {
// eventEmitter.on('sendThresholdTimeNotification', async (fcmTokens, message) => {
// try {
// await sendNotification(fcmTokens, 'Threshold Time Reached', message, 'Motor Alert');
// console.log("Threshold time notification sent successfully.");
// } catch (error) {
// console.error("Error sending threshold time notification:", error);
// }
// });
eventEmitter.on('sendThresholdTimeNotification', async (customerId, fcmTokens, thresholdTime, hw_Id) => {
try {
await sendNotification(fcmTokens, 'Threshold Time Reached', message, 'Motor Alert');
const message = `Motor has reached its time threshold of ${thresholdTime} minutes and will stop.`;
await sendNotification(hw_Id, customerId, fcmTokens, 'Motor Alert', message);
console.log("Threshold time notification sent successfully.");
} catch (error) {
console.error("Error sending threshold time notification:", error);
@ -3506,11 +2907,7 @@ exports.motorAction = async (req, reply) => {
// await checkWaterLevelsAndNotify(customerId, tankName, receiverTank.tankLocation, fcmToken);
try {
// const { customerId, fcmToken, motorId, tankName, blockName, startTime, manual_threshold_time, typeOfWater } = req.body;
// if (!customerId || !fcmToken) {
// return reply.code(400).send({ error: "Missing required fields" });
// }
// eventEmitter.emit("motorStart", customerId, fcmToken, tankName, blockName, startTime, "Mobile APP", manual_threshold_time, typeOfWater);
eventEmitter.emit(
"motorStart",
@ -3555,6 +2952,23 @@ exports.motorAction = async (req, reply) => {
const totalWaterPumped = await calculateTotalPumpedWater(customerId, motorId, start_instance_id);
const lowWaterThreshold = 5; // Adjust as needed
const thresholdTime = new Date(manual_threshold_time); // Convert threshold time
if (new Date() >= thresholdTime || currentWaterPercentage <= lowWaterThreshold) {
console.log("Motor stopping because it entered this condition");
eventEmitter.emit(
"sendThresholdTimeNotification",
customerId,
fcmToken,
manual_threshold_time,
motorId
);
}
console.log("Motor stopped");
eventEmitter.emit("motorStop", customerId, fcmToken, tankName, blockName, stopTime, "Mobile APP", totalWaterPumped, typeOfWater, motorId,
loggedInUser.phone,);
@ -3698,11 +3112,11 @@ exports.motorAction = async (req, reply) => {
console.log(thresholdTime,"thresholdTime")
console.log("motor stopping because it entered this condition")
// Emit the threshold time notification
eventEmitter.emit(
"sendThresholdTimeNotification",
fcmToken,
`Motor has reached its time threshold of ${req.body.manual_threshold_time} minutes and will stop.`
);
// eventEmitter.emit(
// "sendThresholdTimeNotification",
// fcmToken,
// `Motor has reached its time threshold of ${req.body.manual_threshold_time} minutes and will stop.`
// );
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId },

Loading…
Cancel
Save