changes reverted for testing in mqtt iot-data

master^2
Varun 8 months ago
parent 6b26b74dac
commit 637d4a82cd

@ -1086,10 +1086,7 @@ exports.consumption = async (request, reply) => {
const total_water_added_from_midnight = parseInt(tank.total_water_added_from_midnight.replace(/,/g, ''), 10);
const waterlevel = parseInt(tank.waterlevel.replace(/,/g, ''), 10);
const tankname = tank.tankName;
const capacity = tank.capacity
const capacity = parseInt(tank.capacity.replace(/,/g, ''), 10);
const tankConsumptions = await TankConsumptionOriginalSchema.find({
customerId,
@ -1130,11 +1127,13 @@ exports.consumption = async (request, reply) => {
waterlevel: tank.waterlevel
});
}
const totalConsumptionPercentage = ((totalConsumptionForSelectedBlockAndTypeOfWater / totalCapacityForSelectedBlockAndTypeOfWater) * 100).toFixed(2) ;
// Include the total consumption in the response
const response = {
status_code: 200,
tankData,consumptiorecordsdatewise:tankconsumptionData,
totalConsumptionPercentage:totalConsumptionPercentage,
[`total consumption of ${typeofwater} and selected block`]: totalConsumptionForSelectedBlockAndTypeOfWater
};
@ -4894,54 +4893,211 @@ exports.getBlockData = async (req, reply) => {
const mqtt = require('mqtt');
// const moment = require('moment-timezone');
// const IotData = require('./models/IotData'); // Replace with your actual model
// const Tank = require('./models/Tank'); // Replace with your actual model
// const mqtt = require('mqtt');
// // const moment = require('moment-timezone');
// // const IotData = require('./models/IotData'); // Replace with your actual model
// // const Tank = require('./models/Tank'); // Replace with your actual model
// // A map to keep track of MQTT clients by hw_Id
// const mqttClients = new Map();
// A map to keep track of MQTT clients by hw_Id
const mqttClients = new Map();
// // Function to create a new MQTT client for a specific hw_Id
// function createMqttClient(hw_Id) {
// const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to the MQTT broker
// Function to create a new MQTT client for a specific hw_Id
function createMqttClient(hw_Id) {
const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to the MQTT broker
// client.on('connect', () => {
// console.log(`Client for hw_Id ${hw_Id} connected to MQTT broker`);
// client.subscribe('water/iot-data', (err) => {
// if (err) {
// console.error(`Error subscribing to topic for hw_Id ${hw_Id}:`, err);
// } else {
// console.log(`Client for hw_Id ${hw_Id} subscribed to water/iot-data topic`);
// }
// });
// });
// client.on('message', async (topic, message) => {
// if (topic === 'water/iot-data') {
// try {
// const data = JSON.parse(message.toString());
// const { hw_Id: receivedHwId, Motor_status, tanks } = data.objects;
// // Ensure we process data only for the current client
// if (receivedHwId !== hw_Id) return;
// // Get the current date and time
// 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'
client.on('connect', () => {
console.log(`Client for hw_Id ${hw_Id} connected to MQTT broker`);
// // Create tank documents for the received tanks
// const tankDocuments = tanks.map(tank => ({
// tankhardwareId: tank.Id,
// tankHeight: tank.level,
// date,
// time
// }));
// // Save IoT data
// const iotTankData = new IotData({
// hardwareId: receivedHwId,
// Motor_status,
// tanks: tankDocuments,
// date,
// time
// });
// await iotTankData.save();
// // Delete excess records (keep only the latest three)
// const recordsToKeep = 3;
// const recordsToDelete = await IotData.find({ hardwareId: receivedHwId })
// .sort({ date: -1, time: -1 })
// .skip(recordsToKeep);
// for (const record of recordsToDelete) {
// await record.remove();
// }
// // Process tanks
// for (const tank of tanks) {
// const { Id: tankhardwareId, level: tankHeight } = tank;
// const existingTank = await Tank.findOne({ hardwareId: receivedHwId, tankhardwareId });
// if (!existingTank) continue;
// const customerId = existingTank.customerId;
// const tank_name = existingTank.tankName;
// 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);
// 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
// const status = Motor_status;
// const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": receivedHwId });
// if (motorTank) {
// const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === receivedHwId);
// 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;
// }
// if (inputConnection.motor_stop_status === "2" && status === 1) {
// inputConnection.motor_stop_status = "1";
// }
// await motorTank.save();
// }
// }
// console.log(`Data processed successfully for hw_Id: ${receivedHwId}`);
// } catch (err) {
// console.error(`Error processing message for hw_Id ${hw_Id}:`, err.message);
// }
// }
// });
// return client;
// }
// // Handle incoming MQTT messages for water/iot-data topic
// const mainClient = mqtt.connect('mqtt://35.207.198.4:1883');
// mainClient.on('connect', () => {
// console.log('Main client connected to MQTT broker');
// mainClient.subscribe('water/iot-data', (err) => {
// if (err) {
// console.error('Error subscribing to water/iot-data topic:', err);
// }
// });
// });
// mainClient.on('message', (topic, message) => {
// if (topic === 'water/iot-data') {
// try {
// const data = JSON.parse(message.toString());
// const { hw_Id } = data.objects;
// if (!mqttClients.has(hw_Id)) {
// const client = createMqttClient(hw_Id);
// mqttClients.set(hw_Id, client);
// }
// } catch (err) {
// console.error('Error handling message in main client:', err.message);
// }
// }
// });
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker
client.on('connect', () => {
console.log('Connected to MQTT broker');
client.subscribe('water/iot-data', (err) => {
if (err) {
console.error(`Error subscribing to topic for hw_Id ${hw_Id}:`, err);
console.error('Error subscribing to topic:', err);
} else {
console.log(`Client for hw_Id ${hw_Id} subscribed to water/iot-data topic`);
console.log('Subscribed to water/iot-data topic');
}
});
});
});
// Handling incoming MQTT messages
client.on('message', async (topic, message) => {
console.log(`Message received on topic ${topic}:`, message.toString());
client.on('message', async (topic, message) => {
if (topic === 'water/iot-data') {
try {
const data = JSON.parse(message.toString());
const { hw_Id: receivedHwId, Motor_status, tanks } = data.objects;
// Ensure we process data only for the current client
if (receivedHwId !== hw_Id) return;
const { hw_Id, Motor_status, tanks } = data.objects; // Updated variable names according to new format
// Get the current date and time
// 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 tank documents for the received tanks
// Create array of tank documents with current date and time
const tankDocuments = tanks.map(tank => ({
tankhardwareId: tank.Id,
tankHeight: tank.level,
tankhardwareId: tank.Id, // Updated to match the new format
tankHeight: tank.level, // Updated to match the new format
date,
time
}));
// Save IoT data
// Save IoT data for the received tanks
const iotTankData = new IotData({
hardwareId: receivedHwId,
hardwareId: hw_Id, // Updated variable name
Motor_status,
tanks: tankDocuments,
date,
@ -4949,9 +5105,9 @@ function createMqttClient(hw_Id) {
});
await iotTankData.save();
// Delete excess records (keep only the latest three)
// Delete excess records (keep only the latest three records)
const recordsToKeep = 3;
const recordsToDelete = await IotData.find({ hardwareId: receivedHwId })
const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) // Updated variable name
.sort({ date: -1, time: -1 })
.skip(recordsToKeep);
@ -4959,37 +5115,38 @@ function createMqttClient(hw_Id) {
await record.remove();
}
// Process tanks
// Process each tank to update water level and connections
for (const tank of tanks) {
const { Id: tankhardwareId, level: tankHeight } = tank;
const existingTank = await Tank.findOne({ hardwareId: receivedHwId, tankhardwareId });
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
if (!existingTank) continue;
const customerId = existingTank.customerId;
const tank_name = existingTank.tankName;
const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48;
// 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 waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level
if (tankHeight > 0 && waterLevel >= 0) {
// 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)
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;
await linkedTank.save();
inputConnection.water_level = waterLevel; // Update water level for linked tank
await linkedTank.save(); // Save updated linked tank
}
}
}
@ -4999,12 +5156,17 @@ function createMqttClient(hw_Id) {
// Update motor status
const status = Motor_status;
const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": receivedHwId });
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 === receivedHwId);
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;
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";
@ -5016,43 +5178,13 @@ function createMqttClient(hw_Id) {
inputConnection.motor_stop_status = "1";
}
await motorTank.save();
}
}
console.log(`Data processed successfully for hw_Id: ${receivedHwId}`);
} catch (err) {
console.error(`Error processing message for hw_Id ${hw_Id}:`, err.message);
}
}
});
return client;
}
// Handle incoming MQTT messages for water/iot-data topic
const mainClient = mqtt.connect('mqtt://35.207.198.4:1883');
mainClient.on('connect', () => {
console.log('Main client connected to MQTT broker');
mainClient.subscribe('water/iot-data', (err) => {
if (err) {
console.error('Error subscribing to water/iot-data topic:', err);
await motorTank.save(); // Save the updated tank
}
});
});
mainClient.on('message', (topic, message) => {
if (topic === 'water/iot-data') {
try {
const data = JSON.parse(message.toString());
const { hw_Id } = data.objects;
console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name
if (!mqttClients.has(hw_Id)) {
const client = createMqttClient(hw_Id);
mqttClients.set(hw_Id, client);
}
} catch (err) {
console.error('Error handling message in main client:', err.message);
console.error('Error processing message:', err.message);
}
}
});

Loading…
Cancel
Save