notifications

master
Bhaskar 12 months ago
parent 73a0a0ddfb
commit e28bfa1eff

2
node_modules/.package-lock.json generated vendored

@ -1,7 +1,7 @@
{ {
"name": "armintatankapi", "name": "armintatankapi",
"version": "1.0.0", "version": "1.0.0",
"lockfileVersion": 2, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"node_modules/@adminjs/design-system": { "node_modules/@adminjs/design-system": {

1
package-lock.json generated

@ -26,6 +26,7 @@
"csvjson": "^5.1.0", "csvjson": "^5.1.0",
"csvtojson": "^2.0.10", "csvtojson": "^2.0.10",
"email-validator": "^2.0.4", "email-validator": "^2.0.4",
"events": "^3.3.0",
"exceljs": "^4.3.0", "exceljs": "^4.3.0",
"fastify": "^3.29.5", "fastify": "^3.29.5",
"fastify-auth": "^1.0.1", "fastify-auth": "^1.0.1",

@ -27,6 +27,7 @@
"csvjson": "^5.1.0", "csvjson": "^5.1.0",
"csvtojson": "^2.0.10", "csvtojson": "^2.0.10",
"email-validator": "^2.0.4", "email-validator": "^2.0.4",
"events": "^3.3.0",
"exceljs": "^4.3.0", "exceljs": "^4.3.0",
"fastify": "^3.29.5", "fastify": "^3.29.5",
"fastify-auth": "^1.0.1", "fastify-auth": "^1.0.1",

@ -10,7 +10,8 @@ const fastify = require("fastify")({
const cron = require('node-cron'); const cron = require('node-cron');
const moment = require('moment'); const moment = require('moment');
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
async function deleteOldRecords() { async function deleteOldRecords() {
const SEVEN_DAYS_IN_MILLISECONDS = 7 * 24 * 60 * 60 * 1000; const SEVEN_DAYS_IN_MILLISECONDS = 7 * 24 * 60 * 60 * 1000;
const sevenDaysAgo = new Date(Date.now() - SEVEN_DAYS_IN_MILLISECONDS); const sevenDaysAgo = new Date(Date.now() - SEVEN_DAYS_IN_MILLISECONDS);
@ -1320,28 +1321,81 @@ admin.initializeApp({
credential: admin.credential.cert(serviceAccount), credential: admin.credential.cert(serviceAccount),
}); });
// // Handle motor start event
// eventEmitter.on('motorStart', async (fcmTokens) => {
// await sendNotification(fcmTokens, 'Motor Started', 'The motor has been started successfully.');
// });
// // Handle motor stop event
// eventEmitter.on('motorStop', async (fcmTokens) => {
// await sendNotification(fcmTokens, 'Motor Stopped', 'The motor has been stopped successfully.');
// });
// // Handle low water level event
// eventEmitter.on('lowWaterLevel', async (fcmTokens) => {
// await sendNotification(fcmTokens, 'Low Water Level', 'The water level is below 20%.');
// });
// // Handle high water level event
// eventEmitter.on('highWaterLevel', async (fcmTokens) => {
// await sendNotification(fcmTokens, 'High Water Level', 'The water level has reached above 90%.');
// });
// Handle motor start event with timestamp
eventEmitter.on('motorStart', async (fcmTokens, timestamp) => {
await sendNotification(fcmTokens, 'Motor Started', `The motor has been started successfully at ${timestamp}.`);
});
// Handle motor stop event with timestamp
eventEmitter.on('motorStop', async (fcmTokens, timestamp) => {
await sendNotification(fcmTokens, 'Motor Stopped', `The motor has been stopped successfully at ${timestamp}.`);
});
// Handle low water level event with timestamp
eventEmitter.on('lowWaterLevel', async (fcmTokens, timestamp) => {
await sendNotification(fcmTokens, 'Low Water Level', `The water level dropped below 20% at ${timestamp}.`);
});
// Handle high water level event with timestamp
eventEmitter.on('highWaterLevel', async (fcmTokens, timestamp) => {
await sendNotification(fcmTokens, 'High Water Level', `The water level reached above 90% at ${timestamp}.`);
});
// Function to emit events with timestamps
const emitWithTimestamp = (eventName, fcmTokens) => {
const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
eventEmitter.emit(eventName, fcmTokens, timestamp);
};
const sendNotification = async (fcmTokens, title, body) => { const sendNotification = async (fcmTokens, title, body) => {
if (!Array.isArray(fcmTokens) || fcmTokens.length === 0) { if (!Array.isArray(fcmTokens) || fcmTokens.length === 0) {
console.error('No FCM tokens provided.'); console.error('No FCM tokens provided.');
return; return;
} }
const message = { for (const token of fcmTokens) {
tokens: fcmTokens, const message = {
notification: { token: token,
title: title, notification: {
body: body, title: title,
}, body: body,
}; },
data: {
target: 'tank_levels',
},
};
try { try {
const response = await admin.messaging().sendMulticast(message); const response = await admin.messaging().send(message); // Send each message individually
console.log('Notification sent successfully:', response); console.log('Notification sent successfully:', response);
} catch (error) { } catch (error) {
console.error('Error sending notification:', error); console.error(`Failed to send notification to token ${token}:`, error);
}
} }
}; };
// const sendPushNotification = async (registrationToken, title, body) => { // const sendPushNotification = async (registrationToken, title, body) => {
// const message = { // const message = {
// notification: { // notification: {
@ -1372,35 +1426,325 @@ const sendNotification = async (fcmTokens, title, body) => {
const stat_stop_intervals = {}; const stat_stop_intervals = {};
// 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) {
// throw new Error("Motor ID is required.");
// }
// const users = await User.find({ customerId: customerId });
// const fcmToken = users.map(user => user.fcmId).filter(fcmId => fcmId);
// console.log(fcmToken)
// // 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"
// // eventEmitter.emit('motorStart', fcmToken); // Emit motor start event
// emitWithTimestamp('motorStart', fcmToken); // Emit motor start event with timestamp
// console.log( eventEmitter.emit('motorStart', fcmToken))
// } else if (action === "stop") {
// motorStopStatus = "1"; // If action is stop, set stop status to "1"
// // eventEmitter.emit('motorStop', fcmToken); // Emit motor stop event
// emitWithTimestamp('motorStop', fcmToken); // Emit motor stop event with timestamp
// } else {
// throw new Error("Invalid action provided.");
// }
// // Update the motor stop status immediately if action is stop
// if (action === "stop") {
// // Update the motor stop status and other fields
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// {
// $set: {
// "connections.inputConnections.$.motor_stop_status": "1",
// "connections.inputConnections.$.stopTime": req.body.stopTime,
// "connections.inputConnections.$.threshold_type": null,
// "connections.inputConnections.$.manual_threshold_time": null,
// "connections.inputConnections.$.manual_threshold_percentage": null
// }
// }
// );
// reply.code(200).send({ message: "Motor stopped successfully." });
// // Perform stop operations in the background
// (async () => {
// 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()
// }
// }
// );
// }
// })();
// // Return here to ensure the rest of the code is not executed for the stop action
// return;
// } 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" } }
// );
// }
// // Check threshold settings if action is start
// if (action === "start") {
// if (req.body.threshold_type === "time") {
// // If threshold type is time, update threshold time
// // await Tank.updateOne(
// // { 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,[`connections.inputConnections.${index}.start_instance_id`]: start_instance_id } }
// );
// }
// }
// // Start monitoring water level based on threshold time
// const thresholdTime = moment().add(req.body.manual_threshold_time, 'minutes').toDate();
// 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);
// //console.log(splr_tank_info3_waterlevel,"splr_tank_info3_waterlevel")
// const splr_tank_info3_capacity = parseInt(splr_tank_info3.capacity.replace(/,/g, ''), 10);
// // const splr_tank_info3_capacity = parseInt(splr_tank_info3.capacity, 10);
// // console.log(splr_tank_info3.capacity,splr_tank_info3_capacity,"splr_tank_info3_capacity")
// 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) {
// console.log(splr_tank_info3_percentage,)
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// {
// $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);
// 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);
// } else if (req.body.threshold_type === "litres") {
// console.log("entered 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: 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();
// // 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() });
// if (!receiver_tank_info) {
// throw new Error("Receiver tank not found.");
// }
// if (!supplier_tank_info) {
// throw new Error("Supplierr tank not found.");
// }
// 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.replace(/,/g, ''), 10);
// console.log(desired_percentage)
// 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);
// 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 } }
// );
// }
// }
// // Update water level threshold
// // Start monitoring water level based on threshold percentage
// const intervalId = setInterval(async () => {
// // Check if water level has reached the threshold percentage
// const supplier_tank_info1 = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() });
// const current_water_level = parseInt(supplier_tank_info1.waterlevel, 10);
// if (current_water_level <= supplier_threshold) {
// // Stop the motor pump
// await Tank.updateOne(
// { customerId, "connections.inputConnections.motor_id": motorId },
// {
// $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
// 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
// }
// }
// // Respond with success message
// reply.code(200).send({ message: `Motor ${action === "start" ? "started" : "stopped"} successfully.` });
// } catch (err) {
// // Handle errors
// throw boom.boomify(err);
// }
// };
exports.motorAction = async (req, reply) => { exports.motorAction = async (req, reply) => {
try { try {
const customerId = req.params.customerId; const customerId = req.params.customerId;
const action = req.body.action; const action = req.body.action;
const motorId = req.body.motor_id; const motorId = req.body.motor_id;
const start_instance_id = req.body.start_instance_id const start_instance_id = req.body.start_instance_id;
console.log(req.body.startTime)
// Define thresholds for water levels
const lowWaterThreshold = 20; // Low water level percentage threshold
const highWaterThreshold = 90; // High water level percentage threshold
// Ensure motor_id is provided // Ensure motor_id is provided
if (!motorId) { if (!motorId) {
throw new Error("Motor ID is required."); throw new Error("Motor ID is required.");
} }
const users = await User.find({ customerId: customerId }); // Get user FCM tokens
const users = await User.find({ customerId });
const fcmToken = users.map(user => user.fcmId).filter(fcmId => fcmId); const fcmToken = users.map(user => user.fcmId).filter(fcmId => fcmId);
console.log(fcmToken)
// Determine the motor stop status based on the action // Determine the motor stop status based on the action
let motorStopStatus; let motorStopStatus;
if (action === "start") { if (action === "start") {
motorStopStatus = "2"; // If action is start, set stop status to "2" motorStopStatus = "2"; // If action is start, set stop status to "2"
emitWithTimestamp('motorStart', fcmToken); // Emit motor start notification with timestamp
} else if (action === "stop") { } else if (action === "stop") {
motorStopStatus = "1"; // If action is stop, set stop status to "1" motorStopStatus = "1"; // If action is stop, set stop status to "1"
emitWithTimestamp('motorStop', fcmToken); // Emit motor stop notification with timestamp
} else { } else {
throw new Error("Invalid action provided."); throw new Error("Invalid action provided.");
} }
// Update the motor stop status immediately if action is stop // If action is stop, immediately update motor status and perform stop operations
if (action === "stop") { if (action === "stop") {
// Update the motor stop status and other fields
await Tank.updateOne( await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId }, { customerId, "connections.inputConnections.motor_id": motorId },
{ {
@ -1414,14 +1758,12 @@ exports.motorAction = async (req, reply) => {
} }
); );
// Send immediate response to the client
reply.code(200).send({ message: "Motor stopped successfully." }); reply.code(200).send({ message: "Motor stopped successfully." });
// Perform stop operations in the background // Perform stop operations in the background
(async () => { (async () => {
await delay(300000); 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 }); const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id });
if (motorData) { if (motorData) {
const receiverTank = await Tank.findOne({ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() }); const receiverTank = await Tank.findOne({ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() });
@ -1429,6 +1771,7 @@ exports.motorAction = async (req, reply) => {
const quantityDelivered = receiverFinalWaterLevel - parseInt(motorData.receiverInitialwaterlevel, 10); const quantityDelivered = receiverFinalWaterLevel - parseInt(motorData.receiverInitialwaterlevel, 10);
const water_pumped_till_now = parseInt(receiverTank.total_water_added_from_midnight, 10); const water_pumped_till_now = parseInt(receiverTank.total_water_added_from_midnight, 10);
const totalwaterpumped = quantityDelivered + water_pumped_till_now; const totalwaterpumped = quantityDelivered + water_pumped_till_now;
await Tank.findOneAndUpdate( await Tank.findOneAndUpdate(
{ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() }, { customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() },
{ $set: { total_water_added_from_midnight: totalwaterpumped } } { $set: { total_water_added_from_midnight: totalwaterpumped } }
@ -1444,14 +1787,11 @@ exports.motorAction = async (req, reply) => {
} }
} }
); );
} }
})(); })();
// Return here to ensure the rest of the code is not executed for the stop action return; // Return early to avoid executing the start logic
return;
} else { } else {
// Update the motor stop status to "2" for start action
await Tank.updateOne( await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId }, { customerId, "connections.inputConnections.motor_id": motorId },
{ $set: { "connections.inputConnections.$.motor_stop_status": "2" } } { $set: { "connections.inputConnections.$.motor_stop_status": "2" } }
@ -1461,15 +1801,10 @@ exports.motorAction = async (req, reply) => {
// Check threshold settings if action is start // Check threshold settings if action is start
if (action === "start") { if (action === "start") {
if (req.body.threshold_type === "time") { if (req.body.threshold_type === "time") {
// If threshold type is time, update threshold time // Create a new MotorData entry
// await Tank.updateOne( const receiverTank = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() });
// { 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({ const newMotorData = new MotorData({
customerId: customerId, customerId,
motor_id: motorId, motor_id: motorId,
start_instance_id: start_instance_id, start_instance_id: start_instance_id,
supplierTank: req.body.from, supplierTank: req.body.from,
@ -1477,38 +1812,37 @@ exports.motorAction = async (req, reply) => {
supplier_type: req.body.from_type, supplier_type: req.body.from_type,
receiver_type: req.body.to_type, receiver_type: req.body.to_type,
startTime: req.body.startTime, startTime: req.body.startTime,
receiverInitialwaterlevel:parseInt(receiver_tank_info7.waterlevel, 10) receiverInitialwaterlevel: parseInt(receiverTank.waterlevel, 10)
}); });
await newMotorData.save(); await newMotorData.save();
for await (const tank of Tank.find({ "connections.inputConnections.motor_id": motorId })) { // Update the tank connections with start time and threshold time
for await (const tank of Tank.find({ "connections.inputConnections.motor_id": motorId })) {
const index = tank.connections.inputConnections.findIndex(connection => connection.motor_id === motorId); const index = tank.connections.inputConnections.findIndex(connection => connection.motor_id === motorId);
if (index !== -1) { if (index !== -1) {
await Tank.updateOne( await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId }, { customerId, "connections.inputConnections.motor_id": motorId },
{ $set: { [`connections.inputConnections.${index}.manual_threshold_time`]: req.body.manual_threshold_time, [`connections.inputConnections.${index}.startTime`]: req.body.startTime,[`connections.inputConnections.${index}.start_instance_id`]: start_instance_id } } {
$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
}
}
); );
} }
} }
// Start monitoring water level based on threshold time
const thresholdTime = moment().add(req.body.manual_threshold_time, 'minutes').toDate(); const thresholdTime = moment().add(req.body.manual_threshold_time, 'minutes').toDate();
const intervalId = setInterval(async () => { const intervalId = setInterval(async () => {
const splr_tank_info3 = await Tank.findOne({ customerId, tankName: req.body.from, tankLocation: req.body.from_type.toLowerCase() }); const supplierTank = 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 currentWaterLevel = parseInt(supplierTank.waterlevel, 10);
//console.log(splr_tank_info3_waterlevel,"splr_tank_info3_waterlevel") const currentWaterPercentage = (currentWaterLevel / parseInt(supplierTank.capacity.replace(/,/g, ''), 10)) * 100;
const splr_tank_info3_capacity = parseInt(splr_tank_info3.capacity.replace(/,/g, ''), 10);
// const splr_tank_info3_capacity = parseInt(splr_tank_info3.capacity, 10); if (new Date() >= thresholdTime || currentWaterPercentage <= lowWaterThreshold) {
// console.log(splr_tank_info3.capacity,splr_tank_info3_capacity,"splr_tank_info3_capacity")
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) {
console.log(splr_tank_info3_percentage,)
await Tank.updateOne( await Tank.updateOne(
{ customerId, "connections.inputConnections.motor_id": motorId }, { customerId, "connections.inputConnections.motor_id": motorId },
{ {
$set: { $set: {
"connections.inputConnections.$.motor_stop_status": "1", "connections.inputConnections.$.motor_stop_status": "1",
"connections.inputConnections.$.threshold_type": null, "connections.inputConnections.$.threshold_type": null,
@ -1517,26 +1851,28 @@ exports.motorAction = async (req, reply) => {
} }
} }
); );
emitWithTimestamp('lowWaterLevel', fcmToken); // Emit low water level notification
clearInterval(intervalId); clearInterval(intervalId);
await delay(300000); await delay(300000);
const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id }); const motorData = await MotorData.findOne({ customerId, motor_id: motorId, start_instance_id: start_instance_id });
if (motorData) { if (motorData) {
const receiverTank = await Tank.findOne({ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() }); const receiverTank = await Tank.findOne({ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() });
const receiverFinalWaterLevel = parseInt(receiverTank.waterlevel, 10); const receiverFinalWaterLevel = parseInt(receiverTank.waterlevel, 10);
const quantityDelivered = receiverFinalWaterLevel - parseInt(motorData.receiverInitialwaterlevel, 10); const quantityDelivered = receiverFinalWaterLevel - parseInt(motorData.receiverInitialwaterlevel, 10);
const water_pumped_till_now = parseInt(receiverTank.total_water_added_from_midnight, 10); const water_pumped_till_now = parseInt(receiverTank.total_water_added_from_midnight, 10);
const totalwaterpumped = quantityDelivered + water_pumped_till_now 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 Tank.findOneAndUpdate(
{ customerId, tankName: motorData.receiverTank, tankLocation: motorData.receiver_type.toLowerCase() },
{ $set: { total_water_added_from_midnight: totalwaterpumped } }
);
await MotorData.updateOne( await MotorData.updateOne(
{ customerId, motor_id: motorId, start_instance_id: start_instance_id }, { customerId, motor_id: motorId, start_instance_id: start_instance_id },
{ {
$set: { $set: {
stopTime:stopTime, stopTime: req.body.stopTime,
receiverfinalwaterlevel: receiverFinalWaterLevel.toString(), receiverfinalwaterlevel: receiverFinalWaterLevel.toString(),
quantity_delivered: quantityDelivered.toString() quantity_delivered: quantityDelivered.toString()
} }
@ -1544,7 +1880,14 @@ exports.motorAction = async (req, reply) => {
); );
} }
} }
}, 60000);
// Check for high water level and send notification
if (currentWaterPercentage >= highWaterThreshold) {
emitWithTimestamp('highWaterLevel', fcmToken); // Emit high water level notification
}
}, 60000); // Check every minute
} else if (req.body.threshold_type === "litres") { } else if (req.body.threshold_type === "litres") {
console.log("entered litres") console.log("entered litres")
const receiver_tank_info7 = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() }); const receiver_tank_info7 = await Tank.findOne({ customerId, tankName: req.body.to, tankLocation: req.body.to_type.toLowerCase() });
@ -1641,14 +1984,14 @@ exports.motorAction = async (req, reply) => {
); );
} }
} }
}, 20000); // Check water level every minute }, 20000);
} }
} }
// Respond with success message // Respond with success message
reply.code(200).send({ message: `Motor ${action === "start" ? "started" : "stopped"} successfully.` }); reply.code(200).send({ message: `Motor ${action === "start" ? "started" : "stopped"} successfully.` });
} catch (err) { } catch (err) {
// Handle errors
throw boom.boomify(err); throw boom.boomify(err);
} }
}; };

Loading…
Cancel
Save