From dd0a632331be0a59660468a27ff29d436d7842ce Mon Sep 17 00:00:00 2001 From: varun Date: Mon, 20 May 2024 03:42:14 -0400 Subject: [PATCH 01/24] change in iotdata if tank not found for tankhardwareId4 --- src/controllers/tanksController.js | 73 ++++++++++++++++++++++++++---- src/models/tanks.js | 3 +- src/routes/tanksRoute.js | 4 +- 3 files changed, 67 insertions(+), 13 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index fec23961..7ec15385 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -871,6 +871,7 @@ exports.motorAction = async (req, reply) => { // Determine the motor stop status based on the action let motorStopStatus; + if (action === "start") { motorStopStatus = "2"; // If action is start, set stop status to "2" } else if (action === "stop") { @@ -900,15 +901,27 @@ exports.motorAction = async (req, reply) => { } else { + // Update the motor stop status to "2" for start action await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, - { $set: { "connections.inputConnections.$.motor_stop_status": "2" } } + { $set: { "connections.inputConnections.$.motor_stop_status": "2","connections.inputConnections.$.motor_on_type": req.body.on_type } } + ); + } + + if (action === "start"&&req.body.on_type==="auto") { + await Tank.updateOne( + { customerId, "connections.inputConnections.motor_id": motorId }, + { $set: { "connections.inputConnections.$.motor_stop_status": "2","connections.inputConnections.$.motor_on_type": req.body.on_type } } ); } + + + + // Check threshold settings if action is start - if (action === "start") { + if (action === "start"&&req.body.on_type==="manual") { if (req.body.threshold_type === "time") { // If threshold type is time, update threshold time // await Tank.updateOne( @@ -922,7 +935,7 @@ exports.motorAction = async (req, reply) => { 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}.motor_on_type`]: "manual" } } ); } } @@ -938,9 +951,9 @@ exports.motorAction = async (req, reply) => { { customerId, "connections.inputConnections.motor_id": motorId }, { $set: { - "connections.inputConnections.$.motor_stop_status": "1", - + "connections.inputConnections.$.motor_stop_status": "1", "connections.inputConnections.$.threshold_type": null, + "connections.inputConnections.$.motor_on_type": null, "connections.inputConnections.$.manual_threshold_time": null, "connections.inputConnections.$.manual_threshold_percentage": null } @@ -963,9 +976,6 @@ exports.motorAction = async (req, reply) => { 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); @@ -978,7 +988,7 @@ exports.motorAction = async (req, reply) => { if (index !== -1) { await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, - { $set: { [`connections.inputConnections.${index}.manual_threshold_percentage`]: supplier_threshold.toString(), [`connections.inputConnections.${index}.startTime`]: req.body.startTime } } + { $set: { [`connections.inputConnections.${index}.manual_threshold_percentage`]: supplier_threshold.toString(), [`connections.inputConnections.${index}.startTime`]: req.body.startTime,[`connections.inputConnections.${index}.motor_on_type`]: "manual" } } ); } } @@ -1000,7 +1010,7 @@ exports.motorAction = async (req, reply) => { { $set: { "connections.inputConnections.$.motor_stop_status": "1", - + "connections.inputConnections.$.motor_on_type": null, "connections.inputConnections.$.threshold_type": null, "connections.inputConnections.$.manual_threshold_time": null, "connections.inputConnections.$.manual_threshold_percentage": null @@ -1021,6 +1031,49 @@ exports.motorAction = async (req, reply) => { } }; +const checkAutoMode = async () => { + try { + const tanks = await Tank.find(); + + for (const tank of tanks) { + if (tank.auto_mode === "active") { + const waterLevel = parseInt(tank.waterlevel, 10); + const capacity = parseInt(tank.capacity, 10); + const autoMinPercentage = parseInt(tank.auto_min_percentage, 10); + + if (capacity > 0) { + const currentPercentage = (waterLevel / capacity) * 100; + + if (currentPercentage <= autoMinPercentage) { + // Call motorAction function + await motorAction({ + params: { customerId: tank.customerId }, + body: { + action: "start", + motor_id: tank.connections.inputConnections[0].motor_id, + to:tank.tankName, + from:tank.connections.inputConnections[0].inputConnections, + from_type:connections.inputConnections[0].input_type, + to_type:tank.tankLocation, + // startTime:, + on_type:"auto" + + + } + }, { + 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); diff --git a/src/models/tanks.js b/src/models/tanks.js index 53a6063f..91c0a671 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -68,7 +68,7 @@ const tanksSchema = new mongoose.Schema({ motor_status: { type: String, default: "0" }, auto_mode:{type:String,default:"inactive"}, motor_stop_status: { type: String, default: "1" }, - motor_on_type :{ type: String, default: "manual" }, + motor_on_type :{ type: String, default: null }, capacity:{ type: String ,default: null}, water_level:{ type: String ,default: null}, manual_threshold_percentage:{type: String, default: "90"}, @@ -92,6 +92,7 @@ const tanksSchema = new mongoose.Schema({ manual_threshold_percentage:{type: String, default: "90"}, manual_threshold_time:{type: String, default: null}, threshold_type:{type: String, default: "percentage"}, + } ] diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 1edcbcb3..7a646515 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -283,14 +283,14 @@ 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"}, motor_id:{type:"string"}, + on_type:{type:"string"} }, }, security: [ From 228dfcc014abc978977fbfa2d1e33dad7c08ab47 Mon Sep 17 00:00:00 2001 From: varun Date: Mon, 20 May 2024 05:22:34 -0400 Subject: [PATCH 02/24] change in iotdata if tank not found for tankhardwareId4 --- src/controllers/tanksController.js | 73 ++++-------------------------- src/models/tanks.js | 3 +- src/routes/tanksRoute.js | 4 +- 3 files changed, 13 insertions(+), 67 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 7ec15385..fec23961 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -871,7 +871,6 @@ exports.motorAction = async (req, reply) => { // Determine the motor stop status based on the action let motorStopStatus; - if (action === "start") { motorStopStatus = "2"; // If action is start, set stop status to "2" } else if (action === "stop") { @@ -901,27 +900,15 @@ exports.motorAction = async (req, reply) => { } else { - // Update the motor stop status to "2" for start action await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, - { $set: { "connections.inputConnections.$.motor_stop_status": "2","connections.inputConnections.$.motor_on_type": req.body.on_type } } - ); - } - - if (action === "start"&&req.body.on_type==="auto") { - await Tank.updateOne( - { customerId, "connections.inputConnections.motor_id": motorId }, - { $set: { "connections.inputConnections.$.motor_stop_status": "2","connections.inputConnections.$.motor_on_type": req.body.on_type } } + { $set: { "connections.inputConnections.$.motor_stop_status": "2" } } ); } - - - - // Check threshold settings if action is start - if (action === "start"&&req.body.on_type==="manual") { + if (action === "start") { if (req.body.threshold_type === "time") { // If threshold type is time, update threshold time // await Tank.updateOne( @@ -935,7 +922,7 @@ exports.motorAction = async (req, reply) => { 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,[`connections.inputConnections.${index}.motor_on_type`]: "manual" } } + { $set: { [`connections.inputConnections.${index}.manual_threshold_time`]: req.body.manual_threshold_time, [`connections.inputConnections.${index}.startTime`]: req.body.startTime } } ); } } @@ -951,9 +938,9 @@ exports.motorAction = async (req, reply) => { { customerId, "connections.inputConnections.motor_id": motorId }, { $set: { - "connections.inputConnections.$.motor_stop_status": "1", + "connections.inputConnections.$.motor_stop_status": "1", + "connections.inputConnections.$.threshold_type": null, - "connections.inputConnections.$.motor_on_type": null, "connections.inputConnections.$.manual_threshold_time": null, "connections.inputConnections.$.manual_threshold_percentage": null } @@ -976,6 +963,9 @@ exports.motorAction = async (req, reply) => { 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); @@ -988,7 +978,7 @@ exports.motorAction = async (req, reply) => { if (index !== -1) { await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, - { $set: { [`connections.inputConnections.${index}.manual_threshold_percentage`]: supplier_threshold.toString(), [`connections.inputConnections.${index}.startTime`]: req.body.startTime,[`connections.inputConnections.${index}.motor_on_type`]: "manual" } } + { $set: { [`connections.inputConnections.${index}.manual_threshold_percentage`]: supplier_threshold.toString(), [`connections.inputConnections.${index}.startTime`]: req.body.startTime } } ); } } @@ -1010,7 +1000,7 @@ exports.motorAction = async (req, reply) => { { $set: { "connections.inputConnections.$.motor_stop_status": "1", - "connections.inputConnections.$.motor_on_type": null, + "connections.inputConnections.$.threshold_type": null, "connections.inputConnections.$.manual_threshold_time": null, "connections.inputConnections.$.manual_threshold_percentage": null @@ -1031,49 +1021,6 @@ exports.motorAction = async (req, reply) => { } }; -const checkAutoMode = async () => { - try { - const tanks = await Tank.find(); - - for (const tank of tanks) { - if (tank.auto_mode === "active") { - const waterLevel = parseInt(tank.waterlevel, 10); - const capacity = parseInt(tank.capacity, 10); - const autoMinPercentage = parseInt(tank.auto_min_percentage, 10); - - if (capacity > 0) { - const currentPercentage = (waterLevel / capacity) * 100; - - if (currentPercentage <= autoMinPercentage) { - // Call motorAction function - await motorAction({ - params: { customerId: tank.customerId }, - body: { - action: "start", - motor_id: tank.connections.inputConnections[0].motor_id, - to:tank.tankName, - from:tank.connections.inputConnections[0].inputConnections, - from_type:connections.inputConnections[0].input_type, - to_type:tank.tankLocation, - // startTime:, - on_type:"auto" - - - } - }, { - 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); diff --git a/src/models/tanks.js b/src/models/tanks.js index 91c0a671..53a6063f 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -68,7 +68,7 @@ const tanksSchema = new mongoose.Schema({ motor_status: { type: String, default: "0" }, auto_mode:{type:String,default:"inactive"}, motor_stop_status: { type: String, default: "1" }, - motor_on_type :{ type: String, default: null }, + motor_on_type :{ type: String, default: "manual" }, capacity:{ type: String ,default: null}, water_level:{ type: String ,default: null}, manual_threshold_percentage:{type: String, default: "90"}, @@ -92,7 +92,6 @@ const tanksSchema = new mongoose.Schema({ manual_threshold_percentage:{type: String, default: "90"}, manual_threshold_time:{type: String, default: null}, threshold_type:{type: String, default: "percentage"}, - } ] diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 7a646515..1edcbcb3 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -283,14 +283,14 @@ 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"}, motor_id:{type:"string"}, - on_type:{type:"string"} }, }, security: [ From 6d5b4854bc001618f2ef7a570840fe17d5484679 Mon Sep 17 00:00:00 2001 From: varun Date: Mon, 20 May 2024 05:54:50 -0400 Subject: [PATCH 03/24] automation of motor switch --- src/controllers/tanksController.js | 108 +++++++++++++++++++++++++++++ src/routes/tanksRoute.js | 3 +- 2 files changed, 109 insertions(+), 2 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index fec23961..c62ddef0 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1023,6 +1023,114 @@ 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) { + if (tank.auto_mode === "active") { + const waterLevel = parseInt(tank.waterlevel, 10); + const capacity = parseInt(tank.capacity, 10); + const autoMinPercentage = parseInt(tank.auto_min_percentage, 10); + const autoMaxPercentage = parseInt(tank.auto_max_percentage, 10); + const currentPercentage = (waterLevel / capacity) * 100; + + const now = moment().format('DD-MMM-YYYY-HH-mm'); + + if (capacity > 0) { + if (currentPercentage <= autoMinPercentage) { + await motorActionAuto({ + params: { customerId: tank.customerId }, + body: { + action: "start", + motor_id: tank.connections.inputConnections[0].motor_id, + motor_on_type: "auto", + startTime: now + } + }, { + code: (statusCode) => ({ send: (response) => console.log(response) }) + }); + } else if (currentPercentage >= autoMaxPercentage && tank.connections.inputConnections[0].motor_on_type === "auto") { + await motorActionAuto({ + params: { customerId: tank.customerId }, + body: { + action: "stop", + motor_id: tank.connections.inputConnections[0].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 { diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 1edcbcb3..6ac3d2bd 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -283,8 +283,7 @@ 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"}, From e5e691c37bb47b00f9ddf30a9155221e1036b15e Mon Sep 17 00:00:00 2001 From: varun Date: Mon, 20 May 2024 06:07:59 -0400 Subject: [PATCH 04/24] automation of motor switch test2 --- src/controllers/tanksController.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index c62ddef0..2c4d65c8 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1082,12 +1082,13 @@ const checkAutoMode = async () => { for (const tank of tanks) { if (tank.auto_mode === "active") { + console.log("this is automation " + tank.tankName) const waterLevel = parseInt(tank.waterlevel, 10); const capacity = parseInt(tank.capacity, 10); const autoMinPercentage = parseInt(tank.auto_min_percentage, 10); const autoMaxPercentage = parseInt(tank.auto_max_percentage, 10); const currentPercentage = (waterLevel / capacity) * 100; - + console.log("this is automation percentage " + currentPercentage) const now = moment().format('DD-MMM-YYYY-HH-mm'); if (capacity > 0) { From 276725ca119bbefbb203a596a6f63a228753441b Mon Sep 17 00:00:00 2001 From: varun Date: Mon, 20 May 2024 06:15:41 -0400 Subject: [PATCH 05/24] automation of motor switch test2 --- src/controllers/tanksController.js | 73 +++++++++++++++--------------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 2c4d65c8..3dc811da 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1075,47 +1075,48 @@ const motorActionAuto = async (req, reply) => { }; - const checkAutoMode = async () => { try { const tanks = await Tank.find(); for (const tank of tanks) { - if (tank.auto_mode === "active") { - console.log("this is automation " + tank.tankName) - const waterLevel = parseInt(tank.waterlevel, 10); - const capacity = parseInt(tank.capacity, 10); - const autoMinPercentage = parseInt(tank.auto_min_percentage, 10); - const autoMaxPercentage = parseInt(tank.auto_max_percentage, 10); - const currentPercentage = (waterLevel / capacity) * 100; - console.log("this is automation percentage " + currentPercentage) - const now = moment().format('DD-MMM-YYYY-HH-mm'); - - if (capacity > 0) { - if (currentPercentage <= autoMinPercentage) { - await motorActionAuto({ - params: { customerId: tank.customerId }, - body: { - action: "start", - motor_id: tank.connections.inputConnections[0].motor_id, - motor_on_type: "auto", - startTime: now - } - }, { - code: (statusCode) => ({ send: (response) => console.log(response) }) - }); - } else if (currentPercentage >= autoMaxPercentage && tank.connections.inputConnections[0].motor_on_type === "auto") { - await motorActionAuto({ - params: { customerId: tank.customerId }, - body: { - action: "stop", - motor_id: tank.connections.inputConnections[0].motor_id, - motor_on_type: "auto", - stopTime: now - } - }, { - code: (statusCode) => ({ send: (response) => console.log(response) }) - }); + for (const inputConnection of tank.connections.inputConnections) { + if (inputConnection.auto_mode === "active") { + console.log("This is automation for tank: " + tank.tankName); + const waterLevel = parseInt(tank.waterlevel, 10); + const capacity = parseInt(tank.capacity, 10); + const autoMinPercentage = parseInt(inputConnection.auto_min_percentage, 10); + const autoMaxPercentage = parseInt(inputConnection.auto_max_percentage, 10); + const currentPercentage = (waterLevel / capacity) * 100; + console.log("This is automation percentage: " + currentPercentage); + const now = moment().format('DD-MMM-YYYY-HH-mm'); + + if (capacity > 0) { + 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) }) + }); + } } } } From 804f3a134ca99e1587c05470d15582d94b6fed99 Mon Sep 17 00:00:00 2001 From: varun Date: Mon, 20 May 2024 07:02:25 -0400 Subject: [PATCH 06/24] automation of motor switch test2 --- src/controllers/tanksController.js | 72 ++++++++++++++++-------------- 1 file changed, 39 insertions(+), 33 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 3dc811da..560c43b8 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1043,7 +1043,7 @@ const motorActionAuto = async (req, reply) => { $set: { "connections.inputConnections.$.motor_stop_status": "2", "connections.inputConnections.$.startTime": req.body.startTime, - "connections.inputConnections.$.motor)on_type": "auto", + "connections.inputConnections.$.motor_on_type": "auto", } } @@ -1083,40 +1083,45 @@ const checkAutoMode = async () => { for (const inputConnection of tank.connections.inputConnections) { if (inputConnection.auto_mode === "active") { console.log("This is automation for tank: " + tank.tankName); - const waterLevel = parseInt(tank.waterlevel, 10); - const capacity = parseInt(tank.capacity, 10); - const autoMinPercentage = parseInt(inputConnection.auto_min_percentage, 10); - const autoMaxPercentage = parseInt(inputConnection.auto_max_percentage, 10); + 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'); - - if (capacity > 0) { - 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) }) - }); - } + 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) }) + }); } } } @@ -1134,6 +1139,7 @@ setInterval(checkAutoMode, 15000); + // exports.calculateCapacity = async (req, reply) => { // try { // const shape = req.body.shape From d5dc7272f7fc3185022090a89ceb9d040988c182 Mon Sep 17 00:00:00 2001 From: varun Date: Tue, 21 May 2024 05:06:55 -0400 Subject: [PATCH 07/24] automation of motor switch test2 --- src/controllers/tanksController.js | 23 ++++++++++++--- src/routes/tanksRoute.js | 47 ++++++++++++++++++++++++++++-- 2 files changed, 64 insertions(+), 6 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 560c43b8..2a795496 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2323,7 +2323,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( @@ -2331,9 +2331,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, @@ -2347,4 +2363,3 @@ exports.update_auto_mode = async (req, reply) => { throw boom.boomify(error); } }; - diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 6ac3d2bd..6122a18d 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -797,8 +797,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 }, }, @@ -818,6 +817,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(); } From 380627bf7fe16ff0b316a59ae15a6df6f9c6e25e Mon Sep 17 00:00:00 2001 From: varun Date: Wed, 22 May 2024 05:41:44 -0400 Subject: [PATCH 08/24] automation of motor switch test2 --- src/controllers/tanksController.js | 8 +++++++- src/models/tanks.js | 1 + 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 2a795496..6ad20279 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -932,7 +932,13 @@ exports.motorAction = async (req, reply) => { 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) { + const splr_tank_info3 = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() }); + const splr_tank_info3_waterlevel = parseInt(supplier_tank_info.waterlevel, 10); + const splr_tank_info3_capacity = parseInt(supplier_tank_info.capacity, 10); + const splr_tank_info3_percentage = (splr_tank_info3_waterlevel / splr_tank_info3_capacity) * 100; + + + if (new Date() >= thresholdTime || splr_tank_info3_percentage<=20) { // Stop the motor pump await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, diff --git a/src/models/tanks.js b/src/models/tanks.js index 53a6063f..3e6e3532 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -53,6 +53,7 @@ const tanksSchema = new mongoose.Schema({ 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" }, From cc3fa2531aaeaca9a972bc2c5818c5aa9aa7e28f Mon Sep 17 00:00:00 2001 From: varun Date: Wed, 22 May 2024 05:57:48 -0400 Subject: [PATCH 09/24] automation of motor switch test2 --- src/controllers/tanksController.js | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 6ad20279..a6e36335 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1494,23 +1494,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 From 0062f2fdd1719021ba59777d0da9b584cccf8312 Mon Sep 17 00:00:00 2001 From: varun Date: Wed, 22 May 2024 06:37:00 -0400 Subject: [PATCH 10/24] automation of motor switch test2 --- src/controllers/tanksController.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index a6e36335..8929f0dd 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -933,10 +933,10 @@ exports.motorAction = async (req, reply) => { const intervalId = setInterval(async () => { // Check if threshold time has been reached const splr_tank_info3 = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() }); - const splr_tank_info3_waterlevel = parseInt(supplier_tank_info.waterlevel, 10); - const splr_tank_info3_capacity = parseInt(supplier_tank_info.capacity, 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_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) { // Stop the motor pump From 60036e98367a7929e1ec5e376b777b850707fbb9 Mon Sep 17 00:00:00 2001 From: varun Date: Wed, 22 May 2024 07:22:19 -0400 Subject: [PATCH 11/24] automation of motor switch test2 --- src/controllers/tanksController.js | 37 +++++++++++------------------- 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 8929f0dd..2a795496 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -932,13 +932,7 @@ exports.motorAction = async (req, reply) => { const thresholdTime = moment().add(req.body.manual_threshold_time, 'minutes').toDate(); const intervalId = setInterval(async () => { // Check if threshold time has been reached - 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) { + if (new Date() >= thresholdTime) { // Stop the motor pump await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, @@ -1494,26 +1488,23 @@ exports.IotDevice = async (req, reply) => { const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); const water_level = water_level_height * waterCapacityPerCm; - 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(); - } + 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 From 4d8da59661a6b6c2b54bf090687498d40d55aac4 Mon Sep 17 00:00:00 2001 From: varun Date: Wed, 22 May 2024 07:37:32 -0400 Subject: [PATCH 12/24] automation of motor switch test2 --- src/controllers/tanksController.js | 31 +++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 2a795496..e83515e4 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1433,6 +1433,7 @@ exports.calculateCapacity = async (req, reply) => { // }; + exports.IotDevice = async (req, reply) => { try { const { hardwareId, mode, tanks } = req.body; @@ -1488,23 +1489,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 @@ -1525,6 +1529,7 @@ exports.IotDevice = async (req, reply) => { + // exports.IotDevice3 = async (req, reply) => { // try { // const { hardwareId, mode, tanks } = req.body; From 79f39d5fa4c10d0ab1a9c7a734a5d611b1fcf18b Mon Sep 17 00:00:00 2001 From: varun Date: Wed, 22 May 2024 07:43:57 -0400 Subject: [PATCH 13/24] automation of motor switch test2 --- src/controllers/tanksController.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index e83515e4..22ce0747 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -931,8 +931,13 @@ 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) { + 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) { // Stop the motor pump await Tank.updateOne( { customerId, "connections.inputConnections.motor_id": motorId }, From 321f3e5a38d0ea21a2e19a342a3d0f94ea0ece0d Mon Sep 17 00:00:00 2001 From: varun Date: Fri, 24 May 2024 05:01:50 -0400 Subject: [PATCH 14/24] storing waterlevels for every 15 minutes --- src/controllers/tanksController.js | 27 ++++++++++++++++++++++++++- src/models/tanks.js | 11 +++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 22ce0747..d291a0fa 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 } = require('../models/tanks') const User = require("../models/User"); const boom = require("boom"); @@ -2373,3 +2373,28 @@ exports.update_auto_percentage = async (req, reply) => { throw boom.boomify(error); } }; + + +//storing water level for every 15 minutes + +const storeWaterLevels = async () => { + try { + const tanks = await Tank.find({}); + const currentTime = new Date().toISOString(); + + 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); // Run every 15 minutes diff --git a/src/models/tanks.js b/src/models/tanks.js index 3e6e3532..defcd2d6 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -134,15 +134,22 @@ 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 Tank = mongoose.model("Tank", tanksSchema); const MotorData = mongoose.model("MotorData", motordataSchema); - +const TankWaterLevel = mongoose.model("TankWaterLevel", tankWaterLevelSchema); const IotData = mongoose.model("IotData", IOttankSchema); module.exports = { - Tank, MotorData,IotData + Tank, MotorData,IotData,TankWaterLevel } From bded7a1e594733454a9148ecc99c2fef9dd1b40c Mon Sep 17 00:00:00 2001 From: varun Date: Mon, 27 May 2024 04:19:59 -0400 Subject: [PATCH 15/24] This is for getting tank levels --- src/controllers/tanksController.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index d291a0fa..702b6253 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2377,10 +2377,14 @@ exports.update_auto_percentage = 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 = new Date().toISOString(); + const currentTime = getFormattedISTTime(); const waterLevelRecords = tanks.map(tank => ({ customerId: tank.customerId, @@ -2397,4 +2401,4 @@ const storeWaterLevels = async () => { } }; -setInterval(storeWaterLevels, 15 * 60 * 1000); // Run every 15 minutes +setInterval(storeWaterLevels, 15 * 60 * 1000); From 3af5209675264a0c07af6943975a9571a78099d5 Mon Sep 17 00:00:00 2001 From: varun Date: Thu, 30 May 2024 02:31:31 -0400 Subject: [PATCH 16/24] This is for getting tank levels --- src/controllers/tanksController.js | 8 ++------ src/models/tanks.js | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 702b6253..d291a0fa 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2377,14 +2377,10 @@ exports.update_auto_percentage = 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 currentTime = new Date().toISOString(); const waterLevelRecords = tanks.map(tank => ({ customerId: tank.customerId, @@ -2401,4 +2397,4 @@ const storeWaterLevels = async () => { } }; -setInterval(storeWaterLevels, 15 * 60 * 1000); +setInterval(storeWaterLevels, 15 * 60 * 1000); // Run every 15 minutes diff --git a/src/models/tanks.js b/src/models/tanks.js index defcd2d6..a1cc2b34 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -76,7 +76,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} } ], From 40a07d9ba6c9e89255b79c8a6fa2aa5a1f1be9b2 Mon Sep 17 00:00:00 2001 From: varun Date: Thu, 30 May 2024 02:36:58 -0400 Subject: [PATCH 17/24] This is for getting tank levels --- src/controllers/tanksController.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index d291a0fa..702b6253 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -2377,10 +2377,14 @@ exports.update_auto_percentage = 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 = new Date().toISOString(); + const currentTime = getFormattedISTTime(); const waterLevelRecords = tanks.map(tank => ({ customerId: tank.customerId, @@ -2397,4 +2401,4 @@ const storeWaterLevels = async () => { } }; -setInterval(storeWaterLevels, 15 * 60 * 1000); // Run every 15 minutes +setInterval(storeWaterLevels, 15 * 60 * 1000); From 17a2dab2a2312e37f6a8f26d3318be87d0589399 Mon Sep 17 00:00:00 2001 From: varun Date: Wed, 12 Jun 2024 02:44:34 -0400 Subject: [PATCH 18/24] made changes in tankscontroller --- src/controllers/tanksController.js | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 702b6253..374c63c9 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -895,9 +895,6 @@ exports.motorAction = async (req, reply) => { ); - - - } else { // Update the motor stop status to "2" for start action @@ -967,16 +964,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); @@ -2237,8 +2231,7 @@ exports.writeMotorStatus = async (req, reply) => { } }; -// exports.writeMotorStatus = async (req, reply) => { -// try { + // const motor_id = req.body.motor_id; // const status = req.body.status; @@ -2402,3 +2395,20 @@ const storeWaterLevels = async () => { }; 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'); \ No newline at end of file From 29434f7901de97bec2fa6a75ccbbf609117001fe Mon Sep 17 00:00:00 2001 From: varun Date: Wed, 12 Jun 2024 04:54:03 -0400 Subject: [PATCH 19/24] made changes in tankscontroller --- src/routes/tanksRoute.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 6122a18d..b4236657 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -289,6 +289,7 @@ module.exports = function (fastify, opts, next) { manual_threshold_litres:{type:"string"}, manual_threshold_time:{type:"string"}, stopTime:{type:"string"}, + start_instance_id:{type:"string"}, motor_id:{type:"string"}, }, }, From 4856e74bf02e59bcfe76aaa149695973f84adf78 Mon Sep 17 00:00:00 2001 From: varun Date: Fri, 14 Jun 2024 02:08:53 -0400 Subject: [PATCH 20/24] given total tank data in consumption --- src/controllers/tanksController.js | 59 ++++++++++++++++++++---------- src/routes/tanksRoute.js | 2 +- 2 files changed, 40 insertions(+), 21 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 374c63c9..3306b2f1 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -824,34 +824,53 @@ let supplier_tanks = []; // }; -exports.consumption = async (req, 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); +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 + // 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 newWaterLevel1 = Math.floor(consumption); + // const newWaterLevel=Math.abs(newWaterLevel1) + // tankData.push({ tankname, waterLevel: newWaterLevel }); - // console.log(newWaterLevel); + // // console.log(newWaterLevel); + + // } + // reply.send({ status_code: 200, tankData }); + // return { message: 'Water level updates started' }; + // } catch (err) { + // throw boom.boomify(err); + // } + + + + try { + const { customerId } = request.params; + + const tank = await Tank.find({ customerId, tankLocation:"overhead" }); + + if (!tank) { + return reply.status(404).send({ error: 'Tank not found' }); } - reply.send({ status_code: 200, tankData }); - return { message: 'Water level updates started' }; - } catch (err) { - throw boom.boomify(err); + // Here you can process and return the consumption data as needed + return reply.send(tank); + } catch (error) { + request.log.error(error); + return reply.status(500).send({ error: 'Internal Server Error' }); } + }; diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index b4236657..fa4bccbf 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -333,7 +333,7 @@ module.exports = function (fastify, opts, next) { }, ], }, - preHandler: fastify.auth([fastify.authenticate]), + //preHandler: fastify.auth([fastify.authenticate]), handler: tanksController.consumption, }); From 9dc7a94c4d5ae51bfa71d7c1dd9615ccae99f6cb Mon Sep 17 00:00:00 2001 From: varun Date: Fri, 21 Jun 2024 06:11:04 -0400 Subject: [PATCH 21/24] saving motor data --- src/controllers/tanksController.js | 292 +++++++++++++++++++++-------- src/models/tanks.js | 8 +- src/routes/tanksRoute.js | 34 ++-- 3 files changed, 232 insertions(+), 102 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 3306b2f1..e4c4ac31 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -825,55 +825,56 @@ let supplier_tanks = []; 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); + 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 + 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 newWaterLevel1 = Math.floor(consumption); + const newWaterLevel=Math.abs(newWaterLevel1) + 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' }; - // } catch (err) { - // throw boom.boomify(err); - // } + return { message: 'Water level updates started' }; + } catch (err) { + throw boom.boomify(err); + } - try { - const { customerId } = request.params; + // try { + // const { customerId } = request.params; - const tank = await Tank.find({ customerId, tankLocation:"overhead" }); + // const tank = await Tank.find({ customerId, tankLocation:"overhead" }); - if (!tank) { - return reply.status(404).send({ error: 'Tank not found' }); - } + // if (!tank) { + // return reply.status(404).send({ error: 'Tank not found' }); + // } - // Here you can process and return the consumption data as needed - return reply.send(tank); - } catch (error) { - request.log.error(error); - return reply.status(500).send({ error: 'Internal Server Error' }); - } + // // Here you can process and return the consumption data as needed + // return reply.send(tank); + // } catch (error) { + // request.log.error(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 @@ -882,6 +883,7 @@ exports.motorAction = async (req, reply) => { 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) { @@ -912,6 +914,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() + } + } + ); + } @@ -931,14 +957,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 } } ); } } @@ -949,28 +988,63 @@ exports.motorAction = async (req, reply) => { const intervalId = setInterval(async () => { 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_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") + console.log(splr_tank_info3_percentage, "percentage for less than 20"); - if (new Date() >= thresholdTime || splr_tank_info3_percentage<=20) { - // Stop the motor pump + 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 } }) + + 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") { + 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() }); @@ -1026,6 +1100,25 @@ 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); + + 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 } @@ -2030,37 +2123,84 @@ 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 }); - }); - } catch (err) { - throw boom.boomify(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 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) => { try { @@ -2416,18 +2556,6 @@ const storeWaterLevels = async () => { 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'); \ No newline at end of file diff --git a/src/models/tanks.js b/src/models/tanks.js index a1cc2b34..c93d5914 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -55,9 +55,7 @@ const tanksSchema = new mongoose.Schema({ 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: [ @@ -104,8 +102,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 }, diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index fa4bccbf..40236b58 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -558,23 +558,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, + // }); From 7890881ed88322f4a225e6b0371a9712d0e34cfe Mon Sep 17 00:00:00 2001 From: varun Date: Mon, 24 Jun 2024 04:33:31 -0400 Subject: [PATCH 22/24] saving motor data --- src/controllers/tanksController.js | 34 +++++++++++++++++++++++------- src/models/tanks.js | 13 ++++++++++-- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index e4c4ac31..7addce2f 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,TankWaterLevel } = require('../models/tanks') +const { Tank, MotorData, IotData,MotorIot,TankWaterLevel,TankConsumptionSchema } = require('../models/tanks') const User = require("../models/User"); const boom = require("boom"); @@ -2177,18 +2177,33 @@ cron.schedule('0 0 * * *', updatewaterlevelsatmidnight, { timezone: "Asia/Kolkata" }); -const updateWaterConsumptiontillmidnight = async () => { + + + + + + +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() + }); - 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}`); + // Save the new document + await newTankConsumption.save(); + } console.log('Waterlevel noted in waterlevel_at_midnight'); } catch (error) { @@ -2197,11 +2212,14 @@ const updateWaterConsumptiontillmidnight = async () => { }; // Schedule the task to run every day at 13:49 IST (1:49 PM IST) -cron.schedule('55 23 * * *', updateWaterConsumptiontillmidnight, { +cron.schedule('55 23 * * *', updatetotalConsumptiontillmidnight, { timezone: "Asia/Kolkata" }); + + + exports.deletemotordatarecordsbefore7days = async (req, reply) => { try { // Schedule the task to run every day at 10 seconds past the minute diff --git a/src/models/tanks.js b/src/models/tanks.js index c93d5914..903c4b57 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -144,14 +144,23 @@ const tankWaterLevelSchema = new mongoose.Schema({ 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,TankWaterLevel + Tank, MotorData,IotData,TankWaterLevel,TankConsumptionSchema } From 556931e871105b79768d441c3f4ff8b00e407b8c Mon Sep 17 00:00:00 2001 From: varun Date: Mon, 24 Jun 2024 05:00:25 -0400 Subject: [PATCH 23/24] consumption --- src/controllers/tanksController.js | 77 ++++++++++++++++++++++++++++-- src/routes/tanksRoute.js | 10 ++++ 2 files changed, 82 insertions(+), 5 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 7addce2f..6d20881a 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -837,9 +837,7 @@ exports.consumption = async (request, reply) => { 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 }); @@ -874,9 +872,73 @@ exports.consumption = async (request, reply) => { }; +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 } = 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 tankConsumptions = await TankConsumptionSchema.find({ + customerId, + tankName: tank.tankName, + tankLocation: tank.tankLocation, + time: { + $gte: start, + $lte: end + } + }); + + 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 }); + } catch (err) { + throw boom.boomify(err); + } +}; + + + + 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 { @@ -1017,11 +1079,13 @@ exports.motorAction = async (req, reply) => { 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: new Date().toISOString(), + stopTime:stopTime, receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), quantity_delivered: quantityDelivered.toString() } @@ -1108,11 +1172,14 @@ exports.motorAction = async (req, reply) => { 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: new Date().toISOString(), + stopTime:stopTime, receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), quantity_delivered: quantityDelivered.toString() } diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 40236b58..4b11695b 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -327,6 +327,16 @@ module.exports = function (fastify, opts, next) { // querystring: { // tankName: {type: 'string'} // }, + body: { + type: "object", + // required: ['phone'], + properties: { + + startDate:{ type: "string" }, + stopDate:{type:"string"}, + + }, + }, security: [ { basicAuth: [], From bcaed8bac054f997f1323d5f57540218faaf5919 Mon Sep 17 00:00:00 2001 From: varun Date: Tue, 25 Jun 2024 02:16:10 -0400 Subject: [PATCH 24/24] consumed water till night --- src/controllers/tanksController.js | 60 ++++++++++---------------- src/models/tanks.js | 5 --- src/routes/tanksRoute.js | 69 ++++++++++++++++++++++++------ 3 files changed, 77 insertions(+), 57 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 6d20881a..25a490ad 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -824,52 +824,35 @@ let supplier_tanks = []; // }; -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); +// 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 +// const tankname = tank.tankName +// const consumption = (waterlevel_at_midnight+total_water_added_from_midnight)-waterlevel - tankData.push({ tankname, waterLevel: newWaterLevel }); +// tankData.push({ tankname, waterLevel: consumption }); - // console.log(newWaterLevel); +// // console.log(newWaterLevel); - } - reply.send({ status_code: 200, tankData }); - - return { message: 'Water level updates started' }; - } catch (err) { - throw boom.boomify(err); - } - - - - // try { - // const { customerId } = request.params; +// } +// reply.send({ status_code: 200, tankData }); - // const tank = await Tank.find({ customerId, tankLocation:"overhead" }); +// return { message: 'Water level updates started' }; +// } catch (err) { +// throw boom.boomify(err); +// } - // if (!tank) { - // return reply.status(404).send({ error: 'Tank not found' }); - // } - // // Here you can process and return the consumption data as needed - // return reply.send(tank); - // } catch (error) { - // request.log.error(error); - // return reply.status(500).send({ error: 'Internal Server Error' }); - // } -}; function parseDateTime(dateTimeStr) { @@ -884,6 +867,7 @@ function parseDateTime(dateTimeStr) { exports.consumption = async (request, reply) => { try { + const { customerId } = request.params; const { startDate, stopDate } = request.body; @@ -898,7 +882,7 @@ exports.consumption = async (request, reply) => { const total_water_added_from_midnight = parseInt(tank.total_water_added_from_midnight.replace(/,/g, ''), 10); const waterlevel = parseInt(tank.waterlevel.replace(/,/g, ''), 10); const tankname = tank.tankName; - + console.log(waterlevel_at_midnight,total_water_added_from_midnight,waterlevel) const tankConsumptions = await TankConsumptionSchema.find({ customerId, tankName: tank.tankName, diff --git a/src/models/tanks.js b/src/models/tanks.js index 903c4b57..4c4dae84 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -45,11 +45,6 @@ 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" }, diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 4b11695b..7cf084b2 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -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,17 @@ module.exports = function (fastify, opts, next) { }, }, }, - // querystring: { - // tankName: {type: 'string'} - // }, - body: { - type: "object", - // required: ['phone'], - properties: { - - startDate:{ type: "string" }, - stopDate:{type:"string"}, - - }, - }, + + body: { + type: "object", + // required: ['phone'], + properties: { + startDate:{ type: "string" }, + stopDate:{type:"string"}, + + + }, + }, security: [ { basicAuth: [], @@ -347,6 +382,12 @@ module.exports = function (fastify, opts, next) { handler: tanksController.consumption, }); + + + + + + fastify.route({ method: "PUT", url: "/api/calculateCapacity",