diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index fec23961..25a490ad 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1,5 +1,5 @@ //const Tank = require("../models/tanks"); -const { Tank, MotorData, IotData,MotorIot } = require('../models/tanks') +const { Tank, MotorData, IotData,MotorIot,TankWaterLevel,TankConsumptionSchema } = require('../models/tanks') const User = require("../models/User"); const boom = require("boom"); @@ -824,31 +824,85 @@ let supplier_tanks = []; // }; -exports.consumption = async (req, reply) => { +// exports.consumption = async (request, reply) => { +// try { +// const customerId = req.params.customerId; +// const tanks = await Tank.find({ customerId,tankLocation:"overhead"}); +// const tankData = []; +// for (const tank of tanks) { +// const tankId = tank._id; +// 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 consumption = (waterlevel_at_midnight+total_water_added_from_midnight)-waterlevel + +// tankData.push({ tankname, waterLevel: consumption }); + + +// // console.log(newWaterLevel); + +// } +// reply.send({ status_code: 200, tankData }); + +// return { message: 'Water level updates started' }; +// } catch (err) { +// throw boom.boomify(err); +// } + + + + + +function parseDateTime(dateTimeStr) { + const [datePart, timePart] = dateTimeStr.split(' - '); + const [day, month, year] = datePart.split('-'); + const monthIndex = new Date(Date.parse(month +" 1, 2024")).getMonth(); // Parse the month name to get its index + const [hours, minutes] = timePart.split(':'); + return new Date(year, monthIndex, day, hours, minutes); +} + + + +exports.consumption = async (request, reply) => { try { - const customerId = req.params.customerId; - const tanks = await Tank.find({ customerId,tankLocation:"overhead"}); - const tankData = []; + + const { customerId } = request.params; + const { startDate, stopDate } = request.body; + + const start = parseDateTime(startDate); + const end = parseDateTime(stopDate); + const tanks = await Tank.find({ customerId, tankLocation: "overhead" }); + const tankData = []; + for (const tank of tanks) { const tankId = tank._id; 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 consumption = (waterlevel_at_midnight+total_water_added_from_midnight)-waterlevel - - const newWaterLevel1 = Math.floor(consumption); - const newWaterLevel=Math.abs(newWaterLevel1) - tankData.push({ tankname, waterLevel: newWaterLevel }); + const tankname = tank.tankName; + console.log(waterlevel_at_midnight,total_water_added_from_midnight,waterlevel) + const tankConsumptions = await TankConsumptionSchema.find({ + customerId, + tankName: tank.tankName, + tankLocation: tank.tankLocation, + time: { + $gte: start, + $lte: end + } + }); - - // console.log(newWaterLevel); + const total_consumption_from_records = tankConsumptions.reduce((acc, record) => { + return acc + parseInt(record.consumption, 10); + }, 0); + const consumption = (waterlevel_at_midnight + total_water_added_from_midnight) - waterlevel + total_consumption_from_records; + + tankData.push({ tankname, totalConsumption: consumption }); } - reply.send({ status_code: 200, tankData }); - return { message: 'Water level updates started' }; + reply.send({ status_code: 200, tankData }); } catch (err) { throw boom.boomify(err); } @@ -856,13 +910,26 @@ exports.consumption = async (req, reply) => { + +const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); + //const moment = require('moment'); // Import moment.js for date/time operations +const formatDate = (date) => { + const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + const day = String(date.getDate()).padStart(2, '0'); + const month = months[date.getMonth()]; + const year = date.getFullYear(); + const hours = String(date.getHours()).padStart(2, '0'); + const minutes = String(date.getMinutes()).padStart(2, '0'); + return `${day}-${month}-${year} - ${hours}:${minutes}`; +}; exports.motorAction = async (req, reply) => { try { const customerId = req.params.customerId; const action = req.body.action; const motorId = req.body.motor_id; + const start_instance_id = req.body.start_instance_id console.log(req.body.startTime) // Ensure motor_id is provided if (!motorId) { @@ -893,10 +960,31 @@ 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 { @@ -915,14 +1003,27 @@ exports.motorAction = async (req, reply) => { // { customerId, "connections.inputConnections.motor_id": motorId }, // { $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 })) { const index = tank.connections.inputConnections.findIndex(connection => connection.motor_id === motorId); if (index !== -1) { await Tank.updateOne( { 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 } } ); } } @@ -931,25 +1032,67 @@ exports.motorAction = async (req, reply) => { // Start monitoring water level based on threshold time const thresholdTime = moment().add(req.body.manual_threshold_time, 'minutes').toDate(); const intervalId = setInterval(async () => { - // Check if threshold time has been reached - if (new Date() >= thresholdTime) { - // Stop the motor pump + const splr_tank_info3 = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() }); + 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_percentage = (splr_tank_info3_waterlevel / splr_tank_info3_capacity) * 100; + console.log(splr_tank_info3_percentage, "percentage for less than 20"); + + if (new Date() >= thresholdTime || splr_tank_info3_percentage <= 20) { await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, - { - $set: { + { + $set: { "connections.inputConnections.$.motor_stop_status": "1", - "connections.inputConnections.$.threshold_type": null, "connections.inputConnections.$.manual_threshold_time": 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 } }) + + const stopTime = formatDate(new Date()); + + await MotorData.updateOne( + { customerId, motor_id: motorId, start_instance_id: start_instance_id }, + { + $set: { + stopTime:stopTime, + receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), + quantity_delivered: quantityDelivered.toString() + } + } + ); + } } - }, 60000); // Check water level every minute + }, 60000); } 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 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() }); @@ -962,16 +1105,13 @@ exports.motorAction = async (req, reply) => { const supplier_capacity = parseInt(supplier_tank_info.capacity, 10); const supplier_waterLevel = parseInt(supplier_tank_info.waterlevel, 10); - - - - const capacity = parseInt(receiver_tank_info.capacity, 10); const waterLevel = parseInt(receiver_tank_info.waterlevel, 10); const desired_percentage = parseInt(req.body.manual_threshold_litres, 10); const threshold_water_level = waterLevel+desired_percentage; const supplier_threshold = supplier_waterLevel-desired_percentage + console.log(supplier_threshold,"supplier_threshold") for await (const tank of Tank.find({ "connections.inputConnections.motor_id": motorId })) { const index = tank.connections.inputConnections.findIndex(connection => connection.motor_id === motorId); @@ -1008,6 +1148,28 @@ exports.motorAction = async (req, reply) => { } ); 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); + + + const stopTime = formatDate(new Date()); + + await MotorData.updateOne( + { customerId, motor_id: motorId, start_instance_id: start_instance_id }, + { + $set: { + stopTime:stopTime, + receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), + quantity_delivered: quantityDelivered.toString() + } + } + ); + } } }, 20000); // Check water level every minute } @@ -1023,6 +1185,122 @@ exports.motorAction = async (req, reply) => { +const motorActionAuto = async (req, reply) => { + try { + const customerId = req.params.customerId; + const action = req.body.action; + const motorId = req.body.motor_id; + const motor_on_type = req.body.motor_on_type + + if (!motorId) { + throw new Error("Motor ID is required."); + } + + let motorStopStatus; + + if (action === "start") { + await Tank.updateOne( + { customerId, "connections.inputConnections.motor_id": motorId }, + { + $set: { + "connections.inputConnections.$.motor_stop_status": "2", + "connections.inputConnections.$.startTime": req.body.startTime, + "connections.inputConnections.$.motor_on_type": "auto", + + } + } + ); + + ; + } + + if (action === "stop") { + await Tank.updateOne( + { customerId, "connections.inputConnections.motor_id": motorId }, + { + $set: { + "connections.inputConnections.$.motor_stop_status": "1", + "connections.inputConnections.$.stopTime": req.body.stopTime, + "connections.inputConnections.$.motor_on_type": null, + } + } + ); + } + + + + reply.code(200).send({ message: `Motor ${action === "start" ? "started" : "stopped"} successfully.` }); + } catch (err) { + console.error("Error in motorActionAuto:", err); + reply.code(500).send({ error: err.message }); + } +}; + + +const checkAutoMode = async () => { + try { + const tanks = await Tank.find(); + + for (const tank of tanks) { + for (const inputConnection of tank.connections.inputConnections) { + if (inputConnection.auto_mode === "active") { + console.log("This is automation for tank: " + tank.tankName); + const waterLevel = parseFloat(tank.waterlevel.replace(/,/g, '')); + const capacity = parseFloat(tank.capacity.replace(/,/g, '')); + const autoMinPercentage = parseFloat(tank.auto_min_percentage); + const autoMaxPercentage = parseFloat(tank.auto_max_percentage); + console.log(waterLevel,capacity,autoMinPercentage,autoMaxPercentage) + + if (isNaN(waterLevel) || isNaN(capacity) || capacity === 0) { + console.error(`Invalid water level or capacity for tank: ${tank.tankName}`); + continue; // Skip this tank if the values are not valid + } + + const currentPercentage = (waterLevel / capacity) * 100; + console.log("This is automation percentage: " + currentPercentage); + const now = moment().format('DD-MMM-YYYY - HH:mm'); + console.log(now) + if (currentPercentage <= autoMinPercentage) { + await motorActionAuto({ + params: { customerId: tank.customerId }, + body: { + action: "start", + motor_id: inputConnection.motor_id, + motor_on_type: "auto", + startTime: now + } + }, { + code: (statusCode) => ({ send: (response) => console.log(response) }) + }); + } else if (currentPercentage >= autoMaxPercentage && inputConnection.motor_on_type === "auto") { + await motorActionAuto({ + params: { customerId: tank.customerId }, + body: { + action: "stop", + motor_id: inputConnection.motor_id, + motor_on_type: "auto", + stopTime: now + } + }, { + code: (statusCode) => ({ send: (response) => console.log(response) }) + }); + } + } + } + } + } catch (err) { + console.error("Error checking auto mode:", err); + } +}; + +// Set the interval to check every 15 seconds (15000 milliseconds) +setInterval(checkAutoMode, 15000); + + + + + + // exports.calculateCapacity = async (req, reply) => { // try { @@ -1317,6 +1595,7 @@ exports.calculateCapacity = async (req, reply) => { // }; + exports.IotDevice = async (req, reply) => { try { const { hardwareId, mode, tanks } = req.body; @@ -1372,23 +1651,26 @@ exports.IotDevice = async (req, reply) => { const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); const water_level = water_level_height * waterCapacityPerCm; - existingTank.waterlevel = water_level; - - // Save the updated tank document - await existingTank.save(); - - // Update linked tanks - 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 = water_level; - await linkedTank.save(); + if (water_level >= 0) { + existingTank.waterlevel = water_level; + + // Save the updated tank document + await existingTank.save(); + + // Update linked tanks + 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 = water_level; + await linkedTank.save(); + } } } } } + } // Send the latest three documents @@ -1409,6 +1691,7 @@ exports.IotDevice = async (req, reply) => { + // exports.IotDevice3 = async (req, reply) => { // try { // const { hardwareId, mode, tanks } = req.body; @@ -1891,37 +2174,102 @@ exports.startUpdateLoop = async (request, reply) => { }; -exports.updatewaterlevelsatmidnight = async (req, reply) => { +// 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); +// } +// }; + + +const updatewaterlevelsatmidnight = async () => { + console.log('Cron job triggered at:', moment().tz('Asia/Kolkata').format()); + 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); - } - }); + 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); + } +}; - 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 }); +// Schedule the task to run every day at 13:49 IST (1:49 PM IST) +cron.schedule('0 0 * * *', updatewaterlevelsatmidnight, { + timezone: "Asia/Kolkata" +}); + + + + + + + +const updatetotalConsumptiontillmidnight = async () => { + console.log('Cron job triggered at:', moment().tz('Asia/Kolkata').format()); + + try { + const tanks = await Tank.find({}); + 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 totalconsumption = (waterlevel_at_midnight + total_water_added_from_midnight) - waterlevel + const newTankConsumption = new TankConsumptionSchema({ + customerId: tank.customerId, + tankName: tank.tankName, + tankLocation: tank.tankLocation, + consumption: totalconsumption.toString(), + time: new Date().toISOString() }); - } catch (err) { - throw boom.boomify(err); + + // Save the new document + await newTankConsumption.save(); + + } + 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 * * *', updatetotalConsumptiontillmidnight, { + timezone: "Asia/Kolkata" +}); + + + + exports.deletemotordatarecordsbefore7days = async (req, reply) => { try { @@ -2111,8 +2459,7 @@ exports.writeMotorStatus = async (req, reply) => { } }; -// exports.writeMotorStatus = async (req, reply) => { -// try { + // const motor_id = req.body.motor_id; // const status = req.body.status; @@ -2207,7 +2554,7 @@ exports.motortemperature = async (req, reply) => { exports.update_auto_mode = async (req, reply) => { try { const customerId = req.params.customerId; - const { motor_id, auto_min_percentage, auto_max_percentage, auto_mode } = req.body; + const { motor_id, auto_mode } = req.body; // Update inputConnections' auto_mode await Tank.updateOne( @@ -2215,9 +2562,25 @@ exports.update_auto_mode = async (req, reply) => { { $set: { "connections.inputConnections.$.auto_mode": auto_mode } } ); + + + reply.send({ status_code: 200, message: "Auto mode and percentages updated successfully." }); + } catch (error) { + throw boom.boomify(error); + } +}; + +exports.update_auto_percentage = async (req, reply) => { + try { + const customerId = req.params.customerId; + const { tankName,tankLocation, auto_min_percentage, auto_max_percentage } = req.body; + + // Update inputConnections' auto_mode + + // Update auto_min_percentage and auto_max_percentage - await Tank.updateMany( - { customerId: customerId }, + await Tank.updateOne( + { customerId: customerId,tankLocation, tankName}, { $set: { "auto_min_percentage": auto_min_percentage, @@ -2232,3 +2595,36 @@ exports.update_auto_mode = async (req, reply) => { } }; + +//storing water level for every 15 minutes + +const getFormattedISTTime = () => { + return moment().tz('Asia/Kolkata').format('DD-MM-YYYY hh:mm:ss A'); +}; + +const storeWaterLevels = async () => { + try { + const tanks = await Tank.find({}); + const currentTime = getFormattedISTTime(); + + const waterLevelRecords = tanks.map(tank => ({ + customerId: tank.customerId, + tankName: tank.tankName, + tankLocation: tank.tankLocation, + waterlevel: tank.waterlevel, + time: currentTime + })); + + await TankWaterLevel.insertMany(waterLevelRecords); + console.log('Water levels stored successfully'); + } catch (error) { + console.error('Error storing water levels:', error); + } +}; + +setInterval(storeWaterLevels, 15 * 60 * 1000); + + + + +console.log('Cron job scheduled to update water levels at midnight'); \ No newline at end of file diff --git a/src/models/tanks.js b/src/models/tanks.js index 53a6063f..4c4dae84 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -45,18 +45,12 @@ const tanksSchema = new mongoose.Schema({ waterCapacityPerCm:{ type: String, default: "0" }, typeOfWater: { type: String, default: null }, waterlevel: { type: String, default: "0" }, - tankLocation: { type: String, default: null }, - motor_status: { type: String, default: "1" }, - motor_stop_status: { type: String, default: "1" }, - motor_speed: { type: String, default: "100" }, - motor_temperature: { type: String, default: "0" }, waterlevel_at_midnight:{ type: String,default:"0" }, total_water_added_from_midnight:{ type: String,default:"0" }, auto_min_percentage :{ type: String, default: "20" }, + reserved_percentage:{type: String,default:"20"}, auto_max_percentage :{ type: String, default: "80" }, - - - + connections: { source: { type: String }, inputConnections: [ @@ -75,7 +69,7 @@ const tanksSchema = new mongoose.Schema({ manual_threshold_time:{type: String, default: null}, threshold_type:{type: String, default: "percentage"}, startTime:{type: String,default:null}, - + start_instance_id:{type:String,default:null}, stopTime:{type: String,default:null} } ], @@ -103,8 +97,12 @@ const tanksSchema = new mongoose.Schema({ const motordataSchema = new mongoose.Schema({ customerId: { type: String, default: null }, + motor_id: { type: String, default: null }, + start_instance_id:{type:String,default:null}, supplierTank: { type: String, default: null }, receiverTank: { type: String, default: null }, + receiverInitialwaterlevel: { type: String, default: "0" }, + receiverfinalwaterlevel: { type: String, default: "0" }, startTime: { type: String, default: null }, stopTime: { type: String, default: null }, supplier_type: { type: String, default: null }, @@ -133,15 +131,31 @@ const IOttankSchema = new mongoose.Schema({ }); +const tankWaterLevelSchema = new mongoose.Schema({ + customerId: { type: String }, + tankName: { type: String }, + tankLocation: { type: String }, + waterlevel: { type: String }, + time: { type: String } +}); + +const tankconsumptionSchema = new mongoose.Schema({ + customerId: { type: String }, + tankName: { type: String }, + tankLocation: { type: String }, + consumption: { type: String }, + time: { type: String } +}); - const Tank = mongoose.model("Tank", tanksSchema); const MotorData = mongoose.model("MotorData", motordataSchema); - +const TankWaterLevel = mongoose.model("TankWaterLevel", tankWaterLevelSchema); const IotData = mongoose.model("IotData", IOttankSchema); +const TankConsumptionSchema = mongoose.model("TankConsumptionSchema", tankconsumptionSchema); + module.exports = { - Tank, MotorData,IotData + Tank, MotorData,IotData,TankWaterLevel,TankConsumptionSchema } diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 1edcbcb3..7cf084b2 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -283,13 +283,13 @@ module.exports = function (fastify, opts, next) { from: { type: "string", default: null }, from_type: { type: "string" }, to_type: { type: "string" }, - action: { type: "string" }, - + action: { type: "string" }, startTime:{ type: "string" }, threshold_type:{type:"string"}, manual_threshold_litres:{type:"string"}, manual_threshold_time:{type:"string"}, stopTime:{type:"string"}, + start_instance_id:{type:"string"}, motor_id:{type:"string"}, }, }, @@ -308,8 +308,45 @@ module.exports = function (fastify, opts, next) { }); + // fastify.route({ + // method: "PUT", + // url: "/api/consumption/:customerId", + // schema: { + // tags: ["Tank"], + // summary: "This is for getting consumption", + // params: { + // required: ["customerId"], + // type: "object", + // properties: { + // customerId: { + // type: "string", + // description: "customerId", + // }, + // }, + // }, + + // body: { + // type: "object", + + // properties: { + + // startDate:{ type: "string" }, + // stopDate:{type:"string"}, + + // }, + // }, + // security: [ + // { + // basicAuth: [], + // }, + // ], + // }, + // //preHandler: fastify.auth([fastify.authenticate]), + // handler: tanksController.consumption, + // }); + fastify.route({ - method: "GET", + method: "PUT", url: "/api/consumption/:customerId", schema: { tags: ["Tank"], @@ -324,19 +361,33 @@ module.exports = function (fastify, opts, next) { }, }, }, - // querystring: { - // tankName: {type: 'string'} - // }, + + body: { + type: "object", + // required: ['phone'], + properties: { + startDate:{ type: "string" }, + stopDate:{type:"string"}, + + + }, + }, security: [ { basicAuth: [], }, ], }, - preHandler: fastify.auth([fastify.authenticate]), + //preHandler: fastify.auth([fastify.authenticate]), handler: tanksController.consumption, }); + + + + + + fastify.route({ method: "PUT", url: "/api/calculateCapacity", @@ -558,23 +609,23 @@ module.exports = function (fastify, opts, next) { handler: tanksController.startUpdateLoop, }); - fastify.get("/api/updatewaterlevelsatmidnight", { - schema: { - tags: ["Tank"], - description: "This is for storing waterlevels in tank at midnight", - summary: "This is for storing waterlevels in tank at midnight", - querystring: { - customerId: {type: 'string'} - }, - security: [ - { - basicAuth: [], - }, - ], - }, - preHandler: fastify.auth([fastify.authenticate]), - handler: tanksController.updatewaterlevelsatmidnight, - }); + // fastify.get("/api/updatewaterlevelsatmidnight", { + // schema: { + // tags: ["Tank"], + // description: "This is for storing waterlevels in tank at midnight", + // summary: "This is for storing waterlevels in tank at midnight", + // querystring: { + // customerId: {type: 'string'} + // }, + // security: [ + // { + // basicAuth: [], + // }, + // ], + // }, + // preHandler: fastify.auth([fastify.authenticate]), + // handler: tanksController.updatewaterlevelsatmidnight, + // }); @@ -798,8 +849,7 @@ module.exports = function (fastify, opts, next) { // required: ['phone'], properties: { motor_id: { type: "string", default: null }, - auto_min_percentage: { type: "string", default: null }, - auto_max_percentage: { type: "string", default: null }, + auto_mode: { type: "string", default: null }, }, @@ -819,6 +869,50 @@ module.exports = function (fastify, opts, next) { }); + + + fastify.route({ + method: "PUT", + url: "/api/update_auto_percentage/:customerId", + schema: { + tags: ["Tank"], + summary: "This is for changing auto mode for motor with min and max levels", + params: { + required: ["customerId"], + type: "object", + properties: { + customerId: { + type: "string", + description: "customerId", + }, + }, + }, + + body: { + type: "object", + // required: ['phone'], + properties: { + tankName: { type: "string", default: null }, + auto_min_percentage: { type: "string", default: null }, + auto_max_percentage: { type: "string", default: null }, + tankLocation: { type: "string", default: null }, + + }, + }, + security: [ + { + basicAuth: [], + }, + ], + }, + // preHandler: [ + // fastify.auth([fastify.operatorAuthenticate]), + // validationHandler.validatePhoneFormat, + // ], + //preHandler: fastify.auth([fastify.authenticate]), + handler: tanksController.update_auto_percentage, + }); + next(); }