You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1174 lines
45 KiB

//const Tank = require("../models/tanks");
const { Tank, MotorData, IotData } = require('../models/tanks')
const User = require("../models/User");
const boom = require("boom");
const fastify = require("fastify")({
logger: true,
});
// const tanksController = require("./tanksController")
const cron = require('node-cron');
const moment = require('moment');
async function deleteOldRecords() {
const SEVEN_DAYS_IN_MILLISECONDS = 7 * 24 * 60 * 60 * 1000;
const sevenDaysAgo = new Date(Date.now() - SEVEN_DAYS_IN_MILLISECONDS);
await MotorData.deleteMany({ startTime: { $lt: sevenDaysAgo } });
}
exports.addTanks = async (req, reply) => {
try {
var customerId = req.params.customerId
//const username = req.params.username;
console.log(req.params);
//const {username} = loginObject.user.username;
//console.log(loginObject.user.username)
// const userInfo = await User.findOne({ username: username.toString() });
// const updateData = req.body;
// console.log("This is the reply in the handler after the validations", reply);
tankData = {
customerId: customerId,
hardwareId: req.body.hardwareId,
tankName: req.body.tankName,
blockName: req.body.blockName,
capacity: req.body.capacity,
typeOfWater: req.body.typeOfWater,
tankLocation:req.body.tankLocation.toLowerCase(),
};
//console.log( req.body.tankLocation.toLowerCase())
var tank_name = req.body.tankName
var tankLocation = req.body.tankLocation.toLowerCase()
var i_tank = await Tank.findOne({ tankName: tank_name,customerId:customerId,tankLocation:tankLocation})
if(i_tank){
throw new Error('tankname already exists');
}
else {
var tank = new Tank(tankData);
checkFormEncoding = isUserFormUrlEncoded(req);
if (checkFormEncoding.isUserFormUrlEncoded) {
usertobeInserted = checkFormEncoding.tank;
console.log("thsi true url string");
tank.customerId = usertobeInserted.customerId
tank.hardwareId = usertobeInserted.hardwareId;
tank.tankName = usertobeInserted.tankName;
tank.blockName = usertobeInserted.blockName;
tank.capacity = usertobeInserted.capacity;
tank.typeOfWater = usertobeInserted.typeOfWater;
tank.tankLocation = (usertobeInserted.tankLocation).toLowerCase();
console.log((usertobeInserted.tankLocation).toLowerCase())
}
}
const insertedTank = await tank.save();
return insertedTank;
} catch (err) {
throw boom.boomify(err);
}
};
//update selected tank
exports.updateTanksInfo = async (req, reply) => {
try {
3 years ago
var customerId = req.params.customerId;
var tankName = req.query.tankName;
const tank = req.body;
const { ...updateData } = tank;
const update = await Tank.findOneAndUpdate({ tankName: tankName,customerId:customerId, }, updateData, { new: true });
console.log(update.username)
//return update;
reply.send({ status_code: 200, data: update });
}
catch (err) {
throw boom.boomify(err);
}
};
//delete selected tank
exports.deleteTanksInfo = async (req, reply) => {
try {
const customerId = req.params.customerId;
const tankName = req.query.tankName;
const tankLocation = req.body.tankLocation.toLowerCase();
const tank = await Tank.findOneAndDelete({ tankName: tankName,customerId:customerId,tankLocation:tankLocation });
reply.send({ status_code: 200, data: tank});
// return tank;
} catch (err) {
throw boom.boomify(err);
}
};
//get tanks data by passing username
exports.getTank = async (req, reply) => {
try {
3 years ago
await Tank.find({customerId: req.query.customerId})
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
.catch((err) => {
console.log(err);
reply.send({ error: err });
});
} catch (err) {
throw boom.boomify(err);
}
};
//exports.getTanklevels = async (req, reply) => {
// try {
// const customerId = req.params.customerId;
// const tankName = req.query.tankName;
// setInterval(async function () {
// const randomNumber = Math.floor(Math.random() * (5500 - 1000) + 1000);
// console.log(randomNumber)
// console.log( await Tank.findOneAndUpdate({ customerId: customerId, tankName: tankName }, { $set: { waterlevel: randomNumber } }));
// }, 2000);
// return { message: 'Water level will be updated every 2 seconds' };
//}
// catch (err) {
// throw boom.boomify(err);
// }
//};
exports.updateTanklevels = async (req, reply) => {
try {
const customerId = req.params.customerId;
2 years ago
const tanks = await Tank.find({ customerId,tankLocation:"overhead" });
const intervals = {};
for (const tank of tanks) {
const tankId = tank._id;
const tank_name = tank.tankName
let capacity = parseInt(tank.capacity.replace(/,/g, ''), 10);
//let waterLevel = parseInt(tank.waterlevel.replace(/,/g, ''), 10);
const intervalId = setInterval(async function () {
const tank_data = await Tank.findOne({ _id:tankId });
const motorStatus = tank_data.motor_status
let waterLevel = parseInt(tank_data.waterlevel.replace(/,/g, ''), 10);
2 years ago
const newWaterLevel = Math.floor(waterLevel - 150);
console.log("motorstatus:"+motorStatus)
if (newWaterLevel <= 0 ) {
clearInterval(intervals[tankId]);
console.log(`Stopped updating tank with ID ${tankId}`);
return;
}
else{
const result = await Tank.findOneAndUpdate(
{ _id: tankId },
{ $set: { waterlevel: newWaterLevel } }
);
console.log(tank_name+"="+newWaterLevel)
}
// console.log(result);
// waterLevel = newWaterLevel;
}, 5000);
intervals[tankId] = intervalId;
}
return { message: 'Water level updates started' };
} catch (err) {
throw boom.boomify(err);
}
};
exports.getTanklevels = async (req, reply) => {
try {
const customerId = req.params.customerId;
let sumSumpDrinkingWater = 0;
let sumOverheadDrinkingWater = 0;
let sumSumpBoreWater = 0;
let sumOverheadBoreWater = 0;
let sumSumpDrinkingWaterCapacity = 0;
let sumOverheadDrinkingWaterCapacity = 0;
let sumSumpBoreWaterCapacity = 0;
let sumOverheadBoreWaterCapacity = 0;
const updated_data = await Tank.find({ customerId: customerId });
console.log("updated_data", updated_data);
updated_data.forEach((tank) => {
const capacity = parseInt(tank.capacity.replace(/,/g, ''));
if (tank.tankLocation === 'sump' && tank.typeOfWater === 'Drinking Water') {
sumSumpDrinkingWater += parseInt(tank.waterlevel);
sumSumpDrinkingWaterCapacity += capacity;
} else if (tank.tankLocation === 'overhead' && tank.typeOfWater === 'Drinking Water') {
sumOverheadDrinkingWater += parseInt(tank.waterlevel);
sumOverheadDrinkingWaterCapacity += capacity;
} else if (tank.tankLocation === 'sump' && tank.typeOfWater === 'Bore Water') {
sumSumpBoreWater += parseInt(tank.waterlevel);
sumSumpBoreWaterCapacity += capacity;
} else if (tank.tankLocation === 'overhead' && tank.typeOfWater === 'Bore Water') {
sumOverheadBoreWater += parseInt(tank.waterlevel);
sumOverheadBoreWaterCapacity += capacity;
}
});
reply.send({
status_code: 200,
data: updated_data,
totalDrinkingWaterInSump: sumSumpDrinkingWater,
totalDrinkingWaterInOverhead: sumOverheadDrinkingWater,
totalBoreWaterInSump: sumSumpBoreWater,
totalBoreWaterInOverhead: sumOverheadBoreWater,
totalDrinkingWaterInSumpCapacity: sumSumpDrinkingWaterCapacity,
totalDrinkingWaterInOverheadCapacity: sumOverheadDrinkingWaterCapacity,
totalBoreWaterInSumpCapacity: sumSumpBoreWaterCapacity,
totalBoreWaterInOverheadCapacity: sumOverheadBoreWaterCapacity,
});
return { message: 'success' };
} catch (err) {
throw boom.boomify(err);
}
};
const intervals = {};
let sump_water_levels=[];
let supplier_tanks = [];
exports.motorAction = async (req, reply) => {
try {
7
const customerId = req.params.customerId;
const action = req.body.action
const receiver_tank = req.body.to
const receiver_tank_info = await Tank.findOne({ customerId ,tankName:receiver_tank,tankLocation:(req.body.to_type).toLowerCase()});
const receiver_capacity = parseInt((receiver_tank_info.capacity).replace(/,/g, ''), 10)
const desired_water_percentage = parseInt((req.body.percentage).replace(/,/g, ''), 10)
const supplier_tank = req.body.from
const supplier_tank_type = (req.body.from_type).toLowerCase()
const receiver_type = (req.body.to_type).toLowerCase()
// console.log(supplier_tank)
// const suplr_tank_info1 = await Tank.findOne({ customerId ,tankName:supplier_tank,tankLocation:supplier_tank_type});
const interval_variable = supplier_tank+receiver_tank
let currentTank = supplier_tanks.find(tank => tank.supplier_tank === supplier_tank);
let currentSump = sump_water_levels.find(tank => tank.supplier_tank === supplier_tank);
if(action === "start"){
if (!currentTank) {
currentTank = {
supplier_tank: supplier_tank,
start_time: new Date().toLocaleString('en-US', { timeZone: 'Asia/Kolkata' })
};
supplier_tanks.push(currentTank);
}
// start_time = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'})
console.log(supplier_tanks)
// const stop_at = req.body.stop_at
3 years ago
if(supplier_tank_type==="sump" && receiver_type === "overhead"){
await Tank.findOneAndUpdate({customerId, tankName: receiver_tank,tankLocation:receiver_type}, { $set: { motor_status: "1" } });
const supplier_tank_info1 = await Tank.findOne({ customerId ,tankName:supplier_tank,tankLocation:supplier_tank_type});
3 years ago
//console.log(supplier_tank_info1)
//const initial_update = parseInt(supplier_tank_info1.waterlevel.replace(/,/g, ''), 10)-200;
// await Tank.findOneAndUpdate({customerId, tankName: supplier_tank,tankLocation:supplier_tank_type}, { $set: { waterlevel: initial_update } });
const supplier_tank_info = await Tank.findOne({ customerId ,tankName:supplier_tank,tankLocation:supplier_tank_type});
const sump_water_level= parseInt(supplier_tank_info.waterlevel.replace(/,/g, ''), 10)
const receiver_tank_info2 = await Tank.findOne({ customerId ,tankName:receiver_tank,tankLocation:(req.body.to_type).toLowerCase()});
const water_added_from_midnight = parseInt((receiver_tank_info2.total_water_added_from_midnight).replace(/,/g, ''), 10)
if (!currentSump) {
currentSump = {
supplier_tank: supplier_tank,
supplier_initial_waterlevel:sump_water_level,
receiver_tank_total_water_added_from_midnight:water_added_from_midnight
};
sump_water_levels.push(currentSump);
}
console.log(sump_water_levels)
const overheadTank = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
const connection = overheadTank.connections.inputConnections.find((conn) => conn.inputConnections === supplier_tank);
if (connection) {
connection.motor_status = "1";
await overheadTank.save();
}
// await changingfrom_tankwaterlevel(customerId,initial_update,supplier_tank_info);
// let supplier_waterlevel = parseInt(supplier_tank_info.waterlevel.replace(/,/g, ''), 10)
3 years ago
// console.log(supplier_waterlevel)
// let receiver_waterlevel = parseInt(receiver_tank_info.waterlevel.replace(/,/g, ''), 10)
intervals[interval_variable] = setInterval(async function () {
// Calculate new water levels
3 years ago
const supplier_tank_info2 = await Tank.findOne({ customerId ,tankName:supplier_tank,tankLocation:supplier_tank_type});
const rcvr_info = await Tank.findOne({ customerId ,tankName:receiver_tank,tankLocation:receiver_type});
let receiver_waterlevel = parseInt(rcvr_info.waterlevel.replace(/,/g, ''), 10)
let supplier_waterlevel = parseInt(supplier_tank_info2.waterlevel.replace(/,/g, ''), 10)
const newWaterLevel = receiver_waterlevel + 250//Math.floor(supplier_waterlevel * 0.1);
const newSupplierWaterLevel = supplier_waterlevel-250//Math.floor(supplier_waterlevel * 0.1);
const supplier_capacity = parseInt(supplier_tank_info.capacity.replace(/,/g, ''), 10)
3 years ago
console.log((newSupplierWaterLevel/supplier_capacity)*100)
// Check if updating should stop
if ((newSupplierWaterLevel/supplier_capacity)*100 <= 5 || (newWaterLevel/receiver_capacity)*100 >= 95 || (newWaterLevel/receiver_capacity)*100 >= desired_water_percentage || rcvr_info.motor_status === "0") {
console.log((newSupplierWaterLevel/supplier_capacity)*100,(newWaterLevel/receiver_capacity)*100,(newWaterLevel/receiver_capacity)*100,)
clearInterval(intervals[interval_variable]); // Clear the interval for this tank
delete intervals[interval_variable];
const overheadTank = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
const connection = overheadTank.connections.inputConnections.find((conn) => conn.inputConnections === supplier_tank);
if (connection) {
connection.motor_status = "0";
await overheadTank.save();
}
// Find the tank based on customerId, tankName, and tankLocation
const tankToUpdate = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
// Check if all objects in inputConnections have motor_status === "0"
const allMotorStatusZero = tankToUpdate.connections.inputConnections.every(connection => connection.motor_status === "0");
if (allMotorStatusZero) {
// Update the motor_status field to "0" for the tank
await Tank.findOneAndUpdate(
{ customerId, tankName: receiver_tank, tankLocation: receiver_type },
{ $set: { motor_status: "0" } }
);
}
console.log("end for"+receiver_tank);
} else {
// Update water levels in database
3 years ago
//supplier_waterlevel = newSupplierWaterLevel;
// receiver_waterlevel = newWaterLevel;
console.log((newSupplierWaterLevel/supplier_capacity)*100)
3 years ago
// console.log((newWaterLevel/receiver_capacity)*100)
console.log(newWaterLevel+""+receiver_type)
console.log(newSupplierWaterLevel+""+supplier_tank)
3 years ago
await Tank.findOneAndUpdate({customerId, tankName: receiver_tank,tankLocation:receiver_type}, { $set: { waterlevel: newWaterLevel } })
await Tank.findOneAndUpdate({customerId, tankName: supplier_tank,tankLocation:supplier_tank_type}, { $set: { waterlevel: newSupplierWaterLevel } })
//if (supplier_tank_info2.motor_status==="0"){
// await Tank.findOneAndUpdate({customerId, tankName: supplier_tank,tankLocation:supplier_tank_type}, { $set: { waterlevel: supplier_waterlevel } })
// }
3 years ago
}
}, 2000);
}
// if(supplier_tank_type==="sump" && receiver_type === "sump"){
// await Tank.findOneAndUpdate({customerId, tankName: receiver_tank,tankLocation:receiver_type}, { $set: { motor_status: 1 } });
// // console.log(rcvr_info.motor_status)
// // const supplier_tank_info1 = await Tank.findOne({ customerId ,tankName:supplier_tank});
// // initial_update = parseInt(supplier_tank_info1.capacity.replace(/,/g, ''), 10)/2;
// // await Tank.findOneAndUpdate({customerId, tankName: supplier_tank}, { $set: { waterlevel: initial_update } });
// const supplier_tank_info = await Tank.findOne({ customerId ,tankName:supplier_tank,tankLocation:supplier_tank_type});
// let supplier_waterlevel = parseInt(supplier_tank_info.waterlevel.replace(/,/g, ''), 10)
// let receiver_waterlevel = parseInt(receiver_tank_info.waterlevel.replace(/,/g, ''), 10)
// intervals[interval_variable] = setInterval(async function () {
// const rcvr_info = await Tank.findOne({ customerId ,tankName:receiver_tank,tankLocation:receiver_type});
// const supplier_capacity = parseInt(supplier_tank_info.capacity.replace(/,/g, ''), 10)
// // Calculate new water levels
// const newWaterLevel = receiver_waterlevel + 200//Math.floor(supplier_waterlevel * 0.1);
// const newSupplierWaterLevel = Math.min(supplier_capacity, supplier_waterlevel - 200);// Math.floor(supplier_waterlevel * 0.15));
// // console.log(newWaterLevel)
// // console.log(newSupplierWaterLevel)
// // console.log(rcvr_info.motor_status)
// // console.log(rcvr_info.tankName)
// // Check if updating should stop
// if ( (newWaterLevel/receiver_capacity)*100 >= 95 || (newWaterLevel/receiver_capacity)*100 >= desired_water_percentage || rcvr_info.motor_status === 0 || (newSupplierWaterLevel/supplier_capacity)*100 <= 5) {
// clearInterval(interval_variable)
// delete intervals[interval_variable];
// await Tank.findOneAndUpdate({customerId, tankName: receiver_tank,tankLocation:receiver_type}, { $set: { motor_status: 0 } });
// console.log("end");
// } else {
// // Update water levels in database
// supplier_waterlevel = newSupplierWaterLevel;
// receiver_waterlevel = newWaterLevel;
// console.log(supplier_waterlevel,"0")
// console.log(receiver_waterlevel,"1")
// // console.log((newSupplierWaterLevel/supplier_capacity)*100)
// // console.log((newWaterLevel/receiver_capacity)*100)
// await Promise.all([
// Tank.findOneAndUpdate({customerId, tankName: receiver_tank}, { $set: { waterlevel: newWaterLevel } }),
// Tank.findOneAndUpdate({customerId, tankName: supplier_tank}, { $set: { waterlevel: newSupplierWaterLevel } })
// ]);
// }
// }, 2000);
// }
if(supplier_tank_type==="sump" && receiver_type === "sump"){
const receiver_capacity = parseInt(receiver_tank_info.capacity.replace(/,/g, ''), 10)
const sumpTank = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
const connection = sumpTank.connections.inputConnections.find((conn) => conn.inputConnections === supplier_tank);
if (connection) {
connection.motor_status = "1";
await sumpTank.save();
}
// console.log(receiver_capacity,"0",receiver_tank_info.tankName)
await Tank.findOneAndUpdate({customerId, tankName: receiver_tank,tankLocation:receiver_type}, { $set: { motor_status: "1" } });
const supplier_tank_info = await Tank.findOne({ customerId ,tankName:supplier_tank,tankLocation:supplier_tank_type});
// let supplier_waterlevel = parseInt(supplier_tank_info.waterlevel.replace(/,/g, ''), 10)
// let receiver_waterlevel = parseInt(receiver_tank_info.waterlevel.replace(/,/g, ''), 10)
// console.log(receiver_waterlevel,"1")
intervals[interval_variable] = setInterval(async function () {
// Calculate new water levels
const splr_tank_info = await Tank.findOne({ customerId ,tankName:supplier_tank,tankLocation:supplier_tank_type});
const rcvr_info = await Tank.findOne({ customerId ,tankName:receiver_tank,tankLocation:receiver_type});
const supplier_capacity = parseInt(supplier_tank_info.capacity.replace(/,/g, ''), 10)
let supplier_waterlevel = parseInt(splr_tank_info.waterlevel.replace(/,/g, ''), 10)
let receiver_waterlevel = parseInt(rcvr_info.waterlevel.replace(/,/g, ''), 10)
// Calculate new water levels
const newWaterLevel = receiver_waterlevel + 250//Math.floor(supplier_waterlevel * 0.1);
const newSupplierWaterLevel = Math.min(supplier_capacity, supplier_waterlevel - 250);// Math.floor(supplier_waterlevel * 0.15));
// Check if updating should stop
if ((newWaterLevel/receiver_capacity)*100 >= 97 || (newWaterLevel/receiver_capacity)*100 >= desired_water_percentage || rcvr_info.motor_status === "0" || (newSupplierWaterLevel/supplier_capacity)*100 <= 5 ) {
clearInterval(intervals[interval_variable]); // Clear the interval for this tank
delete intervals[interval_variable];
const sumpTank = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
const connection = sumpTank.connections.inputConnections.find((conn) => conn.inputConnections === supplier_tank);
if (connection) {
connection.motor_status = "0";
await sumpTank.save();
}
}
const tankToUpdate = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
// Check if all objects in inputConnections have motor_status === "0"
const allMotorStatusZero = tankToUpdate.connections.inputConnections.every(connection => connection.motor_status === "0");
if (allMotorStatusZero) {
// Update the motor_status field to "0" for the tank
await Tank.findOneAndUpdate(
{ customerId, tankName: receiver_tank, tankLocation: receiver_type },
{ $set: { motor_status: "0" } }
);
console.log("end for" + receiver_tank);
} else {
// Update water levels in database
// supplier_waterlevel = newSupplierWaterLevel;
// receiver_waterlevel = newWaterLevel;
console.log(supplier_waterlevel,"0")
console.log(receiver_waterlevel,"1")
// console.log((newSupplierWaterLevel/supplier_capacity)*100)
// console.log((newWaterLevel/receiver_capacity)*100)
await Promise.all([
Tank.findOneAndUpdate({customerId, tankName: receiver_tank}, { $set: { waterlevel: newWaterLevel } }),
Tank.findOneAndUpdate({customerId, tankName: supplier_tank}, { $set: { waterlevel: newSupplierWaterLevel } })
]);
}
}, 2000);
}
if(supplier_tank_type==="bore" && receiver_type === "sump"){
const receiver_capacity = parseInt(receiver_tank_info.capacity.replace(/,/g, ''), 10)
3 years ago
// console.log(receiver_capacity,"0",receiver_tank_info.tankName)
await Tank.findOneAndUpdate({customerId, tankName: receiver_tank,tankLocation:receiver_type}, { $set: { motor_status: "1" } });
const sumpTank = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
const connection = sumpTank.connections.inputConnections.find((conn) => conn.inputConnections === supplier_tank);
if (connection) {
connection.motor_status = "1";
await sumpTank.save();
}
// let receiver_waterlevel = parseInt(receiver_tank_info.waterlevel.replace(/,/g, ''), 10)
3 years ago
// console.log(receiver_waterlevel,"1")
intervals[interval_variable] = setInterval(async function () {
// Calculate new water levels
const rcvr_info = await Tank.findOne({ customerId ,tankName:receiver_tank,tankLocation:receiver_type});
3 years ago
//console.log(rcvr_info)
let receiver_waterlevel = parseInt(rcvr_info.waterlevel.replace(/,/g, ''), 10)
3 years ago
//console.log(rcvr_info.motor_status)
const newWaterLevel = receiver_waterlevel+250;
3 years ago
//console.log(newWaterLevel,"2",receiver_tank_info.tankName)
// Check if updating should stop
if ((newWaterLevel/receiver_capacity)*100 >= 97 || (newWaterLevel/receiver_capacity)*100 >= desired_water_percentage || rcvr_info.motor_status === "0" ) {
clearInterval(intervals[interval_variable]); // Clear the interval for this tank
delete intervals[interval_variable];
const sumpTank = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
const connection = sumpTank.connections.inputConnections.find((conn) => conn.inputConnections === supplier_tank);
if (connection) {
connection.motor_status = "0";
await sumpTank.save();
}
const tankToUpdate = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
// Check if all objects in inputConnections have motor_status === "0"
const allMotorStatusZero = tankToUpdate.connections.inputConnections.every(connection => connection.motor_status === "0");
if (allMotorStatusZero) {
// Update the motor_status field to "0" for the tank
await Tank.findOneAndUpdate(
{ customerId, tankName: receiver_tank, tankLocation: receiver_type },
{ $set: { motor_status: "0" } }
);
}
console.log("end for" + receiver_tank);
} else {
// Update water levels in database
// receiver_waterlevel = newWaterLevel;
3 years ago
//console.log((newWaterLevel/receiver_capacity)*100,"4",receiver_tank_info.tankName)
await Tank.findOneAndUpdate({customerId, tankName: receiver_tank,tankLocation:receiver_type}, { $set: { waterlevel: newWaterLevel } })
console.log(receiver_tank+"="+newWaterLevel+"="+"bore to sump")
}
}, 2000);
}
3 years ago
// console.log(customerId,req.body.from,req.body.from_type,receiver_tank,req.body.to_type,)
}
else if (action === "stop") {
//stop_time = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'})
clearInterval(intervals[interval_variable]); // Clear the interval for this tank
delete intervals[interval_variable];
const stopTime = new Date().toLocaleString('en-US', { timeZone: 'Asia/Kolkata' });
// console.log(currentTank.start_time)
const startTime = currentTank.start_time;
// const duration = calculateDuration(startTime, stopTime);
// Store the duration or perform any required operations
supplier_tanks = supplier_tanks.filter(tank => tank.supplier_tank !== supplier_tank);
// console.log(supplier_tanks)
// storing data of how amny water supplied from sump to overhead to calculate the consumption
const suplr_tank_info2 = await Tank.findOne({ customerId ,tankName:supplier_tank,tankLocation:supplier_tank_type});
let water_added_from_midnight1=0
if (supplier_tank_type === "sump") {
// const rcvr_info2 = await Tank.findOne({ customerId ,tankName:receiver_tank,tankLocation:receiver_type});
console.log(currentSump.receiver_tank_total_water_added_from_midnight,"5")
water_added_from_midnight1=currentSump.receiver_tank_total_water_added_from_midnight
console.log(water_added_from_midnight1)
}
const sump_water_level1 =currentSump.supplier_initial_waterlevel
console.log(sump_water_level1,"1")
// console.log(water_added_from_midnight)
const sump_final_water_level= parseInt(suplr_tank_info2.waterlevel.replace(/,/g, ''), 10)
console.log(sump_final_water_level,"2")
sump_water_levels = sump_water_levels.filter(tank => tank.supplier_tank !== supplier_tank);
const quantity_delivered = sump_water_level1-sump_final_water_level
if (supplier_tank_type === "sump") {
final_added_water=water_added_from_midnight1+quantity_delivered
await Tank.findOneAndUpdate({customerId, tankName: receiver_tank,tankLocation:receiver_type}, { $set: { total_water_added_from_midnight: final_added_water } })
}
const overheadTank = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
const connection = overheadTank.connections.inputConnections.find((conn) => conn.inputConnections === supplier_tank);
if (connection) {
connection.motor_status = "0";
await overheadTank.save();
}
const tankToUpdate = await Tank.findOne({ customerId, tankName: receiver_tank, tankLocation: receiver_type });
// Check if all objects in inputConnections have motor_status === "0"
const allMotorStatusZero = tankToUpdate.connections.inputConnections.every(connection => connection.motor_status === "0");
if (allMotorStatusZero) {
console.log(allMotorStatusZero)
// Update the motor_status field to "0" for the tank
await Tank.findOneAndUpdate(
{ customerId, tankName: receiver_tank, tankLocation: receiver_type },
{ $set: { motor_status: "0" } }
);
}
//saving the motor run time and data
motorData = {
customerId:customerId,
supplierTank : supplier_tank,
supplier_type: supplier_tank_type,
receiverTank: receiver_tank,
receiver_type: receiver_type,
startTime: startTime,
stopTime: stopTime,
quantity_delivered:quantity_delivered
};
var motorData = new MotorData(motorData);
checkFormEncoding = isUserFormUrlEncoded(req);
if (checkFormEncoding.isUserFormUrlEncoded) {
usertobeInserted = checkFormEncoding.motorData;
console.log("thsi true url string");
motorData.customerId = customerId;
motorData.supplierTank = supplierTank;
motorData.receiverTank = receiver_tank;
motorData.supplier_type = supplier_type;
motorData.receiver_type = receiver_type;
motorData.startTime = startTime;
motorData.stopTime = stopTime;
motorData.quantity_delivered = quantity_delivered;
}
const motor_data = await motorData.save();
console.log(motor_data)
// reply.send({ status_code: 200, data: motor_data });
// reply.send({ status_code: 200, "start time": start_time, data: motor_data});
// console.log(start_time)
// return motor_data
// console.log(stop_time)
// clearInterval(intervalId);
// await Tank.findOneAndUpdate({customerId, tankName: receiver_tank,tankLocation:(req.body.to_type).toLowerCase()}, { $set: { motor_status: "0" } });
reply.send({ status_code: 200, "stop time": stopTime,data: motor_data});
} else {
throw new Error("Invalid action");
}
return { message: 'Water level updates started' };
} catch (err) {
throw new Error(`Failed to start/stop water level updates: ${err.message}`);
};
};
exports.consumption = async (req, reply) => {
try {
const customerId = req.params.customerId;
const tanks = await Tank.find({ customerId });
const tankData = [];
for (const tank of tanks) {
const tankId = tank._id;
let capacity = parseInt(tank.capacity.replace(/,/g, ''), 10);
let waterLevel = capacity*2+1700; // initial water level
const tankname = tank.tankName
const newWaterLevel = Math.floor(waterLevel);
tankData.push({ tankname, waterLevel: newWaterLevel });
// console.log(newWaterLevel);
}
reply.send({ status_code: 200, tankData });
return { message: 'Water level updates started' };
} catch (err) {
throw boom.boomify(err);
}
};
// exports.calculateCapacity = async (req, reply) => {
// try {
// const shape = req.body.shape
// if(shape==="rectangle"){
// const { length, width, height } = req.body
// // Ensure all parameters are valid numbers
// if (isNaN(length) || isNaN(width) || isNaN(height)) {
// reply.code(400).send('Invalid input parameters')
// return
// }
// // Calculate the capacity of the water tank in liters
// const capacity = length * width * height * 1000
// reply.send({ status_code: 200, capacity: capacity});
// return { message: 'success' };
// }
// if(shape==="cylinder"){
// console.log("hii1")
// const { length,diameter } = req.body
// // Ensure all parameters are valid numbers
// if (isNaN(length) || isNaN(diameter)) {
// reply.code(400).send('Invalid input parameters')
// return
// }
// // Calculate the capacity of the water tank in liters
// const radius = diameter / 2
// const volume = Math.PI * Math.pow(radius, 2) * length
// const capacity = volume * 1000
// reply.send({ status_code: 200, capacity: capacity});
// return { message: 'success' };
// }
// // if(shape==="oval"){
// // console.log("hii3")
// // const { length, width, height } = req.body
// // // Ensure all parameters are valid numbers
// // if (isNaN(length) || isNaN(width) || isNaN(height)) {
// // reply.code(400).send('Invalid input parameters')
// // return
// // }
// // // Calculate the capacity of the water tank in liters
// // const radius = height / 2
// // const a = width - height
// // const area = Math.PI * radius * radius + 2 * radius * a
// // const volume = area * length
// // const capacity = volume * 1000
// // // Format the result with two decimal places and comma-separated thousands
// // const formattedCapacity = capacity.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
// // reply.send({ status_code: 200, capacity: formattedCapacity});
// // return { message: 'success' };
// // }
// // if(shape==="horizontalellipse"){
// // const { length, width, height } = req.body
// // // Ensure all parameters are valid numbers
// // if (isNaN(length) || isNaN(width) || isNaN(height)) {
// // reply.code(400).send('Invalid input parameters')
// // return
// // }
// // // Calculate the capacity of the water tank in liters
// // const radius1 = length / 2
// // const radius2 = width / 2
// // const volume = Math.PI * radius1 * radius2 * height
// // const capacity = volume * 1000
// // reply.send({ status_code: 200, capacity: capacity});
// // return { message: 'success' };
// // }
// if(shape==="userdefined"){
// const capacity = req.body
// reply.send({ status_code: 200, capacity: capacity});
// return { message: 'success' };
// }
// }
// catch (err) {
// throw boom.boomify(err);
// }
// };
exports.calculateCapacity = async (req, reply) => {
try {
const shape = req.body.shape;
if (shape === "rectangle") {
const { length, width, height } = req.body;
// Convert input units from feet to meters
const length_m = length * 0.3048;
const width_m = width * 0.3048;
const height_m = height * 0.3048;
console.log(length_m,width_m,height_m)
// Ensure all parameters are valid numbers
if (isNaN(length_m) || isNaN(width_m) || isNaN(height_m)) {
reply.code(400).send("Invalid input parameters");
return;
}
// Calculate the capacity of the water tank in liters
const capacity = length_m * width_m * height_m * 1000;
reply.send({ status_code: 200, capacity: capacity });
return { message: "success" };
}
if (shape === "cylinder") {
console.log("hii1");
const { length, diameter } = req.body;
// Convert input units from feet to meters
const length_m = length * 0.3048;
const diameter_m = diameter * 0.3048;
// Ensure all parameters are valid numbers
if (isNaN(length_m) || isNaN(diameter_m)) {
reply.code(400).send("Invalid input parameters");
return;
}
// Calculate the capacity of the water tank in liters
const radius = diameter_m / 2;
const volume = Math.PI * Math.pow(radius, 2) * length_m;
const capacity = volume * 1000;
reply.send({ status_code: 200, capacity: capacity });
return { message: "success" };
}
// Add similar conversions for other shapes if necessary
if (shape === "userdefined") {
const capacity = req.body;
reply.send({ status_code: 200, capacity: capacity });
return { message: "success" };
}
} catch (err) {
throw boom.boomify(err);
}
};
exports.IotDevice = async (req, reply) => {
try {
const { hardwareId, tankHeight, maxLevel, minLevel, mode } = req.body;
// create a new tank document with the current date and time
const currentDate = new Date();
const date = currentDate.toISOString(); // save the date as an ISO string
const time = currentDate.toLocaleTimeString('en-IN', {hour12:false, timeZone: 'Asia/Kolkata' });
const tank = new IotData({ hardwareId, tankHeight, maxLevel, minLevel, mode, date, time });
// save the document to MongoDB
await tank.save();
// get all the tank documents for the current hardwareId sorted in descending order of date and time
const tanks = await IotData.find({ hardwareId }).sort({ date: -1, time: -1 });
// if the number of documents for the current hardwareId is greater than three, remove the oldest documents until there are only three left
if (tanks.length > 3) {
const oldestDocuments = tanks.slice(3);
for (const doc of oldestDocuments) {
await IotData.deleteOne({ _id: doc._id });
}
}
// get the latest three tank documents for the current hardwareId sorted in descending order of date and time
const latestTanks = await IotData.find({ hardwareId }).sort({ date: -1, time: -1 }).limit(3);
// send the latest three documents in descending order of date and time
reply.code(200).send({ latestTanks: latestTanks.reverse() });
} catch (err) {
// send an error response
reply.code(500).send({ error: err.message });
}
};
exports.getIotD = async(req, reply) => {
try {
await IotData.find({hardwareId: req.query.hardwareId})
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
.catch((err) => {
console.log(err);
reply.send({ error: err });
});
} catch (err) {
throw boom.boomify(err);
}
}
exports.getLatestData = async (req, reply) => {
try {
const hardwareId = req.params.hardwareId;
// get the latest two tank documents for the current hardwareId sorted in descending order of date and time
const latestTanks = await IotData.find({ hardwareId }).sort({ date: -1, time: -1 }).limit(2);
// if the number of documents for the current hardwareId is less than two, return an error response
if (latestTanks.length < 2) {
return reply.code(404).send({ error: 'Not enough data' });
}
// calculate the time difference between the latest and previous documents
const latestDate = new Date(latestTanks[0].date);
const previousDate = new Date(latestTanks[1].date);
const latestTime = latestTanks[0].time.split('.')[0]; // remove milliseconds
const previousTime = latestTanks[1].time.split('.')[0]; // remove milliseconds
latestDate.setHours(parseInt(latestTime.substring(0, 2)), parseInt(latestTime.substring(3, 5)), parseInt(latestTime.substring(6, 8)));
previousDate.setHours(parseInt(previousTime.substring(0, 2)), parseInt(previousTime.substring(3, 5)), parseInt(previousTime.substring(6, 8)));
const timeDiff = (latestDate.getTime() - previousDate.getTime()) / 1000; // convert from milliseconds to seconds
console.log(latestDate,previousDate,latestTime,previousTime,timeDiff)
reply.code(200).send({ timeDiff });
} catch (err) {
// send an error response
reply.code(500).send({ error: err.message });
}
};
exports.checkStatusofIot = async (req, reply) => {
try {
// get a list of unique hardware IDs in the collection
const hardwareIds = await IotData.distinct('hardwareId');
// create an empty object to store the time differences for each hardware ID
const timeDiffs = {};
// loop over each hardware ID and calculate the time difference between the latest two records
for (const hardwareId of hardwareIds) {
// get the latest two records for the current hardware ID
const latestTanks = await IotData.find({ hardwareId }).sort({ date: -1, time: -1 }).limit(2);
// if the number of records for the current hardware ID is less than two, skip to the next ID
if (latestTanks.length < 2) {
continue;
}
// calculate the time difference between the latest and previous records for the current hardware ID
const latestDate = new Date(latestTanks[0].date);
const previousDate = new Date(latestTanks[1].date);
const latestTime = latestTanks[0].time.split('.')[0]; // remove milliseconds
const previousTime = latestTanks[1].time.split('.')[0]; // remove milliseconds
latestDate.setHours(parseInt(latestTime.substring(0, 2)), parseInt(latestTime.substring(3, 5)), parseInt(latestTime.substring(6, 8)));
previousDate.setHours(parseInt(previousTime.substring(0, 2)), parseInt(previousTime.substring(3, 5)), parseInt(previousTime.substring(6, 8)));
const timeDiff = (latestDate.getTime() - previousDate.getTime()) / 1000; // convert from milliseconds to seconds
// store the time difference for the current hardware ID
timeDiffs[hardwareId] = timeDiff;
}
// send the time differences for all hardware IDs
reply.code(200).send({ timeDiffs });
} catch (err) {
// send an error response
reply.code(500).send({ error: err.message });
}
};
exports.totalwaterLevelSum = async (request, reply) => {
const { tankLocation, typeOfWater } = request.query;
const waterlevelSum = await Tank.aggregate([
{
$match: { tankLocation, typeOfWater }
},
{
$group: {
_id: null,
totalWaterlevel: { $sum: { $toInt: '$waterlevel' } }
}
}
]);
const result = waterlevelSum[0]?.totalWaterlevel ?? 0;
reply.send({ waterlevelSum: result });
}
exports.startUpdateLoop = async (request, reply) => {
const updateInterval = 5000;
setInterval(async () => {
try {
const iotTank = await IotData.findOne({ hardwareId: request.body.hardwareId });
if (!iotTank) {
console.log(`IOTtank not found for hardwareId ${request.body.hardwareId}`);
return;
}
const currentWaterlevel = Number(iotTank.tankHeight) * 200;
const tank = await Tank.findOne({ hardwareId: iotTank.hardwareId });
let combinedWaterlevel;
if (tank) {
combinedWaterlevel = currentWaterlevel + Number(tank.waterlevel);
} else {
combinedWaterlevel = currentWaterlevel;
}
await Tank.updateOne({ hardwareId: iotTank.hardwareId }, { $set: { waterlevel: combinedWaterlevel } });
console.log(`Waterlevel updated successfully for hardwareId ${iotTank.hardwareId}`);
console.log(`Previous waterlevel: ${tank ? tank.waterlevel : 0}`);
console.log(`Current waterlevel: ${currentWaterlevel}`);
console.log(`Combined waterlevel: ${combinedWaterlevel}`);
} catch (err) {
console.error(err);
}
}, updateInterval);
};
exports.updatewaterlevelsatmidnight = async (req, reply) => {
try {
// Schedule the task to run every day at 10 seconds past the minute
cron.schedule('0 0 * * *', async () => {
try {
const tanks = await Tank.find({ customerId: req.query.customerId });
for (const tank of tanks) {
tank.waterlevel_at_midnight = tank.waterlevel;
console.log(tank.waterlevel_at_midnight)
await tank.save();
}
console.log('Waterlevel noted in waterlevel_at_midnight');
} catch (error) {
console.error('Error occurred:', error);
}
});
await Tank.find({ customerId: req.query.customerId })
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
.catch((err) => {
console.log(err);
reply.send({ error: err });
});
} catch (err) {
throw boom.boomify(err);
}
};
exports.deletemotordatarecordsbefore7days = async (req, reply) => {
try {
// Schedule the task to run every day at 10 seconds past the minute
cron.schedule('0 0 * * *', async () => {
try {
// Run the deletion task once a day
setInterval(async () => {
await deleteOldRecords();
}, 24 * 60 * 60 * 1000); // 24 hours in milliseconds
} catch (error) {
console.error('Error occurred:', error);
}
});
} catch (err) {
throw boom.boomify(err);
}
};