saving motor data

master
varun 1 year ago
parent 4856e74bf0
commit 9dc7a94c4d

@ -825,55 +825,56 @@ let supplier_tanks = [];
exports.consumption = async (request, reply) => { exports.consumption = async (request, reply) => {
// try { try {
// const customerId = req.params.customerId; const customerId = req.params.customerId;
// const tanks = await Tank.find({ customerId,tankLocation:"overhead"}); const tanks = await Tank.find({ customerId,tankLocation:"overhead"});
// const tankData = []; const tankData = [];
// for (const tank of tanks) { for (const tank of tanks) {
// const tankId = tank._id; const tankId = tank._id;
// const waterlevel_at_midnight = parseInt(tank.waterlevel_at_midnight.replace(/,/g, ''), 10); 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 total_water_added_from_midnight = parseInt(tank.total_water_added_from_midnight.replace(/,/g, ''), 10);
// const waterlevel = parseInt(tank.waterlevel.replace(/,/g, ''), 10); const waterlevel = parseInt(tank.waterlevel.replace(/,/g, ''), 10);
// const tankname = tank.tankName const tankname = tank.tankName
// const consumption = (waterlevel_at_midnight+total_water_added_from_midnight)-waterlevel const consumption = (waterlevel_at_midnight+total_water_added_from_midnight)-waterlevel
// const newWaterLevel1 = Math.floor(consumption); const newWaterLevel1 = Math.floor(consumption);
// const newWaterLevel=Math.abs(newWaterLevel1) const newWaterLevel=Math.abs(newWaterLevel1)
// tankData.push({ tankname, waterLevel: newWaterLevel }); tankData.push({ tankname, waterLevel: newWaterLevel });
// // console.log(newWaterLevel); // console.log(newWaterLevel);
// } }
// reply.send({ status_code: 200, tankData }); reply.send({ status_code: 200, tankData });
// return { message: 'Water level updates started' }; return { message: 'Water level updates started' };
// } catch (err) { } catch (err) {
// throw boom.boomify(err); throw boom.boomify(err);
// } }
try { // try {
const { customerId } = request.params; // const { customerId } = request.params;
const tank = await Tank.find({ customerId, tankLocation:"overhead" }); // const tank = await Tank.find({ customerId, tankLocation:"overhead" });
if (!tank) { // if (!tank) {
return reply.status(404).send({ error: 'Tank not found' }); // return reply.status(404).send({ error: 'Tank not found' });
} // }
// Here you can process and return the consumption data as needed // // Here you can process and return the consumption data as needed
return reply.send(tank); // return reply.send(tank);
} catch (error) { // } catch (error) {
request.log.error(error); // request.log.error(error);
return reply.status(500).send({ error: 'Internal Server Error' }); // return reply.status(500).send({ error: 'Internal Server Error' });
} // }
}; };
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
//const moment = require('moment'); // Import moment.js for date/time operations //const moment = require('moment'); // Import moment.js for date/time operations
@ -882,6 +883,7 @@ exports.motorAction = async (req, reply) => {
const customerId = req.params.customerId; const customerId = req.params.customerId;
const action = req.body.action; const action = req.body.action;
const motorId = req.body.motor_id; const motorId = req.body.motor_id;
const start_instance_id = req.body.start_instance_id
console.log(req.body.startTime) console.log(req.body.startTime)
// Ensure motor_id is provided // Ensure motor_id is provided
if (!motorId) { if (!motorId) {
@ -913,6 +915,30 @@ exports.motorAction = async (req, reply) => {
} }
); );
await delay(300000);
// Update the existing motor data entry with stop details
const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id });
if (motorData) {
const receiverTank = await Tank.findOne({ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() });
const receiverFinalWaterLevel = parseInt(receiverTank.waterlevel, 10);
const quantityDelivered = receiverFinalWaterLevel - parseInt(motorData.receiverInitialwaterlevel, 10);
const water_pumped_till_now = parseInt(receiverTank.total_water_added_from_midnight, 10);
const totalwaterpumped = quantityDelivered + water_pumped_till_now
await Tank.findOneAndUpdate({customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase()}, { $set: { total_water_added_from_midnight: totalwaterpumped } })
await MotorData.updateOne(
{ customerId, motor_id: motorId, start_instance_id: start_instance_id },
{
$set: {
stopTime: req.body.stopTime,
receiverfinalwaterlevel: receiverFinalWaterLevel.toString(),
quantity_delivered: quantityDelivered.toString()
}
}
);
}
} else { } else {
@ -931,14 +957,27 @@ exports.motorAction = async (req, reply) => {
// { customerId, "connections.inputConnections.motor_id": motorId }, // { customerId, "connections.inputConnections.motor_id": motorId },
// { $set: { "connections.inputConnections.$.manual_threshold_time": req.body.manual_threshold_time,startTime:req.body.startTime } } // { $set: { "connections.inputConnections.$.manual_threshold_time": req.body.manual_threshold_time,startTime:req.body.startTime } }
// ); // );
const receiver_tank_info7 = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() });
const newMotorData = new MotorData({
customerId: customerId,
motor_id: motorId,
start_instance_id: start_instance_id,
supplierTank: req.body.from,
receiverTank: req.body.to,
supplier_type: req.body.from_type,
receiver_type: req.body.to_type,
startTime: req.body.startTime,
receiverInitialwaterlevel:parseInt(receiver_tank_info7.waterlevel, 10)
});
await newMotorData.save();
for await (const tank of Tank.find({ "connections.inputConnections.motor_id": motorId })) { for await (const tank of Tank.find({ "connections.inputConnections.motor_id": motorId })) {
const index = tank.connections.inputConnections.findIndex(connection => connection.motor_id === motorId); const index = tank.connections.inputConnections.findIndex(connection => connection.motor_id === motorId);
if (index !== -1) { if (index !== -1) {
await Tank.updateOne( await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId }, { customerId, "connections.inputConnections.motor_id": motorId },
{ $set: { [`connections.inputConnections.${index}.manual_threshold_time`]: req.body.manual_threshold_time, [`connections.inputConnections.${index}.startTime`]: req.body.startTime } } { $set: { [`connections.inputConnections.${index}.manual_threshold_time`]: req.body.manual_threshold_time, [`connections.inputConnections.${index}.startTime`]: req.body.startTime,[`connections.inputConnections.${index}.start_instance_id`]: start_instance_id } }
); );
} }
} }
@ -951,26 +990,61 @@ exports.motorAction = async (req, reply) => {
const splr_tank_info3_waterlevel = parseInt(splr_tank_info3.waterlevel, 10); const splr_tank_info3_waterlevel = parseInt(splr_tank_info3.waterlevel, 10);
const splr_tank_info3_capacity = parseInt(splr_tank_info3.capacity, 10); const splr_tank_info3_capacity = parseInt(splr_tank_info3.capacity, 10);
const splr_tank_info3_percentage = (splr_tank_info3_waterlevel / splr_tank_info3_capacity) * 100; const splr_tank_info3_percentage = (splr_tank_info3_waterlevel / splr_tank_info3_capacity) * 100;
console.log(splr_tank_info3_percentage,"percentage for less than 20") console.log(splr_tank_info3_percentage, "percentage for less than 20");
if (new Date() >= thresholdTime || splr_tank_info3_percentage <= 20) { if (new Date() >= thresholdTime || splr_tank_info3_percentage <= 20) {
// Stop the motor pump
await Tank.updateOne( await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId }, { customerId, "connections.inputConnections.motor_id": motorId },
{ {
$set: { $set: {
"connections.inputConnections.$.motor_stop_status": "1", "connections.inputConnections.$.motor_stop_status": "1",
"connections.inputConnections.$.threshold_type": null, "connections.inputConnections.$.threshold_type": null,
"connections.inputConnections.$.manual_threshold_time": null, "connections.inputConnections.$.manual_threshold_time": null,
"connections.inputConnections.$.manual_threshold_percentage": null "connections.inputConnections.$.manual_threshold_percentage": null
} }
} }
); );
clearInterval(intervalId); // Stop monitoring water level clearInterval(intervalId);
await delay(300000);
const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id });
if (motorData) {
const receiverTank = await Tank.findOne({ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() });
const receiverFinalWaterLevel = parseInt(receiverTank.waterlevel, 10);
const quantityDelivered = receiverFinalWaterLevel - parseInt(motorData.receiverInitialwaterlevel, 10);
const water_pumped_till_now = parseInt(receiverTank.total_water_added_from_midnight, 10);
const totalwaterpumped = quantityDelivered + water_pumped_till_now
await Tank.findOneAndUpdate({customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase()}, { $set: { total_water_added_from_midnight: totalwaterpumped } })
await MotorData.updateOne(
{ customerId, motor_id: motorId, start_instance_id: start_instance_id },
{
$set: {
stopTime: new Date().toISOString(),
receiverfinalwaterlevel: receiverFinalWaterLevel.toString(),
quantity_delivered: quantityDelivered.toString()
} }
}, 60000); // Check water level every minute }
);
}
}
}, 60000);
} else if (req.body.threshold_type === "litres") { } else if (req.body.threshold_type === "litres") {
const receiver_tank_info7 = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() });
const newMotorData = new MotorData({
customerId: customerId,
motor_id: motor_id,
start_instance_id: start_instance_id,
supplierTank: req.body.from,
receiverTank: req.body.to,
supplier_type: req.body.from_type,
receiver_type: req.body.to_type,
startTime: req.body.startTime,
receiverwaterlevel:parseInt(receiver_tank_info7.waterlevel, 10)
});
await newMotorData.save();
// If threshold type is percentage, calculate percentage threshold // If threshold type is percentage, calculate percentage threshold
const receiver_tank_info = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() }); const receiver_tank_info = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() });
const supplier_tank_info = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() }); const supplier_tank_info = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() });
@ -1026,6 +1100,25 @@ exports.motorAction = async (req, reply) => {
} }
); );
clearInterval(intervalId); // Stop monitoring water level clearInterval(intervalId); // Stop monitoring water level
await delay(300000);
const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id });
if (motorData) {
const receiverTank = await Tank.findOne({ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() });
const receiverFinalWaterLevel = parseInt(receiverTank.waterlevel, 10);
const quantityDelivered = receiverFinalWaterLevel - parseInt(motorData.receiverInitialwaterlevel, 10);
await MotorData.updateOne(
{ customerId, motor_id: motorId, start_instance_id: start_instance_id },
{
$set: {
stopTime: new Date().toISOString(),
receiverfinalwaterlevel: receiverFinalWaterLevel.toString(),
quantity_delivered: quantityDelivered.toString()
}
}
);
}
} }
}, 20000); // Check water level every minute }, 20000); // Check water level every minute
} }
@ -2030,37 +2123,84 @@ exports.startUpdateLoop = async (request, reply) => {
}; };
exports.updatewaterlevelsatmidnight = async (req, reply) => { // exports.updatewaterlevelsatmidnight = async (req, reply) => {
try { // try {
// Schedule the task to run every day at 10 seconds past the minute // // Schedule the task to run every day at 10 seconds past the minute
cron.schedule('0 0 * * *', async () => { // 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);
// }
// };
const updatewaterlevelsatmidnight = async () => {
console.log('Cron job triggered at:', moment().tz('Asia/Kolkata').format());
try { try {
const tanks = await Tank.find({ customerId: req.query.customerId }); const tanks = await Tank.find({});
for (const tank of tanks) { for (const tank of tanks) {
tank.waterlevel_at_midnight = tank.waterlevel; tank.waterlevel_at_midnight = tank.waterlevel;
console.log(tank.waterlevel_at_midnight) tank.total_water_added_from_midnight = "0";
await tank.save(); await tank.save();
console.log(`Updated tank ${tank._id} waterlevel_at_midnight to ${tank.waterlevel}`);
} }
console.log('Waterlevel noted in waterlevel_at_midnight'); console.log('Waterlevel noted in waterlevel_at_midnight');
} catch (error) { } catch (error) {
console.error('Error occurred:', error); console.error('Error occurred:', error);
} }
}); };
await Tank.find({ customerId: req.query.customerId }) // Schedule the task to run every day at 13:49 IST (1:49 PM IST)
.exec() cron.schedule('0 0 * * *', updatewaterlevelsatmidnight, {
.then((docs) => { timezone: "Asia/Kolkata"
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); const updateWaterConsumptiontillmidnight = async () => {
console.log('Cron job triggered at:', moment().tz('Asia/Kolkata').format());
try {
const tanks = await Tank.find({});
for (const tank of tanks) {
tank.waterlevel_at_midnight = tank.waterlevel;
tank.total_water_added_from_midnight = "0";
await tank.save();
console.log(`Updated tank ${tank._id} waterlevel_at_midnight to ${tank.waterlevel}`);
}
console.log('Waterlevel noted in waterlevel_at_midnight');
} catch (error) {
console.error('Error occurred:', error);
} }
}; };
// Schedule the task to run every day at 13:49 IST (1:49 PM IST)
cron.schedule('55 23 * * *', updateWaterConsumptiontillmidnight, {
timezone: "Asia/Kolkata"
});
exports.deletemotordatarecordsbefore7days = async (req, reply) => { exports.deletemotordatarecordsbefore7days = async (req, reply) => {
try { try {
@ -2416,18 +2556,6 @@ const storeWaterLevels = async () => {
setInterval(storeWaterLevels, 15 * 60 * 1000); setInterval(storeWaterLevels, 15 * 60 * 1000);
const updateWaterLevelAtMidnight = async () => {
try {
await Tank.updateMany({}, { $set: { waterlevel_at_midnight: '$waterlevel' } });
console.log('Water levels updated at midnight');
} catch (error) {
console.error('Error updating water levels:', error);
}
};
// Schedule the job to run at midnight every day
cron.schedule('0 0 * * *', async () => {
await updateWaterLevelAtMidnight();
});
console.log('Cron job scheduled to update water levels at midnight'); console.log('Cron job scheduled to update water levels at midnight');

@ -56,8 +56,6 @@ const tanksSchema = new mongoose.Schema({
reserved_percentage:{type: String,default:"20"}, reserved_percentage:{type: String,default:"20"},
auto_max_percentage :{ type: String, default: "80" }, auto_max_percentage :{ type: String, default: "80" },
connections: { connections: {
source: { type: String }, source: { type: String },
inputConnections: [ inputConnections: [
@ -104,8 +102,12 @@ const tanksSchema = new mongoose.Schema({
const motordataSchema = new mongoose.Schema({ const motordataSchema = new mongoose.Schema({
customerId: { type: String, default: null }, customerId: { type: String, default: null },
motor_id: { type: String, default: null },
start_instance_id:{type:String,default:null},
supplierTank: { type: String, default: null }, supplierTank: { type: String, default: null },
receiverTank: { type: String, default: null }, receiverTank: { type: String, default: null },
receiverInitialwaterlevel: { type: String, default: "0" },
receiverfinalwaterlevel: { type: String, default: "0" },
startTime: { type: String, default: null }, startTime: { type: String, default: null },
stopTime: { type: String, default: null }, stopTime: { type: String, default: null },
supplier_type: { type: String, default: null }, supplier_type: { type: String, default: null },

@ -558,23 +558,23 @@ module.exports = function (fastify, opts, next) {
handler: tanksController.startUpdateLoop, handler: tanksController.startUpdateLoop,
}); });
fastify.get("/api/updatewaterlevelsatmidnight", { // fastify.get("/api/updatewaterlevelsatmidnight", {
schema: { // schema: {
tags: ["Tank"], // tags: ["Tank"],
description: "This is for storing waterlevels in tank at midnight", // description: "This is for storing waterlevels in tank at midnight",
summary: "This is for storing waterlevels in tank at midnight", // summary: "This is for storing waterlevels in tank at midnight",
querystring: { // querystring: {
customerId: {type: 'string'} // customerId: {type: 'string'}
}, // },
security: [ // security: [
{ // {
basicAuth: [], // basicAuth: [],
}, // },
], // ],
}, // },
preHandler: fastify.auth([fastify.authenticate]), // preHandler: fastify.auth([fastify.authenticate]),
handler: tanksController.updatewaterlevelsatmidnight, // handler: tanksController.updatewaterlevelsatmidnight,
}); // });

Loading…
Cancel
Save