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) => {
try {
const customerId = req.params.customerId;
const { tankName,tankLocation, auto_min_percentage, auto_max_percentage } = req.body;
// Update inputConnections' auto_mode
const { tankName, tankLocation, auto_min_percentage, auto_max_percentage, auto_mode_type } = req.body;
// 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
await Tank.updateOne(
{ customerId: customerId,tankLocation, tankName},
// Update auto_min_percentage, auto_max_percentage, and auto_mode_type
await Tank.updateMany(
filter,
{
$set: {
"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
const getFormattedISTTime = () => {
@ -5234,49 +5242,58 @@ exports.getBlockData = async (req, reply) => {
// }
// }
// });
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', () => {
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) {
console.error('Error subscribing to topic:', err);
} 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) => {
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
const topicParts = topic.split('/'); // Split the topic to get the hardwareId
const hardwareId = topicParts[2]; // Extract hardwareId from topic
// Get the current date and time in the required format
const { Motor_status, tanks } = data.objects;
// Process data for the specific device
await processDeviceData(hardwareId, Motor_status, tanks);
} catch (err) {
console.error('Error processing message:', err.message);
}
});
// Function to process data for each device
async function processDeviceData(hw_Id, Motor_status, tanks) {
try {
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'
const time = moment().tz('Asia/Kolkata').format('HH:mm:ss'); // Time in 'HH:mm:ss'
// Create array of tank documents with current date and time
// Prepare tank documents
const tankDocuments = tanks.map(tank => ({
tankhardwareId: tank.Id, // Updated to match the new format
tankHeight: tank.level, // Updated to match the new format
tankhardwareId: tank.Id,
tankHeight: tank.level,
date,
time
}));
// Save IoT data for the received tanks
// Save IoT data for the device
const iotTankData = new IotData({
hardwareId: hw_Id, // Updated variable name
hardwareId: hw_Id,
Motor_status,
tanks: tankDocuments,
date,
@ -5286,7 +5303,7 @@ client.on('message', async (topic, message) => {
// Delete excess records (keep only the latest three records)
const recordsToKeep = 3;
const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) // Updated variable name
const recordsToDelete = await IotData.find({ hardwareId: hw_Id })
.sort({ date: -1, time: -1 })
.skip(recordsToKeep);
@ -5294,38 +5311,38 @@ client.on('message', async (topic, message) => {
await record.remove();
}
// Process each tank to update water level and connections
// Update water levels for tanks
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
const { Id: tankhardwareId, level: tankHeight } = tank;
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
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 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
// 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)
// Update linked tanks
for (const outputConnection of existingTank.connections.outputConnections) {
const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type });
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
inputConnection.water_level = waterLevel;
await linkedTank.save();
}
}
}
@ -5334,64 +5351,33 @@ client.on('message', async (topic, message) => {
}
// Update 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) {
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) {
inputConnection.motor_status = status; // Update motor status
const tankName = motorTank.tankName;
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_status = Motor_status;
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;
// 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
// );
inputConnection.startTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
}
if (inputConnection.motor_stop_status === "2" && status === 1) {
if (inputConnection.motor_stop_status === "2" && Motor_status === 1) {
inputConnection.motor_stop_status = "1";
// Emit motor stop notification with tankName
// eventEmitter.emit(
// "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
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) {
console.error('Error processing message:', err.message);
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" },
reserved_percentage: { type: String, default: "20" },
auto_max_percentage: { type: String, default: "80" },
auto_mode_type: { type: String, default: "default" },
notificationSentCritical: { type: Boolean },
notificationSentVeryLow: { type: Boolean },
notificationSentLow: { type: Boolean },

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

Loading…
Cancel
Save