changes in auto mode

master^2
Varun 8 months ago
parent ee968ce27d
commit 80a4775e2a

@ -4985,18 +4985,25 @@ exports.update_auto_mode = async (req, reply) => {
exports.update_auto_percentage = async (req, reply) => { exports.update_auto_percentage = async (req, reply) => {
try { try {
const customerId = req.params.customerId; const customerId = req.params.customerId;
const { tankName,tankLocation, auto_min_percentage, auto_max_percentage } = req.body; const { tankName, tankLocation, auto_min_percentage, auto_max_percentage, auto_mode_type } = req.body;
// Update inputConnections' auto_mode // Build the query filter
const filter = { customerId: customerId };
if (tankName !== "all") {
filter.tankName = tankName;
}
if (tankLocation) {
filter.tankLocation = tankLocation;
}
// Update auto_min_percentage and auto_max_percentage // Update auto_min_percentage, auto_max_percentage, and auto_mode_type
await Tank.updateOne( await Tank.updateMany(
{ customerId: customerId,tankLocation, tankName}, filter,
{ {
$set: { $set: {
"auto_min_percentage": auto_min_percentage, "auto_min_percentage": auto_min_percentage,
"auto_max_percentage": auto_max_percentage "auto_max_percentage": auto_max_percentage,
"auto_mode_type": auto_mode_type
} }
} }
); );
@ -5008,6 +5015,7 @@ exports.update_auto_percentage = async (req, reply) => {
}; };
//storing water level for every 15 minutes //storing water level for every 15 minutes
const getFormattedISTTime = () => { const getFormattedISTTime = () => {
@ -5234,164 +5242,142 @@ exports.getBlockData = async (req, reply) => {
// } // }
// } // }
// }); // });
const mqtt = require('mqtt'); const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker
// Connect to MQTT broker
const client = mqtt.connect('mqtt://35.207.198.4:1883');
client.on('connect', () => { client.on('connect', () => {
console.log('Connected to MQTT broker'); console.log('Connected to MQTT broker');
client.subscribe('water/iot-data', (err) => {
// Subscribe to all topics under water/iot-data/
client.subscribe('water/iot-data/#', (err) => {
if (err) { if (err) {
console.error('Error subscribing to topic:', err); console.error('Error subscribing to topic:', err);
} else { } else {
console.log('Subscribed to water/iot-data topic'); console.log('Subscribed to water/iot-data/#');
} }
}); });
}); });
// Handling incoming MQTT messages // Handle incoming MQTT messages
client.on('message', async (topic, message) => { client.on('message', async (topic, message) => {
console.log(`Message received on topic ${topic}:`, message.toString()); try {
const data = JSON.parse(message.toString());
const topicParts = topic.split('/'); // Split the topic to get the hardwareId
const hardwareId = topicParts[2]; // Extract hardwareId from topic
if (topic === 'water/iot-data') { const { Motor_status, tanks } = data.objects;
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
}));
// Process data for the specific device
await processDeviceData(hardwareId, Motor_status, tanks);
} catch (err) {
console.error('Error processing message:', err.message);
}
});
// Save IoT data for the received tanks // Function to process data for each device
const iotTankData = new IotData({ async function processDeviceData(hw_Id, Motor_status, tanks) {
hardwareId: hw_Id, // Updated variable name try {
Motor_status, const currentDate = new Date();
tanks: tankDocuments, const date = currentDate.toISOString(); // ISO string for date
date, const time = moment().tz('Asia/Kolkata').format('HH:mm:ss'); // Time in 'HH:mm:ss'
time
});
await iotTankData.save();
// Delete excess records (keep only the latest three records) // Prepare tank documents
const recordsToKeep = 3; const tankDocuments = tanks.map(tank => ({
const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) // Updated variable name tankhardwareId: tank.Id,
.sort({ date: -1, time: -1 }) tankHeight: tank.level,
.skip(recordsToKeep); date,
time
}));
for (const record of recordsToDelete) { // Save IoT data for the device
await record.remove(); const iotTankData = new IotData({
} hardwareId: hw_Id,
Motor_status,
tanks: tankDocuments,
date,
time
});
await iotTankData.save();
// Process each tank to update water level and connections // Delete excess records (keep only the latest three records)
for (const tank of tanks) { const recordsToKeep = 3;
const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format const recordsToDelete = await IotData.find({ hardwareId: hw_Id })
// Find the corresponding tank in the Tank schema using hardwareId and tankhardwareId .sort({ date: -1, time: -1 })
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); // Updated variable name .skip(recordsToKeep);
if (!existingTank) continue;
for (const record of recordsToDelete) {
const customerId = existingTank.customerId; await record.remove();
const tank_name = existingTank.tankName; }
// Calculate water level using tank height and capacity // Update water levels for tanks
const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; // Convert height to cm for (const tank of tanks) {
const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); const { Id: tankhardwareId, level: tankHeight } = tank;
const waterLevelHeight = tank_height - tankHeight;
const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
if (!existingTank) continue;
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level
const customerId = existingTank.customerId;
// Update water level in the existing tank const tank_name = existingTank.tankName;
console.log(tankHeight,"this is located in tank controllers at iot-data mqtt sub ")
if (tankHeight>0 && waterLevel >= 0) { const tankHeightInCm = parseInt(existingTank.height.replace(/,/g, ''), 10) * 30.48;
existingTank.waterlevel = waterLevel; const waterLevelHeight = tankHeightInCm - tankHeight;
await existingTank.save(); const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10);
// Update linked tanks (input/output connections)
for (const outputConnection of existingTank.connections.outputConnections) { if (tankHeight > 0 && waterLevel >= 0) {
const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type }); existingTank.waterlevel = waterLevel;
if (linkedTank) { await existingTank.save();
for (const inputConnection of linkedTank.connections.inputConnections) {
if (inputConnection.inputConnections === tank_name) { // Update linked tanks
inputConnection.water_level = waterLevel; // Update water level for linked tank for (const outputConnection of existingTank.connections.outputConnections) {
await linkedTank.save(); // Save updated linked tank 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;
await linkedTank.save();
} }
} }
} }
} }
} }
}
// Update motor status // Update motor status
const status = Motor_status; const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id });
const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); // Updated variable name if (motorTank) {
const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
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
if (inputConnection) { if (inputConnection) {
inputConnection.motor_status = status; // Update motor status inputConnection.motor_status = Motor_status;
const tankName = motorTank.tankName;
if (inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") { if (inputConnection.motor_stop_status === "1" && Motor_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_stop_status = "2";
inputConnection.motor_on_type = "forced_manual"; inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = currentTime; inputConnection.startTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
// Emit motor start notification with tankName
// eventEmitter.emit(
// "sendMotorStartNotification",
// fcmToken, // FCM tokens
// hw_Id, // Motor ID
// inputConnection.water_level || 0, // Water level
// motorTank.blockName || "N/A", // Block name
// tankName, // Tank name
// inputConnection.motor_on_type, // Motor on type
// "threshold", // Stop criteria
// manual_threshold_time // Threshold time in mins
// );
} }
if (inputConnection.motor_stop_status === "2" && status === 1) {
inputConnection.motor_stop_status = "1";
// Emit motor stop notification with tankName if (inputConnection.motor_stop_status === "2" && Motor_status === 1) {
// eventEmitter.emit( inputConnection.motor_stop_status = "1";
// "sendMotorStopNotification",
// fcmToken, // FCM tokens
// hw_Id, // Motor ID
// inputConnection.water_level || 0, // Water level
// motorTank.blockName || "N/A", // Block name
// tankName, // Tank name
// inputConnection.motor_on_type // Motor on type
// );
} }
await motorTank.save(); // Save the updated tank
}
console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name await motorTank.save();
}
} catch (err) {
console.error('Error processing message:', err.message);
} }
console.log(`Data processed successfully for hardwareId: ${hw_Id}`);
} catch (err) {
console.error(`Error processing data for hardwareId ${hw_Id}:`, err.message);
} }
}); }

@ -55,6 +55,7 @@ const tanksSchema = new mongoose.Schema({
auto_min_percentage: { type: String, default: "20" }, auto_min_percentage: { type: String, default: "20" },
reserved_percentage: { type: String, default: "20" }, reserved_percentage: { type: String, default: "20" },
auto_max_percentage: { type: String, default: "80" }, auto_max_percentage: { type: String, default: "80" },
auto_mode_type: { type: String, default: "default" },
notificationSentCritical: { type: Boolean }, notificationSentCritical: { type: Boolean },
notificationSentVeryLow: { type: Boolean }, notificationSentVeryLow: { type: Boolean },
notificationSentLow: { type: Boolean }, notificationSentLow: { type: Boolean },

@ -1070,6 +1070,7 @@ module.exports = function (fastify, opts, next) {
auto_min_percentage: { type: "string", default: null }, auto_min_percentage: { type: "string", default: null },
auto_max_percentage: { type: "string", default: null }, auto_max_percentage: { type: "string", default: null },
tankLocation: { type: "string", default: null }, tankLocation: { type: "string", default: null },
auto_mode_type: { type: "string", default: "default" },
}, },
}, },

Loading…
Cancel
Save