Bhaskar 8 months ago
commit f85ac6efef

@ -5881,144 +5881,148 @@ 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) => { 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 all IoT devices under water/iot-data/#');
} }
}); });
}); });
client.on('message', async (topic, message) => { client.on('message', async (topic, message) => {
console.log(`Message received on topic ${topic}:`, message.toString()); console.log(`Message received on topic ${topic}:`, message.toString());
if (topic === 'water/iot-data') { try {
try { const topicParts = topic.split('/'); // ['water', 'iot-data', '140924']
const data = JSON.parse(message.toString()); const hw_Id = topicParts[2]; // Extract hardwareId from topic
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
}));
if (!hw_Id) {
console.error('Invalid topic format: Missing hw_Id');
return;
}
// Save IoT data for the received tanks const data = JSON.parse(message.toString());
const iotTankData = new IotData({ const { Motor_status, tanks } = data.objects;
hardwareId: hw_Id, // Updated variable name
Motor_status,
tanks: tankDocuments,
date,
time
});
await iotTankData.save();
// Delete excess records (keep only the latest three records) console.log(`Processing data for hardwareId: ${hw_Id}`);
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) { // Get the current date and time in the required format
await record.remove(); const currentTime = moment().tz('Asia/Kolkata');
} const date = currentTime.format('YYYY-MM-DD'); // Adjust format if needed
const time = currentTime.format('HH:mm:ss');
// Process each tank to update water level and connections // Create tank documents
for (const tank of tanks) { const tankDocuments = tanks.map(tank => ({
const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format tankhardwareId: tank.Id,
// Find the corresponding tank in the Tank schema using hardwareId and tankhardwareId tankHeight: tank.level,
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); // Updated variable name date,
if (!existingTank) continue; time,
}));
const customerId = existingTank.customerId;
const tank_name = existingTank.tankName; // Save IoT data
const iotTankData = new IotData({
// Calculate water level using tank height and capacity hardwareId: hw_Id,
const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; // Convert height to cm Motor_status,
const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); tanks: tankDocuments,
const waterLevelHeight = tank_height - tankHeight; date,
const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); time,
});
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level await iotTankData.save();
// Update water level in the existing tank // Delete excess records (keep only the latest three records)
console.log(tankHeight,"this is located in tank controllers at iot-data mqtt sub ") const recordsToKeep = 3;
if (tankHeight>0 && waterLevel >= 0) { const recordsToDelete = await IotData.find({ hardwareId: hw_Id })
existingTank.waterlevel = waterLevel; .sort({ date: -1, time: -1 })
await existingTank.save(); .skip(recordsToKeep);
// Update linked tanks (input/output connections) await Promise.all(recordsToDelete.map(record => record.remove()));
for (const outputConnection of existingTank.connections.outputConnections) {
const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type }); // Process tanks and update water level
if (linkedTank) { for (const tank of tanks) {
for (const inputConnection of linkedTank.connections.inputConnections) { const { Id: tankhardwareId, level: tankHeight } = tank;
if (inputConnection.inputConnections === tank_name) { const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
inputConnection.water_level = waterLevel; // Update water level for linked tank if (!existingTank) continue;
await linkedTank.save(); // Save updated linked tank
} const customerId = existingTank.customerId;
const tank_name = existingTank.tankName;
// Convert height and calculate water level
const tankHeightInCm = parseInt(existingTank.height.replace(/,/g, ''), 10) * 30.48;
const tank_height = Math.round(tankHeightInCm);
const waterLevelHeight = tank_height - tankHeight;
const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10);
const waterLevel = Math.max(0, waterLevelHeight * waterCapacityPerCm);
console.log(`${tankHeight} - Processed in MQTT subscriber`);
if (tankHeight > 0) {
existingTank.waterlevel = waterLevel;
await existingTank.save();
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;
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) {
console.log(`Motor not found for motor_id: ${hw_Id}`);
return;
}
if (!motorTank) { const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
console.log('Motor not found for the specified motor_id'); if (inputConnection) {
return; inputConnection.motor_status = Motor_status;
}
// Find the inputConnection for the motor and update motor status if (inputConnection.motor_stop_status === "1" && Motor_status === 2 && inputConnection.motor_on_type !== "forced_manual") {
const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name inputConnection.motor_stop_status = "2";
if (inputConnection) { inputConnection.motor_on_type = "forced_manual";
inputConnection.motor_status = status; // Update motor status inputConnection.startTime = currentTime.format('DD-MMM-YYYY - HH:mm');
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.motor_on_type = "manual";
inputConnection.stopTime = currentTime;
}
await motorTank.save(); // Save the updated tank
} }
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.format('DD-MMM-YYYY - HH:mm');
}
} catch (err) { await motorTank.save();
console.error('Error processing message:', err.message);
} }
console.log(`Processed successfully for hardwareId: ${hw_Id}`);
} catch (err) {
console.error('Error processing message:', err.message);
} }
}); });
const sendMotorNotifications = async () => { const sendMotorNotifications = async () => {
// console.log("🔄 Checking for motor notifications..."); // console.log("🔄 Checking for motor notifications...");

Loading…
Cancel
Save