forced_manual notfications

master^2
Bhaskar 7 months ago
parent 2254b20ba9
commit c0d38cb06d

@ -2105,61 +2105,87 @@ eventEmitter.on('sendThresholdTimeNotification', async (fcmTokens, message) => {
// ); // );
eventEmitter.on( eventEmitter.on(
'sendMotorStartNotification', "sendMotorStartNotification",
async ( async (
customerId,
fcmTokens, fcmTokens,
waterLevel,
blockName, blockName,
tankName, tankName,
motorOnType, motorOnType,
stopCriteria, stopCriteria,
typeOfWater, typeOfWater,
highThreshold // Add the high threshold as a parameter manualThresholdTime
) => { ) => {
try { try {
// Get the latest timestamp // Get the latest timestamp
const currentDateTime = new Date(); const currentDateTime = new Date();
const startTime = currentDateTime.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }); const formattedDate = currentDateTime.toLocaleDateString("en-IN", { timeZone: "Asia/Kolkata" });
const formattedDate = currentDateTime.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata' }); const formattedTime = currentDateTime.toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" });
const formattedTime = currentDateTime.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata' });
// Retrieve the user information // Fetch users based on the customerId
const users = await User.find({ fcmIds: { $in: fcmTokens } }); const users = await User.find({ customerId }).select("username fcmIds notificationPreference lastNotificationSent");
const userNames = users.map(user => user.username).join(', ');
if (!users || users.length === 0) {
console.log(`No users found for customer ID: ${customerId}`);
return;
}
const userNames = users.map(user => user.username).join(", ");
// Filter valid FCM tokens for the specific customer
const validTokens = users.flatMap(user => user.fcmIds).filter(token => fcmTokens.includes(token));
if (validTokens.length === 0) {
console.log(`No valid FCM tokens found for customer ID: ${customerId}`);
return;
}
// Check if the motor was started manually (forced manual)
if (motorOnType !== "forced_manual") {
console.log(`Skipping notification: Motor was started in ${motorOnType} mode.`);
return;
}
// Determine the pump initiation method // Determine the pump initiation method
const startMethod = motorOnType === "Forced Manual" ? "Physically" : "Manually" const startMethod = motorOnType === "forced_manual" ? "Physically" : "Manually";
// Dynamically generate the motor name // Generate the motor name dynamically
const motorName = `${tankName}-${blockName}-${typeOfWater}`; const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// Determine the stop condition message // Determine stop condition message
let stopConditionMessage = ""; let stopConditionMessage = "";
if (stopCriteria === "manual") { if (stopCriteria === "manual") {
stopConditionMessage = `Will stop at Manually \n`; stopConditionMessage = `⚠️ Pump will stop **manually**.\n`;
} else if (stopCriteria === "highThreshold") { } else if (stopCriteria === "threshold") {
stopConditionMessage = `🚨 Pump will stop when the water level reaches the high threshold of ${highThreshold}%.\n`; stopConditionMessage = `🚨 Pump will stop when the water level reaches **${manualThresholdTime}%**.\n`;
} }
// Prepare the notification message // Prepare the notification message
const message = const message =
`🚰 Motor Name: ${motorName}\n` + `🚰 **Motor Started** 🚀\n` +
`🛢️ Tank Name: '${tankName}'\n` + `🔹 **Motor Name:** ${motorName}\n` +
`🏢 Block Name: '${blockName}'\n` + `🛢️ **Tank Name:** ${tankName}\n` +
`👤 Started by: ${userNames}\n` + `🏢 **Block Name:** ${blockName}\n` +
`📱 Mode: '${startMethod}'\n` + `💧 **Water Level:** ${waterLevel}%\n` +
`🕒 Pump started at: ${startTime} \n` + `👤 **Started by:** ${userNames}\n` +
stopConditionMessage; // Add only the relevant stop condition `📱 **Mode:** ${startMethod}\n` +
`🕒 **Pump started at:** ${formattedTime}\n` +
stopConditionMessage;
// Send the notification // Send the notification
await sendNotification(fcmTokens, 'Motor Started 🚀', message); await sendNotification(customerId, validTokens, "Motor Started 🚀", message);
console.log('Motor start notification with stop criteria sent successfully!');
console.log(`Motor start notification sent successfully to customer ID: ${customerId}`);
} catch (error) { } catch (error) {
console.error('Error in sendMotorStartNotification event:', error); console.error(`Error in sendMotorStartNotification event for customer ID: ${customerId}`, error);
} }
} }
); );
// eventEmitter.on( // eventEmitter.on(
// 'sendMotorStartNotification', // 'sendMotorStartNotification',
// async (fcmTokens, motorId, waterLevel, blockName, tankName, motorOnType, stopCriteria, manual_threshold_time, typeOfWater) => { // async (fcmTokens, motorId, waterLevel, blockName, tankName, motorOnType, stopCriteria, manual_threshold_time, typeOfWater) => {
@ -2203,84 +2229,59 @@ eventEmitter.on(
// ); // );
// eventEmitter.on(
// 'sendMotorStopNotification',
// async (fcmTokens, motorId, waterLevel, blockName, tankName, motorOnType) => {
// try {
// // Get the latest timestamp
// const stopTime = new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' });
// // Retrieve the user information
// const users = await User.find({ fcmIds: { $in: fcmTokens } });
// const userNames = users.map(user => user.username).join(', ');
// const stopMethod = motorOnType.toUpperCase() === "Forced Manual";
// // Prepare the message
// const message =
// `🚰 Tank Name: '${tankName}'\n` +
// `🕒 Pump stopped at: '${stopTime}'\n` +
// `👤 Initiated by: ${userNames}\n` +
// `🔄 Pump stopped by: '${stopMethod}'\n`;
// // Send the notification
// await sendNotification(fcmTokens, 'Motor Stopped 🛑', message);
// console.log('Motor stop notification sent successfully!');
// } catch (error) {
// console.error('Error in sendMotorStopNotification event:', error);
// }
// }
// );
eventEmitter.on( eventEmitter.on(
'sendMotorStopNotification', "sendMotorStopNotification",
async ( async (customerId, fcmTokens, waterLevel, blockName, tankName, motorOnType,typeOfWater) => {
fcmTokens,
blockName,
tankName,
motorOnType,
typeOfWater
) => {
try { try {
// Get the latest timestamp // Get the latest timestamp
const currentDateTime = new Date(); const currentDateTime = new Date();
const stopTime = currentDateTime.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }); const formattedDate = currentDateTime.toLocaleDateString("en-IN", { timeZone: "Asia/Kolkata" });
const formattedDate = currentDateTime.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata' }); const formattedTime = currentDateTime.toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" });
const formattedTime = currentDateTime.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata' });
// Retrieve the user information // Fetch users based on the customerId
const users = await User.find({ fcmIds: { $in: fcmTokens } }); const users = await User.find({ customerId }).select("username fcmIds notificationPreference lastNotificationSent");
const userNames = users.map(user => user.username).join(', ');
if (!users || users.length === 0) {
console.log(`No users found for customer ID: ${customerId}`);
return;
}
const userNames = users.map(user => user.username).join(", ");
// Filter valid FCM tokens for the specific customer
const validTokens = users.flatMap(user => user.fcmIds).filter(token => fcmTokens.includes(token));
// Determine the pump stop method if (validTokens.length === 0) {
const stopMethod = motorOnType === "Forced Manual" ? "Physically" : "Manually"; console.log(`No valid FCM tokens found for customer ID: ${customerId}`);
return;
}
// Dynamically generate the motor name // Generate the motor name dynamically
const motorName = `${tankName}-${blockName}-${typeOfWater}`; const motorName = `${tankName}-${blockName}-${typeOfWater}`;
// Determine the stop condition message
let stopConditionMessage = "";
if (stopCriteria === "manual") {
stopConditionMessage = `Stopped at Manually \n`;
} else if (stopCriteria === "highThreshold") {
stopConditionMessage = `🚨 Pump will stop when the water level reaches the high threshold of ${highThreshold}%.\n`;
}
// Prepare the notification message // Prepare the notification message
const message = const message =
`🚰 Motor Name: ${motorName}\n` + `⏹️ **Motor Stopped** 🛑\n` +
`🛢️ Tank Name: '${tankName}'\n` + `🔹 **Motor Name:** ${motorName}\n` +
`🏢 Block Name: '${blockName}'\n` + `🛢️ **Tank Name:** ${tankName}\n` +
`📱 Mode: '${stopMethod}'\n` + `🏢 **Block Name:** ${blockName}\n` +
`🕒 Pump stopped at: ${stopTime}\n` + `💧 **Water Level:** ${waterLevel}%\n` +
stopConditionMessage; `👤 **Stopped by:** ${userNames}\n` +
`📱 **Mode:** ${motorOnType}\n` +
`🕒 **Pump stopped at:** ${formattedTime}\n`;
// Send the notification // Send the notification
await sendNotification(fcmTokens, 'Motor Stopped 🛑', message); await sendNotification(customerId, validTokens, "Motor Stopped 🛑", message);
console.log('Motor stop notification sent successfully!');
console.log(`Motor stop notification sent successfully to customer ID: ${customerId}`);
} catch (error) { } catch (error) {
console.error('Error in sendMotorStopNotification event:', error); console.error(`Error in sendMotorStopNotification event for customer ID: ${customerId}`, error);
} }
} }
); );
// eventEmitter.on('sendLowWaterNotification', (fcmTokens, message) => { // eventEmitter.on('sendLowWaterNotification', (fcmTokens, message) => {
// const notificationMessage = `Warning: Water level is low in the tank. // const notificationMessage = `Warning: Water level is low in the tank.
// Tank Name: ${tankName}, // Tank Name: ${tankName},
@ -6257,116 +6258,82 @@ client.on('message', async (topic, message) => {
if (topic === 'water/iot-data') { if (topic === 'water/iot-data') {
try { try {
const data = JSON.parse(message.toString()); const data = JSON.parse(message.toString());
const { hw_Id, Motor_status, tanks } = data.objects; // Updated variable names according to new format const { hw_Id, Motor_status, tanks } = data.objects;
// Get the current date and time in the required format
const currentDate = new Date(); const currentDate = new Date();
const date = currentDate.toISOString(); // ISO string for date const date = currentDate.toISOString();
const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); // Time in 'HH:MM:SS' const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' });
// Create array of tank documents with current date and time
const tankDocuments = tanks.map(tank => ({
tankhardwareId: tank.Id, // Updated to match the new format
tankHeight: tank.level, // Updated to match the new format
date,
time
}));
// Save IoT data for the received tanks
const iotTankData = new IotData({
hardwareId: hw_Id, // Updated variable name
Motor_status,
tanks: tankDocuments,
date,
time
});
await iotTankData.save();
// Delete excess records (keep only the latest three records)
const recordsToKeep = 3;
const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) // Updated variable name
.sort({ date: -1, time: -1 })
.skip(recordsToKeep);
for (const record of recordsToDelete) {
await record.remove();
}
// Process each tank to update water level and connections // Process each tank to update water level and connections
for (const tank of tanks) { for (const tank of tanks) {
const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format const { Id: tankhardwareId, level: tankHeight } = tank;
// Find the corresponding tank in the Tank schema using hardwareId and tankhardwareId const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); // Updated variable name
if (!existingTank) continue; if (!existingTank) continue;
const customerId = existingTank.customerId; const customerId = existingTank.customerId;
const tank_name = existingTank.tankName; const tankName = existingTank.tankName;
// Calculate water level using tank height and capacity // Fetch FCM tokens of users linked to this customer
const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; // Convert height to cm const users = await User.find({ customerId }).select("fcmIds");
const fcmTokens = users.flatMap(user => user.fcmIds).filter(token => token); // Get valid FCM tokens
if (!fcmTokens.length) {
console.log(`No valid FCM tokens found for customer ID: ${customerId}`);
}
// Calculate water level
const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48;
const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); const tank_height = parseInt(tankHeightInCm.toFixed(0), 10);
const waterLevelHeight = tank_height - tankHeight; const waterLevelHeight = tank_height - tankHeight;
const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level if (tankHeight > 0 && waterLevel >= 0) {
// Update water level in the existing tank
console.log(tankHeight,"this is located in tank controllers at iot-data mqtt sub ")
if (tankHeight>0 && waterLevel >= 0) {
existingTank.waterlevel = waterLevel; existingTank.waterlevel = waterLevel;
await existingTank.save(); await existingTank.save();
// Update linked tanks (input/output connections)
for (const outputConnection of existingTank.connections.outputConnections) {
const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type });
if (linkedTank) {
for (const inputConnection of linkedTank.connections.inputConnections) {
if (inputConnection.inputConnections === tank_name) {
inputConnection.water_level = waterLevel; // Update water level for linked tank
await linkedTank.save(); // Save updated linked tank
}
}
}
}
} }
} }
// Update motor status // Motor Status Processing
const status = Motor_status; const status = Motor_status;
const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); // Updated variable name const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id });
if (!motorTank) { if (!motorTank) {
console.log('Motor not found for the specified motor_id'); console.log('Motor not found for the specified motor_id');
return; return;
} }
// Find the inputConnection for the motor and update motor status const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name const user = await User.findOne({ customerId: motorTank.customerId });
const user = await User.findOne({ customerId: motorTank.customerId }); // Fetch user by customerId const allowNotifications = user?.manualStartAndStopNotify ?? true;
const allowNotifications = user?.manualStartAndStopNotify ?? true; // Default to true if not set
if (inputConnection) { if (inputConnection) {
inputConnection.motor_status = status; // Update motor status inputConnection.motor_status = status;
const tankName = motorTank.tankName; const tankName = motorTank.tankName;
if (allowNotifications && inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") { if (allowNotifications && inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") {
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
inputConnection.motor_stop_status = "2"; inputConnection.motor_stop_status = "2";
inputConnection.motor_on_type = "forced_manual"; inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = currentTime; inputConnection.startTime = currentTime;
eventEmitter.emit( // Determine stop criteria dynamically
"sendMotorStartNotification", const stopCriteria = inputConnection.motor_stop_status === "1" ? "manual" : "threshold";
fcmToken, // FCM tokens
hw_Id, // Motor ID eventEmitter.emit(
inputConnection.water_level || 0, // Water level "sendMotorStartNotification",
motorTank.blockName || "N/A", // Block name customerId, // Pass customerId
tankName, // Tank name fcmTokens, // Pass FCM tokens
inputConnection.motor_on_type, // Motor on type hw_Id, // Motor ID
"threshold", // Stop criteria inputConnection.water_level || 0, // Water level
manual_threshold_time // Threshold time in mins motorTank.blockName || "N/A", // Block name
); tankName, // Tank name
inputConnection.motor_on_type, // Motor on type
stopCriteria, // Stop criteria (manual/threshold)
manual_threshold_time // Threshold time (only used for threshold stop)
);
} }
if (allowNotifications && inputConnection.motor_stop_status === "2" && status === 1) { if (allowNotifications && inputConnection.motor_stop_status === "2" && status === 1) {
@ -6376,20 +6343,20 @@ client.on('message', async (topic, message) => {
eventEmitter.emit( eventEmitter.emit(
"sendMotorStopNotification", "sendMotorStopNotification",
fcmToken, // FCM tokens customerId, // Pass customerId
fcmTokens, // Pass FCM tokens
hw_Id, // Motor ID hw_Id, // Motor ID
inputConnection.water_level || 0, // Water level inputConnection.water_level || 0,
motorTank.blockName || "N/A", // Block name motorTank.blockName || "N/A",
tankName, // Tank name tankName,
inputConnection.motor_on_type // Motor on type inputConnection.motor_on_type
); );
} }
await motorTank.save(); // Save the updated tank await motorTank.save();
} }
console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name console.log('Data processed successfully for hardwareId:', hw_Id);
} catch (err) { } catch (err) {
console.error('Error processing message:', err.message); console.error('Error processing message:', err.message);
} }

Loading…
Cancel
Save