@ -1595,25 +1595,64 @@ admin.initializeApp({
// 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 ( fcmTokens , timestamp , motorId , waterLevel , blockName , tankName , startTime , motorOnType , stopCriteria , manual _threshold _time ) => {
async ( fcmTokens , t ankName, bloc kName, startTime , motorOnType , manual_threshold _time , typeOfWater ) => {
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" ;
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 ` +
` 🕒 Pump started at: ' ${ startTime } ' \n ` +
` 👤 Initiated by : ${ userNames } \n ` +
// `Pump started by: '${motorOnType.toUpperCase()}'\n` +
` 🔄 Pump started by: ' ${ startMethod } ' \n ` +
` Will stop at after: ' ${ manual _threshold _time } ' mins ` ;
` 🚰 Block Name: '${ blockNa me} ' \n ` +
` 👤 Started by : ${ userNames } \n ` +
` 📱 Mode: ' ${ startMethod } ' \n ` +
` 🕒 Pump started at: ${ startTime } (Time: ${ formattedTime } on ${ formattedDate } ) \n ` +
` Will stop a fter: '${ manual _threshold _time } ' mins ` ;
// Send the notification
await sendNotification ( fcmTokens , 'Arminta Water Management' , message ) ;
@ -1623,33 +1662,71 @@ eventEmitter.on(
}
) ;
eventEmitter . on ( 'motorStop' , async ( fcmTokens , tankName , stopTime , motorOnType ) => {
// Event listener for motorStop
eventEmitter . on (
'motorStop' ,
async ( fcmTokens , tankName , blockName , stopTime , motorOnType , totalWaterPumped , typeOfWater ) => {
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 === "APP" ? "via the App" : "manual" ;
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 = `Tank Name: '${tankName}', Pump stopped at '${stopTime}' by Initiated by user(s): ${userNames} '${motorOnType}'`;
const message =
` 🚰 Motor Name: ${ motorName } \n ` +
` 🚰 Tank Name: ' ${ tankName } ' \n ` +
` 🕒 Pump stopped at: ' ${ stopTime } ' \n ` +
` 👤 Initiated by : ${ userNames } \n ` +
// `Motor Off Type: '${motorOnType}'`;
` Motor Off Type: ' ${ stopMethod } ' ` ;
` 🚰 Block Name: ' ${ blockNa me} ' \n ` +
` 👤 Stopped by : ${ userNames } \n ` +
` 📱 Mode: ' ${ stopMethod } ' \n ` +
` 🕒 Pump stopped at: ${ stopTime } (Time: ${ formattedTime } on ${ formattedDate } ) \n ` +
` 💧 Total water pumped: ${ totalWaterPumped } liters \n ` ; // Ensure this line is properly terminated
// Send the notification
await sendNotification ( fcmTokens , 'Arminta Water Management' , message ) ;
} catch ( error ) {
console . error ( 'Error in motorSt art event:', error ) ;
console . error ( 'Error in motorSt op event:', error ) ;
}
} ) ;
}
) ;
// 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) => {
@ -2314,6 +2391,17 @@ const monitorWaterLevels = async () => {
setInterval ( monitorWaterLevels , 30 * 60 * 1000 ) ;
const motorIntervals = { } ;
async function calculateTotalPumpedWater ( customerId , motorId , start _instance _id ) {
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 waterPumpedTillNow = parseInt ( receiverTank . total _water _added _from _midnight , 10 ) ;
return quantityDelivered + waterPumpedTillNow ; // Total water pumped
}
return 0 ; // Return 0 if no data found
}
exports . motorAction = async ( req , reply ) => {
try {
const customerId = req . params . customerId ;
@ -2340,7 +2428,8 @@ exports.motorAction = async (req, reply) => {
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 ;
@ -2369,32 +2458,18 @@ exports.motorAction = async (req, reply) => {
await checkWaterLevelsAndNotify ( customerId , tankName , receiverTank . tankLocation , fcmToken ) ;
// eventEmitter.emit(
// "motorStart",
// fcmToken,
// new Date().toISOString(),
// motorId,
// currentWaterLevel,
// blockName, // Block Name
// tankName, // Tank Name
// startTime,
// motorOnType,
// stopCriteria,
// manual_threshold_time
// );
if ( ! notificationSentStatus . motorStart ) {
eventEmitter . emit (
"motorStart" ,
'motorStart' ,
fcmToken ,
new Date ( ) . toISOString ( ) ,
motorId ,
currentWaterLevel ,
blockName ,
tankName ,
blockName ,
startTime ,
"APP" ,
manual _threshold _time
"Mobile APP" ,
manual _threshold _time ,
typeOfWater
) ;
notificationSentStatus . motorStart = true ; // Set flag to true to prevent duplicate notifications
}
await Tank . updateOne (
@ -2405,17 +2480,6 @@ exports.motorAction = async (req, reply) => {
"connections.inputConnections.$.motor_on_type" : motorOnType } }
) ;
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// {
// $set: {
// "connections.inputConnections.$.motor_stop_status": "2",
// "connections.inputConnections.$.motor_on_type": "manual",
// }
// }
// );
reply . code ( 200 ) . send ( { message : "Motor started successfully." } ) ;
} else if ( action === "stop" ) {
@ -2434,13 +2498,28 @@ exports.motorAction = async (req, reply) => {
// stopTime,
// motorOnType
// );
if ( ! notificationSentStatus . motorStop ) {
// eventEmitter.emit(
// "motorStop",
// fcmToken,
// tankName,
// stopTime,
// "APP"
// );
// Emit motorStop event
const totalWaterPumped = await calculateTotalPumpedWater ( customerId , motorId , start _instance _id ) ; // A function to calculate total water pumped
eventEmitter . emit (
"motorStop" ,
'motorStop' ,
fcmToken ,
tankName ,
blockName ,
stopTime ,
"APP"
"Mobile APP" ,
totalWaterPumped , // Include total water pumped
typeOfWater
) ;
notificationSentStatus . motorStop = true ; // Set flag to true to prevent duplicate notifications
}