changes in mqtt

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

@ -5887,23 +5887,33 @@ 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; // Updated variable names according to new format const { hw_Id, Motor_status, tanks } = data.objects;
if (!hw_Id) {
console.error('Invalid message format: Missing hw_Id');
return;
}
// Extract device-specific topic
const expectedTopic = `water/iot-data/${hw_Id}`;
if (topic !== expectedTopic) {
console.log(`Unexpected topic. Received: ${topic}, Expected: ${expectedTopic}`);
return;
}
// Get the current date and time in the required format // Get the current date and time in the required format
const currentDate = new Date(); const currentDate = new Date();
@ -5912,17 +5922,15 @@ client.on('message', async (topic, message) => {
// Create array of tank documents with current date and time // Create array of tank documents with current date and time
const tankDocuments = tanks.map(tank => ({ const tankDocuments = tanks.map(tank => ({
tankhardwareId: tank.Id, // Updated to match the new format tankhardwareId: tank.Id,
tankHeight: tank.level, // Updated to match the new format tankHeight: tank.level,
date, date,
time time
})); }));
// Save IoT data
// Save IoT data for the received tanks
const iotTankData = new IotData({ const iotTankData = new IotData({
hardwareId: hw_Id, // Updated variable name hardwareId: hw_Id,
Motor_status, Motor_status,
tanks: tankDocuments, tanks: tankDocuments,
date, date,
@ -5932,7 +5940,7 @@ client.on('message', async (topic, message) => {
// Delete excess records (keep only the latest three records) // Delete excess records (keep only the latest three records)
const recordsToKeep = 3; 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 }) .sort({ date: -1, time: -1 })
.skip(recordsToKeep); .skip(recordsToKeep);
@ -5940,38 +5948,35 @@ client.on('message', async (topic, message) => {
await record.remove(); await record.remove();
} }
// Process each tank to update water level and connections // Process tanks and update water level
for (const tank of tanks) { for (const tank of tanks) {
const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format const { Id: tankhardwareId, level: tankHeight } = tank;
// Find the corresponding tank in the Tank schema using hardwareId and tankhardwareId const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); // Updated variable name
if (!existingTank) continue; if (!existingTank) continue;
const customerId = existingTank.customerId; const customerId = existingTank.customerId;
const tank_name = existingTank.tankName; const tank_name = existingTank.tankName;
// Calculate water level using tank height and capacity // Calculate water level using tank height and capacity
const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; // Convert height to cm const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48;
const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); const tank_height = parseInt(tankHeightInCm.toFixed(0), 10);
const waterLevelHeight = tank_height - tankHeight; const waterLevelHeight = tank_height - tankHeight;
const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10);
// Update water level in the existing tank console.log(tankHeight, "this is located in tank controllers at iot-data mqtt sub");
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; existingTank.waterlevel = waterLevel;
await existingTank.save(); await existingTank.save();
// Update linked tanks (input/output connections)
for (const outputConnection of existingTank.connections.outputConnections) { 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) { if (linkedTank) {
for (const inputConnection of linkedTank.connections.inputConnections) { for (const inputConnection of linkedTank.connections.inputConnections) {
if (inputConnection.inputConnections === tank_name) { if (inputConnection.inputConnections === tank_name) {
inputConnection.water_level = waterLevel; // Update water level for linked tank inputConnection.water_level = waterLevel;
await linkedTank.save(); // Save updated linked tank await linkedTank.save();
} }
} }
} }
@ -5981,17 +5986,16 @@ client.on('message', async (topic, message) => {
// 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) { if (!motorTank) {
console.log('Motor not found for the specified motor_id'); console.log('Motor not found for the specified motor_id');
return; return;
} }
// Find the inputConnection for the motor and update motor status const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
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 = status;
if (inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") { 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'); const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
inputConnection.motor_stop_status = "2"; inputConnection.motor_stop_status = "2";
@ -6002,23 +6006,21 @@ client.on('message', async (topic, message) => {
if (inputConnection.motor_stop_status === "2" && status === 1) { if (inputConnection.motor_stop_status === "2" && status === 1) {
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
inputConnection.motor_stop_status = "1"; inputConnection.motor_stop_status = "1";
inputConnection.motor_on_type = "manual";
inputConnection.stopTime = currentTime; inputConnection.stopTime = currentTime;
} }
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) { } catch (err) {
console.error('Error processing message:', err.message); 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