changes in consumption

master^2
Varun 9 months ago
parent 167d04aabb
commit 71592afbd1

@ -1057,6 +1057,7 @@ exports.consumption = async (request, reply) => {
const { startDate, stopDate, block } = request.body;
let { typeofwater } = request.body;
// Convert typeofwater to lowercase
typeofwater = typeofwater.toLowerCase();
const start = moment(startDate, "DD-MMM-YYYY - HH:mm").toDate();
@ -1078,12 +1079,14 @@ exports.consumption = async (request, reply) => {
const tankconsumptionData = [];
// Variable to track total consumption for the selected block and typeofwater
let totalConsumptionForSelectedBlockAndTypeOfWater = 0;
let totalCapacityForSelectedBlockAndTypeOfWater=0;
for (const tank of tanks) {
const waterlevel_at_midnight = parseInt(tank.waterlevel_at_midnight.replace(/,/g, ''), 10);
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
@ -1114,6 +1117,7 @@ exports.consumption = async (request, reply) => {
// Add to the total consumption for the selected block and typeofwater
totalConsumptionForSelectedBlockAndTypeOfWater += consumption;
totalCapacityForSelectedBlockAndTypeOfWater += capacity;
tankData.push({
tankname,
@ -1126,7 +1130,7 @@ exports.consumption = async (request, reply) => {
waterlevel: tank.waterlevel
});
}
// Include the total consumption in the response
const response = {
status_code: 200,
@ -1180,14 +1184,24 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => {
return recordTime >= start && recordTime <= end;
});
filteredConsumptions.forEach(record => {
totalConsumed += parseInt(record.consumption, 10);
totalAvailableCapacity += parseInt(record.available_capacity, 10);
});
// filteredConsumptions.forEach(record => {
// totalConsumed += parseInt(record.consumption, 10);
// totalAvailableCapacity += parseInt(record.capacity, 10);
// });
for (const record of filteredConsumptions) {
const recordTime = moment(record.time, "DD-MMM-YYYY - HH:mm").format("DD-MMM-YYYY - HH:mm");
const tank_info = await Tank.findOne({
customerId:record.customerId,
tankName: record.tankName,
tankLocation: record.tankLocation,
});
totalConsumptionForSelectedBlockAndTypeOfWater+=parseInt(record.consumption, 10);
totalConsumed += parseInt(record.consumption, 10);
;
// console.log( parseInt(tank_info.capacity.replace(/,/g, ''), 10))
totalAvailableCapacity += parseInt(tank_info.capacity.replace(/,/g, ''), 10)
if (!tankconsumptionData[recordTime]) {
tankconsumptionData[recordTime] = {
date: recordTime,
@ -1212,7 +1226,7 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => {
const responseData = Object.values(tankconsumptionData);
const totalConsumptionPercentage = totalAvailableCapacity > 0 ? ((totalConsumed / totalAvailableCapacity) * 100).toFixed(2) : "0";
console.log(totalConsumed,"totalConsumed",totalAvailableCapacity,"totalAvailableCapacity",totalConsumptionForSelectedBlockAndTypeOfWater,"totalConsumptionForSelectedBlockAndTypeOfWater")
const response = {
status_code: 200,
consumptiorecordsdatewise: responseData,
@ -2188,9 +2202,9 @@ const monitorWaterLevels = async () => {
// Call the function to check water levels and send notifications
await checkWaterLevelsAndNotify(customerId, tankName, tankLocation, fcmTokens);
} else {
console.log(`No FCM tokens found for customerId ${tank.customerId}`);
//console.log(`No FCM tokens found for customerId ${tank.customerId}`);
}
}
}
} catch (error) {
console.error('Error monitoring water levels:', error);
}
@ -4842,143 +4856,172 @@ exports.getBlockData = async (req, reply) => {
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:', err);
} else {
console.log('Subscribed to water/iot-data topic');
}
// 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();
// 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`);
}
});
});
});
// Handling 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
// 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();
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'
// 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 records)
const recordsToKeep = 3;
const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) // Updated variable name
.sort({ date: -1, time: -1 })
.skip(recordsToKeep);
// 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();
}
for (const record of recordsToDelete) {
await record.remove();
}
// Process each tank to update water level and connections
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
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 waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 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)
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; // Update water level for linked tank
await linkedTank.save(); // Save updated linked tank
// 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": hw_Id }); // Updated variable name
// 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 (!motorTank) {
console.log('Motor not found for the specified motor_id');
return;
}
if (inputConnection.motor_stop_status === "2" && status === 1) {
inputConnection.motor_stop_status = "1";
}
// 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) {
inputConnection.motor_stop_status = "1";
await motorTank.save();
}
}
await motorTank.save(); // Save the updated tank
console.log(`Data processed successfully for hw_Id: ${receivedHwId}`);
} catch (err) {
console.error(`Error processing message for hw_Id ${hw_Id}:`, err.message);
}
}
});
console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name
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 processing message:', err.message);
console.error('Error handling message in main client:', err.message);
}
}
});
exports.getPendingAndCompletedsurveyOfparticularInstaller = async (request, reply) => {
try {
const { installationId } = request.params;

Loading…
Cancel
Save