changes start and stop

master^2
Bhaskar 8 months ago
parent 15d08db0bf
commit 165bd6ff9e

@ -1595,25 +1595,64 @@ admin.initializeApp({
// await sendNotification(fcmTokens, 'Motor Started', `Motor ID: ${motorId} started successfully at ${timestamp}. Current Water Level: ${waterLevel} Ltrs`); // 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( eventEmitter.on(
'motorStart', 'motorStart',
async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName, startTime, motorOnType, stopCriteria, manual_threshold_time) => { async (fcmTokens, tankName, blockName, startTime, motorOnType, manual_threshold_time, typeOfWater) => {
try { try {
// Retrieve the user information // Retrieve the user information
const users = await User.find({ fcmIds: { $in: fcmTokens } }); const users = await User.find({ fcmIds: { $in: fcmTokens } });
console.log("users", users); console.log("users", users);
const userNames = users.map(user => user.username).join(', '); const userNames = users.map(user => user.username).join(', ');
console.log("userNames", userNames); 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 // Prepare the message
const message = const message =
`🚰 Motor Name: ${motorName}\n` +
`🚰 Tank Name: '${tankName}'\n` + `🚰 Tank Name: '${tankName}'\n` +
`🕒 Pump started at: '${startTime}'\n` + `🚰 Block Name: '${blockName}'\n` +
`👤 Initiated by : ${userNames}\n` + `👤 Started by: ${userNames}\n` +
// `Pump started by: '${motorOnType.toUpperCase()}'\n` + `📱 Mode: '${startMethod}'\n` +
`🔄 Pump started by: '${startMethod}'\n` + `🕒 Pump started at: ${startTime} (Time: ${formattedTime} on ${formattedDate})\n` +
`Will stop at after: '${manual_threshold_time}' mins`; `Will stop after: '${manual_threshold_time}' mins`;
// Send the notification // Send the notification
await sendNotification(fcmTokens, 'Arminta Water Management', message); await sendNotification(fcmTokens, 'Arminta Water Management', message);
@ -1623,33 +1662,71 @@ eventEmitter.on(
} }
); );
// 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 } });
const userNames = users.map(user => user.username).join(', ');
const stopMethod = motorOnType === "Mobile APP" ? "Mobile APP" : "Manual";
eventEmitter.on('motorStop', async (fcmTokens, tankName,stopTime, motorOnType) => { // Generate motor name dynamically based on tank name, block name, and type of water
try { const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// 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";
// 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}'`;
// Get current date and time for the motor stop time
// Send the notification const currentDateTime = new Date();
await sendNotification(fcmTokens, 'Arminta Water Management', message); const formattedDate = currentDateTime.toLocaleDateString(); // Customize this format as needed
} catch (error) { const formattedTime = currentDateTime.toLocaleTimeString(); // Customize this format as needed
console.error('Error in motorStart event:', error);
// 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} (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 motorStop 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 // Emit motor stop event with motorId
// eventEmitter.on('motorStop', async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName,stopTime,motorOnType) => { // eventEmitter.on('motorStop', async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName,stopTime,motorOnType) => {
@ -2314,6 +2391,17 @@ const monitorWaterLevels = async () => {
setInterval(monitorWaterLevels, 30 * 60 * 1000); setInterval(monitorWaterLevels, 30 * 60 * 1000);
const motorIntervals = {}; 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) => { exports.motorAction = async (req, reply) => {
try { try {
const customerId = req.params.customerId; const customerId = req.params.customerId;
@ -2340,7 +2428,8 @@ exports.motorAction = async (req, reply) => {
console.log(receiverTank) console.log(receiverTank)
const currentWaterLevel = parseInt(receiverTank.waterlevel, 10); const currentWaterLevel = parseInt(receiverTank.waterlevel, 10);
const waterLevelThresholds = { low: 30, veryLow: 20, criticallyLow: 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 // Determine the motor stop status based on the action
let motorStopStatus; let motorStopStatus;
@ -2362,39 +2451,25 @@ exports.motorAction = async (req, reply) => {
); );
const thresholdTimeMs = req.body.manual_threshold_time * 60 * 1000; // Convert minutes to milliseconds const thresholdTimeMs = req.body.manual_threshold_time * 60 * 1000; // Convert minutes to milliseconds
const stopCriteria = const stopCriteria =
motorOnType === "time" motorOnType === "time"
? `${req.body.manual_threshold_time} minutes` ? `${req.body.manual_threshold_time} minutes`
: `${req.body.manual_threshold_litres} litres`; : `${req.body.manual_threshold_litres} litres`;
await checkWaterLevelsAndNotify(customerId, tankName, receiverTank.tankLocation, fcmToken); 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) { if (!notificationSentStatus.motorStart) {
eventEmitter.emit( eventEmitter.emit(
"motorStart", 'motorStart',
fcmToken, fcmToken,
new Date().toISOString(), tankName,
motorId, blockName,
currentWaterLevel, startTime,
blockName, "Mobile APP",
tankName, manual_threshold_time,
startTime, typeOfWater
"APP",
manual_threshold_time
); );
notificationSentStatus.motorStart = true; // Set flag to true to prevent duplicate notifications notificationSentStatus.motorStart = true; // Set flag to true to prevent duplicate notifications
} }
await Tank.updateOne( await Tank.updateOne(
@ -2405,17 +2480,6 @@ exports.motorAction = async (req, reply) => {
"connections.inputConnections.$.motor_on_type": motorOnType } } "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." }); reply.code(200).send({ message: "Motor started successfully." });
} else if (action === "stop") { } else if (action === "stop") {
@ -2434,13 +2498,28 @@ exports.motorAction = async (req, reply) => {
// stopTime, // stopTime,
// motorOnType // motorOnType
// ); // );
if (!notificationSentStatus.motorStop) { 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( eventEmitter.emit(
"motorStop", 'motorStop',
fcmToken, fcmToken,
tankName, tankName,
stopTime, blockName,
"APP" stopTime,
"Mobile APP",
totalWaterPumped, // Include total water pumped
typeOfWater
); );
notificationSentStatus.motorStop = true; // Set flag to true to prevent duplicate notifications notificationSentStatus.motorStop = true; // Set flag to true to prevent duplicate notifications
} }

Loading…
Cancel
Save