changes for tesing multiple devices to server mqtt

master^2
Varun 7 months ago
parent 4b4a9b91ec
commit c829041483

@ -5851,639 +5851,138 @@ exports.getBlockData = async (req, reply) => {
// });
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker
const client = mqtt.connect('mqtt://35.207.198.4:1883');
const subscribedTopics = new Set();
client.on('connect', () => {
console.log('Connected to MQTT broker');
client.subscribe('water/iot-data', (err) => {
client.subscribe('water/iot-data/+', (err) => {
if (err) {
console.error('Error subscribing to topic:', err);
console.error('Error subscribing to wildcard topic:', err);
} else {
console.log('Subscribed to water/iot-data topic');
console.log('Subscribed to water/iot-data/+ wildcard topic');
}
});
});
// client.on("message", async (topic, message) => {
// console.log(`📩 Message received on topic ${topic}:`, message.toString());
// if (topic === "water/iot-data") {
// try {
// const data = JSON.parse(message.toString());
// const { hw_Id, Motor_status, tanks } = data.objects;
// const currentDate = new Date();
// const time = currentDate.toLocaleTimeString("en-IN", { hour12: false, timeZone: "Asia/Kolkata" });
// for (const tank of tanks) {
// const { Id: tankhardwareId, level: tankHeight } = tank;
// const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
// if (!existingTank) continue;
// const customerId = existingTank.customerId;
// const tankName = existingTank.tankName;
// console.log(`🔍 Checking FCM tokens for Customer ID: ${customerId}`);
// const users = await User.find({ customerId }).select("fcmIds");
// let fcmTokens = users.flatMap(user => user.fcmIds).filter(token => token);
// console.log(`📡 Found ${fcmTokens.length} FCM tokens for Customer ID: ${customerId}`);
// if (!Array.isArray(fcmTokens) || fcmTokens.length === 0) {
// console.warn(`⚠️ No valid FCM tokens found for Customer ID: ${customerId}`);
// continue;
// }
// const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id });
// if (!motorTank) {
// console.warn(`⚠️ Motor not found for motor_id: ${hw_Id}`);
// return;
// }
// const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
// console.log(`📢 Emitting 'sendMotorStartNotification' for hw_Id: ${hw_Id}`);
// if (inputConnection) {
// const blockName = motorTank.blockName || "N/A";
// console.log(`🚀 blockName`, blockName);
// console.log("🔍 Debugging Condition Check:");
// console.log("🛠️ inputConnection.motor_stop_status:", inputConnection.motor_stop_status);
// console.log("🛠️ Motor_status:", Motor_status);
// console.log("🛠️ inputConnection.motor_on_type:", inputConnection.motor_on_type);
// if (inputConnection.motor_stop_status == 1 && Motor_status == 2) { // Removed forced_manual check
// inputConnection.motor_stop_status = "2";
// inputConnection.motor_on_type = "forced_manual";
// inputConnection.startTime = new Date().toISOString();
// console.log("🚀 Motor started in FORCED_MANUAL mode.");
// console.log("📢 Emitting sendMotorStartNotification event...");
// eventEmitter.emit(
// "sendMotorStartNotification",
// hw_Id,
// customerId,
// fcmTokens,
// inputConnection.water_level || 0,
// blockName,
// tankName,
// "forced_manual",
// inputConnection.stop_criteria,
// inputConnection.typeOfWater,
// inputConnection.manual_threshold_time
// );
// await motorTank.markModified("connections.inputConnections");
// await motorTank.save(); // Ensure the change is saved
// console.log("💾 motorTank saved successfully.");
// }
// console.log("🛠️ Debugging Motor Stop Condition:");
// console.log("🛠️ inputConnection.motor_stop_status:", inputConnection.motor_stop_status);
// console.log("🛠️ Motor_status:", Motor_status);
// if (inputConnection.motor_stop_status == 2 && Motor_status == 1) {
// console.log("🛑 Motor stopping... Updating motor_stop_status.");
// inputConnection.motor_stop_status = 1;
// inputConnection.stopTime = new Date().toISOString();
// console.log("📢 Emitting sendMotorStopNotification event...");
// eventEmitter.emit(
// "sendMotorStopNotification",
// hw_Id,
// customerId,
// fcmTokens,
// inputConnection.water_level || 0,
// blockName,
// tankName,
// "forced_manual",
// inputConnection.typeOfWater
// );
// await motorTank.markModified("connections.inputConnections");
// await motorTank.save();
// console.log("💾 motorTank saved successfully.");
// } else {
// console.log("❌ Stop condition not met. No notification sent.");
// }
// }
// }
// console.log(`✅ Data processed successfully for hardwareId: ${hw_Id}`);
// } catch (err) {
// console.error(`❌ Error processing message: ${err.message}`);
// }
// }
// });
// client.on("message", async (topic, message) => {
// console.log(`📩 Message received on topic ${topic}:`, message.toString());
// if (topic === "water/iot-data") {
// try {
// const data = JSON.parse(message.toString());
// const { hw_Id, Motor_status, tanks } = data.objects;
// for (const tank of tanks) {
// const { Id: tankhardwareId } = tank;
// const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
// if (!existingTank) continue;
// const customerId = existingTank.customerId;
// const tankName = existingTank.tankName;
// console.log(`🔍 Checking FCM tokens for Customer ID: ${customerId}`);
// const users = await User.find({ customerId }).select("fcmIds");
// let fcmTokens = users.flatMap(user => user.fcmIds).filter(token => token);
// console.log(`📡 Found ${fcmTokens.length} FCM tokens for Customer ID: ${customerId}`);
// if (!Array.isArray(fcmTokens) || fcmTokens.length === 0) {
// console.warn(`⚠️ No valid FCM tokens found for Customer ID: ${customerId}`);
// continue;
// }
// const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id });
// if (!motorTank) {
// console.warn(`⚠️ Motor not found for motor_id: ${hw_Id}`);
// return;
// }
// const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
// if (!inputConnection) {
// console.warn(`⚠️ No inputConnection found for motor_id: ${hw_Id}`);
// return;
// }
// console.log(`📢 Processing motor logic for hw_Id: ${hw_Id}`);
// const blockName = motorTank.blockName || "N/A";
// console.log("🔍 Debugging Condition Check:");
// console.log("🛠️ inputConnection.motor_stop_status:", inputConnection.motor_stop_status);
// console.log("🛠️ Motor_status:", Motor_status);
// console.log("🛠️ inputConnection.motor_on_type:", inputConnection.motor_on_type);
// /** 🔥 MOTOR START LOGIC */
// if (Motor_status === 2 && inputConnection.motor_stop_status === 1) {
// // Only update if motor_stop_status is still 1 (motor was previously OFF)
// inputConnection.motor_stop_status = 2;
// inputConnection.motor_on_type = "forced_manual";
// inputConnection.startTime = new Date().toISOString();
// console.log("🚀 Motor started. Updating motor_stop_status to 2.");
// console.log("📢 Emitting sendMotorStartNotification event...");
// eventEmitter.emit(
// "sendMotorStartNotification",
// hw_Id,
// customerId,
// fcmTokens,
// inputConnection.water_level || 0,
// blockName,
// tankName,
// "forced_manual",
// inputConnection.stop_criteria,
// inputConnection.typeOfWater,
// inputConnection.manual_threshold_time
// );
// await motorTank.markModified("connections.inputConnections");
// await motorTank.save();
// console.log("💾 motorTank saved successfully after start.");
// }
// /** 🔥 MOTOR STOP LOGIC */
// console.log("🛠️ Debugging Motor Stop Condition:");
// console.log("🛠️ inputConnection.motor_stop_status:", inputConnection.motor_stop_status);
// console.log("🛠️ Motor_status:", Motor_status);
// if (Motor_status === 1 && inputConnection.motor_stop_status === 2) {
// // Only update if motor_stop_status was previously 2 (motor was ON)
// console.log("🛑 Motor stopping... Updating motor_stop_status to 1.");
// inputConnection.motor_stop_status = 1;
// inputConnection.stopTime = new Date().toISOString();
// console.log("📢 Emitting sendMotorStopNotification event...");
// eventEmitter.emit(
// "sendMotorStopNotification",
// hw_Id,
// customerId,
// fcmTokens,
// inputConnection.water_level || 0,
// blockName,
// tankName,
// "forced_manual",
// inputConnection.typeOfWater
// );
// await motorTank.markModified("connections.inputConnections");
// await motorTank.save();
// console.log("💾 motorTank saved successfully after stop.");
// } else {
// console.log("⚠️ Stop condition not met. No notification sent.");
// }
// }
// console.log(`✅ Data processed successfully for hardwareId: ${hw_Id}`);
// } catch (err) {
// console.error(`❌ Error processing message: ${err.message}`);
// }
// }
// });
// Handling incoming MQTT messages important
// client.on('message', async (topic, message) => {
// console.log(`Message received on topic ${topic}:`, message.toString());
// if (topic === 'water/iot-data') {
// try {
// const data = JSON.parse(message.toString());
// const { hw_Id, Motor_status, tanks } = data.objects; // Updated variable names according to new format
// // Get the current date and time in the required format
// const currentDate = new Date();
// const date = currentDate.toISOString(); // ISO string for date
// const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); // Time in 'HH:MM:SS'
// // 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
// for (const tank of tanks) {
// const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format
// // Find the corresponding tank in the Tank schema using hardwareId and tankhardwareId
// const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); // Updated variable name
// if (!existingTank) continue;
// const customerId = existingTank.customerId;
// const tank_name = existingTank.tankName;
// // Calculate water level using tank height and capacity
// const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; // Convert height to cm
// 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); // Calculated water level
// // 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;
// 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
// const status = Motor_status;
// const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); // Updated variable name
// if (!motorTank) {
// console.log('Motor not found for the specified motor_id');
// return;
// }
// // Find the inputConnection for the motor and update motor status
// const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name
// const user = await User.findOne({ customerId: motorTank.customerId }); // Fetch user by customerId
// const allowNotifications = user?.manualStartAndStopNotify ?? true; // Default to true if not set
// if (!motorTank) {
// console.warn(`⚠️ Motor not found for motor_id: ${hw_Id}`);
// return;
// }
// if (!inputConnection) {
// console.warn(`⚠️ No inputConnection found for motor_id: ${hw_Id}`);
// return;
// }
// if (inputConnection) {
// inputConnection.motor_status = status; // Update motor status
// const tankName = motorTank.tankName;
// const customerId = motorTank.customerId;
// console.log("tankName",tankName)
// console.log("customerId", customerId)
// console.log("status", status)
// // Ensure fcmTokens are fetched before emitting
// // const user = await User.findOne({ customerId: motorTank.customerId }).select("fcmIds manualStartAndStopNotify");
// // const fcmTokens = user?.fcmIds || []; // Ensure fcmTokens is an array
// // console.log("fcmTokens", fcmTokens)
// const users = await User.findOne({ customerId : motorTank.customerId}).select("fcmIds");
// let fcmTokens = users.fcmIds.filter(token => token);
// console.log(`📡 Found ${fcmTokens.length} FCM tokens for Customer ID: ${customerId}`);
// if (!Array.isArray(fcmTokens) || fcmTokens.length === 0) {
// console.warn(`⚠️ No valid FCM tokens found for Customer ID: ${customerId}`);
// }
// console.log(`📢 Processing motor logic for hw_Id: ${hw_Id}`);
// const blockName = motorTank.blockName || "N/A";
// console.log("🔍 Debugging Condition Check:");
// console.log("🛠️ inputConnection.motor_stop_status:", inputConnection.motor_stop_status);
// console.log("🛠️ Motor_status:", status);
// console.log("🛠inputConnection.motor_status:", inputConnection.motor_status);
// console.log("🛠️ inputConnection.motor_on_type:", inputConnection.motor_on_type);
// // if (status === 2 && inputConnection.motor_stop_status === "1" && inputConnection.motor_on_type !== "forced_manual") {
// // // Only update if motor_stop_status is still 1 (motor was previously OFF)
// // inputConnection.motor_stop_status ="2";
// // inputConnection.motor_on_type = "forced_manual";
// // inputConnection.startTime = new Date().toISOString();
// // // status = 1;
// // // inputConnection.motor_status = "1";
// // console.log("🛠️ IN inputConnection.motor_stop_status:", inputConnection.motor_stop_status);
// // console.log("🛠In Motor_status:", status);
// // console.log("🛠In inputConnection.motor_status:", inputConnection.motor_status);
// // console.log("🚀 Motor started. Updating motor_stop_status to 2.");
// // console.log("📢 Emitting sendMotorStartNotification event...");
// // await motorTank.markModified("connections.inputConnections");
// // await motorTank.save();
// // console.log("💾 motorTank saved successfully after start.");
// // eventEmitter.emit(
// // "sendMotorStartNotification",
// // hw_Id,
// // customerId,
// // fcmTokens,
// // inputConnection.water_level || 0,
// // blockName,
// // tankName,
// // "forced_manual",
// // inputConnection.stop_criteria,
// // inputConnection.typeOfWater,
// // inputConnection.manual_threshold_time
// // );
// // }
// // console.log(`🔍 Checking stop condition: status=${status}, motor_stop_status=${inputConnection.motor_stop_status}`);
// // if (status === 1 && inputConnection.motor_stop_status === "2") {
// // console.log("🛑 Motor stopping... Updating motor_stop_status to 1.");
// // inputConnection.motor_stop_status = "1";
// // inputConnection.stopTime = new Date().toISOString();
// // await motorTank.markModified("connections.inputConnections");
// // await motorTank.save(); // Ensure data is saved before emitting
// // console.log("📢 Emitting sendMotorStopNotification event...");
// // eventEmitter.emit(
// // "sendMotorStopNotification",
// // hw_Id,
// // customerId,
// // fcmTokens,
// // inputConnection.water_level || 0,
// // blockName,
// // tankName,
// // "forced_manual",
// // inputConnection.typeOfWater
// // );
// // }
// // if (status === 2 && inputConnection.motor_stop_status === "1" && inputConnection.motor_on_type !== "forced_manual") {
// // // Motor is starting (only execute this block)
// // inputConnection.motor_stop_status = "2"; // Motor is now running
// // inputConnection.motor_on_type = "forced_manual";
// // inputConnection.startTime = new Date().toISOString();
// // console.log("🚀 Motor started. Updating motor_stop_status to 2.");
// // console.log("📢 Emitting sendMotorStartNotification event...");
// // await motorTank.markModified("connections.inputConnections");
// // await motorTank.save();
// // console.log("💾 motorTank saved successfully after start.");
// // eventEmitter.emit(
// // "sendMotorStartNotification",
// // hw_Id,
// // customerId,
// // fcmTokens,
// // inputConnection.water_level || 0,
// // blockName,
// // tankName,
// // "forced_manual",
// // inputConnection.stop_criteria,
// // inputConnection.typeOfWater,
// // inputConnection.manual_threshold_time
// // );
// // } else if (status === 1 && inputConnection.motor_stop_status === "2") {
// // // Motor is stopping (only execute this block)
// // console.log("🛑 Motor stopping... Updating motor_stop_status to 1.");
// // inputConnection.motor_stop_status = "1"; // Motor is now OFF
// // inputConnection.stopTime = new Date().toISOString();
// // await motorTank.markModified("connections.inputConnections");
// // await motorTank.save(); // Ensure data is saved before emitting
// // console.log("📢 Emitting sendMotorStopNotification event...");
// // eventEmitter.emit(
// // "sendMotorStopNotification",
// // hw_Id,
// // customerId,
// // fcmTokens,
// // inputConnection.water_level || 0,
// // blockName,
// // tankName,
// // "forced_manual",
// // inputConnection.typeOfWater
// // );
// // }
// console.log(`🔍 Final condition: status=${status}, motor_stop_status=${inputConnection.motor_stop_status}`);
// await motorTank.save(); // Save the updated tank
// }
client.on('message', async (topic, message) => {
console.log(`Message received on topic ${topic}:`, message.toString());
// console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name
if (!topic.startsWith('water/iot-data/')) return;
// } catch (err) {
// console.error('Error processing message:', err.message);
// }
// }
// });
try {
const data = JSON.parse(message.toString());
const { hw_Id, Motor_status, tanks } = data.objects;
const deviceTopic = `water/iot-data/${hw_Id}`;
if (!subscribedTopics.has(deviceTopic)) {
client.subscribe(deviceTopic, (err) => {
if (err) console.error(`Error subscribing to topic ${deviceTopic}:`, err);
else {
console.log(`Subscribed to device-specific topic: ${deviceTopic}`);
subscribedTopics.add(deviceTopic);
}
});
}
client.on('message', async (topic, message) => {
console.log(`Message received on topic ${topic}:`, message.toString());
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
if (topic === 'water/iot-data') {
try {
const data = JSON.parse(message.toString());
const { hw_Id, Motor_status, tanks } = data.objects; // Updated variable names according to new format
// Get the current date and time in the required format
const currentDate = new Date();
const date = currentDate.toISOString(); // ISO string for date
const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); // Time in 'HH:MM:SS'
// 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
}));
// Create tank documents
const tankDocuments = tanks.map((tank) => ({
tankhardwareId: tank.Id,
tankHeight: tank.level,
date: currentTime,
}));
// Save IoT data
const iotTankData = new IotData({
hardwareId: hw_Id,
Motor_status,
tanks: tankDocuments,
date: currentTime,
});
// 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();
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);
// Keep only the latest 3 records
const recordsToDelete = await IotData.find({ hardwareId: hw_Id })
.sort({ date: -1 })
.skip(3);
for (const record of recordsToDelete) {
await record.remove();
}
await Promise.all(recordsToDelete.map((record) => record.remove()));
// Process each tank to update water level and connections
for (const tank of tanks) {
const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format
// Find the corresponding tank in the Tank schema using hardwareId and tankhardwareId
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); // Updated variable name
if (!existingTank) continue;
// Process each tank update
await Promise.all(
tanks.map(async (tank) => {
const { Id: tankhardwareId, level: tankHeight } = tank;
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
if (!existingTank) return;
const customerId = existingTank.customerId;
const tank_name = existingTank.tankName;
// Calculate water level using tank height and capacity
const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; // Convert height to cm
const tank_height = parseInt(tankHeightInCm.toFixed(0), 10);
const waterLevelHeight = tank_height - tankHeight;
const tankHeightInCm = parseInt(existingTank.height.replace(/,/g, ''), 10) * 30.48;
const waterLevelHeight = tankHeightInCm - tankHeight;
const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level
console.log(tankHeight, "Processed in IoT Data MQTT Subscription");
// 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) {
if (tankHeight > 0 && waterLevel >= 0) {
existingTank.waterlevel = waterLevel;
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 linked tanks
await Promise.all(
existingTank.connections.outputConnections.map(async (outputConnection) => {
const linkedTank = await Tank.findOne({
customerId,
tankName: outputConnection.outputConnections,
tankLocation: outputConnection.output_type,
});
if (linkedTank) {
linkedTank.connections.inputConnections.forEach((inputConnection) => {
if (inputConnection.inputConnections === tank_name) {
inputConnection.water_level = waterLevel;
}
});
await linkedTank.save();
}
}
}
})
);
}
}
})
);
// Update motor status
const status = Motor_status;
const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); // Updated variable name
// Update 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;
}
if (!motorTank) {
console.log('Motor not found for the specified motor_id');
return;
}
const inputConnection = motorTank.connections.inputConnections.find((conn) => conn.motor_id === hw_Id);
if (inputConnection) {
inputConnection.motor_status = Motor_status;
// Find the inputConnection for the motor and update motor status
const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name
if (inputConnection) {
inputConnection.motor_status = status; // Update motor status
if (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');
inputConnection.motor_stop_status = "2";
inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = currentTime;
}
if (inputConnection.motor_stop_status === "2" && status === 1) {
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
inputConnection.motor_stop_status = "1";
inputConnection.stopTime = currentTime;
}
await motorTank.save(); // Save the updated tank
if (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 = currentTime;
}
console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name
if (inputConnection.motor_stop_status === "2" && Motor_status === 1) {
inputConnection.motor_stop_status = "1";
inputConnection.stopTime = currentTime;
}
} catch (err) {
console.error('Error processing message:', err.message);
await motorTank.save();
}
console.log('Successfully processed data for hardwareId:', hw_Id);
} catch (err) {
console.error('Error processing message:', err.message);
}
});

Loading…
Cancel
Save