master^2
Bhaskar 8 months ago
parent 1af5427f25
commit 928855819d

@ -6349,7 +6349,6 @@ client.on('message', async (topic, message) => {
const date = currentDate.toISOString();
const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' });
// Process each tank to update water level
for (const tank of tanks) {
const { Id: tankhardwareId, level: tankHeight } = tank;
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
@ -6359,110 +6358,72 @@ client.on('message', async (topic, message) => {
const customerId = existingTank.customerId;
const tankName = existingTank.tankName;
// Fetch FCM tokens of users linked to this customer
console.log(`🔍 Checking FCM tokens for Customer ID: ${customerId}`);
const users = await User.find({ customerId }).select("fcmIds");
const fcmTokens = users.flatMap(user => user.fcmIds).filter(token => token);
console.log(`📡 Found ${fcmTokens.length} FCM tokens for Customer ID: ${customerId}`);
if (!fcmTokens.length) {
console.log(`⚠️ No valid FCM tokens found for Customer ID: ${customerId}`);
console.warn(`⚠️ 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 waterLevelHeight = tank_height - tankHeight;
const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10);
const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id });
if (tankHeight > 0 && waterLevel >= 0) {
existingTank.waterlevel = waterLevel;
await existingTank.save();
if (!motorTank) {
console.warn(`⚠️ Motor not found for motor_id: ${hw_Id}`);
return;
}
}
// 🔹 Motor Status Processing
// 🔹 Motor Status Processing
const status = Motor_status;
const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id });
if (!motorTank) {
console.log(`⚠️ Motor not found for motor_id: ${hw_Id}`);
return;
}
// ✅ Extract customerId from motorTank
const customerId = motorTank.customerId;
if (!customerId) {
console.error(`❌ Error: customerId is missing for motor_id: ${hw_Id}`);
return;
}
// ✅ Find users linked to this customer and extract valid FCM tokens
const users = await User.find({ customerId }).select("fcmIds");
const fcmTokens = users.flatMap(user => user.fcmIds).filter(token => token);
if (!fcmTokens.length) {
console.log(`⚠️ No valid FCM tokens found for Customer ID: ${customerId}`);
}
// ✅ Extract motor input connection details
const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
if (inputConnection) {
const blockName = motorTank.blockName || "N/A";
const tankName = motorTank.tankName;
const allowNotifications = (await User.findOne({ customerId }))?.manualStartAndStopNotify ?? true;
// ✅ Motor Start Notification
if (allowNotifications && inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") {
inputConnection.motor_stop_status = "2";
inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = new Date().toISOString();
console.log(`🚀 Motor started in FORCED_MANUAL mode.`);
// Determine stop criteria
const stopCriteria = inputConnection.motor_stop_status === "1" ? "manual" : "threshold";
eventEmitter.emit(
"sendMotorStartNotification",
hw_Id,
customerId, // ✅ Pass customerId here
fcmTokens,
inputConnection.water_level || 0,
blockName,
tankName,
"forced_manual",
stopCriteria,
inputConnection.typeOfWater,
inputConnection.manual_threshold_time
);
}
// 🛑 Motor Stop Notification
if (allowNotifications && inputConnection.motor_stop_status === "2" && status === 1) {
inputConnection.motor_stop_status = "1";
inputConnection.stopTime = new Date().toISOString();
console.log(`🛑 Motor stopped manually.`);
eventEmitter.emit(
"sendMotorStopNotification",
hw_Id,
customerId, // ✅ Ensure customerId is passed
fcmTokens,
inputConnection.water_level || 0,
blockName,
tankName,
"forced_manual",
inputConnection.typeOfWater
);
}
await motorTank.save();
const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
if (inputConnection) {
const blockName = motorTank.blockName || "N/A";
const allowNotifications = (await User.findOne({ customerId }))?.manualStartAndStopNotify ?? true;
if (allowNotifications && inputConnection.motor_stop_status === "1" && Motor_status === 2 && inputConnection.motor_on_type !== "forced_manual") {
inputConnection.motor_stop_status = "2";
inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = new Date().toISOString();
console.log(`🚀 Motor started in FORCED_MANUAL mode.`);
eventEmitter.emit(
"sendMotorStartNotification",
hw_Id,
customerId,
fcmTokens,
inputConnection.water_level || 0,
blockName,
tankName,
"forced_manual",
inputConnection.typeOfWater,
inputConnection.manual_threshold_time
);
}
if (allowNotifications && inputConnection.motor_stop_status === "2" && Motor_status === 1) {
inputConnection.motor_stop_status = "1";
inputConnection.stopTime = new Date().toISOString();
console.log(`🛑 Motor stopped manually.`);
eventEmitter.emit(
"sendMotorStopNotification",
hw_Id,
customerId,
fcmTokens,
inputConnection.water_level || 0,
blockName,
tankName,
"forced_manual",
inputConnection.typeOfWater
);
}
await motorTank.save();
}
}
console.log(`✅ Data processed successfully for hardwareId: ${hw_Id}`);

Loading…
Cancel
Save