changes in mqtt

master^2
Varun 8 months ago
parent 887f6858de
commit ab7b00ea13

@ -5887,138 +5887,140 @@ const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT brok
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 data = JSON.parse(message.toString());
const data = JSON.parse(message.toString()); const { hw_Id, Motor_status, tanks } = data.objects;
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) if (!hw_Id) {
const recordsToKeep = 3; console.error('Invalid message format: Missing hw_Id');
const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) // Updated variable name return;
.sort({ date: -1, time: -1 }) }
.skip(recordsToKeep);
for (const record of recordsToDelete) { // Extract device-specific topic
await record.remove(); const expectedTopic = `water/iot-data/${hw_Id}`;
} if (topic !== expectedTopic) {
console.log(`Unexpected topic. Received: ${topic}, Expected: ${expectedTopic}`);
return;
}
// Process each tank to update water level and connections // Get the current date and time in the required format
for (const tank of tanks) { const currentDate = new Date();
const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format const date = currentDate.toISOString(); // ISO string for date
// Find the corresponding tank in the Tank schema using hardwareId and tankhardwareId const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); // Time in 'HH:MM:SS'
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); // Updated variable name
if (!existingTank) continue; // Create array of tank documents with current date and time
const tankDocuments = tanks.map(tank => ({
const customerId = existingTank.customerId; tankhardwareId: tank.Id,
const tank_name = existingTank.tankName; tankHeight: tank.level,
date,
// Calculate water level using tank height and capacity time
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; // Save IoT data
const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); const iotTankData = new IotData({
hardwareId: hw_Id,
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level Motor_status,
tanks: tankDocuments,
// Update water level in the existing tank date,
console.log(tankHeight,"this is located in tank controllers at iot-data mqtt sub ") time
if (tankHeight>0 && waterLevel >= 0) { });
existingTank.waterlevel = waterLevel; await iotTankData.save();
await existingTank.save();
// Delete excess records (keep only the latest three records)
// Update linked tanks (input/output connections) const recordsToKeep = 3;
for (const outputConnection of existingTank.connections.outputConnections) { const recordsToDelete = await IotData.find({ hardwareId: hw_Id })
const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type }); .sort({ date: -1, time: -1 })
if (linkedTank) { .skip(recordsToKeep);
for (const inputConnection of linkedTank.connections.inputConnections) {
if (inputConnection.inputConnections === tank_name) { for (const record of recordsToDelete) {
inputConnection.water_level = waterLevel; // Update water level for linked tank await record.remove();
await linkedTank.save(); // Save updated linked tank }
}
// Process tanks and update water level
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 tank_name = existingTank.tankName;
// Calculate water level using tank height and capacity
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);
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();
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 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) {
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
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) { if (!motorTank) {
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); console.log('Motor not found for the specified motor_id');
inputConnection.motor_stop_status = "1"; return;
inputConnection.motor_on_type = "manual"; }
inputConnection.stopTime = currentTime;
}
await motorTank.save(); // Save the updated tank const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
if (inputConnection) {
inputConnection.motor_status = 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;
} }
console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name 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;
}
} catch (err) { await motorTank.save();
console.error('Error processing message:', err.message);
} }
console.log(`Data 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