Bhaskar 8 months ago
commit 11f5e32c95

@ -352,21 +352,50 @@ exports.getTanksofParticularInstaller = async (req, reply) => {
exports.getTankmotordata = async (req, reply) => {
try {
await MotorData.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 });
const { startDate, stopDate, block } = req.body;
const { customerId } = req.params;
const start = moment(startDate, "DD-MMM-YYYY - HH:mm").toDate();
const end = moment(stopDate, "DD-MMM-YYYY - HH:mm").toDate();
// Fetch the name from the User collection based on customerId, only from profile
const user = await User.findOne({ customerId })
.select("profile.firstName profile.lastName");
if (user) {
// Get the full name (combine firstName and lastName if available)
const userName = user.profile.firstName && user.profile.lastName
? `${user.profile.firstName} ${user.profile.lastName}`
: "N/A"; // Fallback if no name is found
// Construct the query object for motor data based on customerId
const motorQuery = { customerId };
// If block is provided (and not "All"), add it to the query
if (block !== "All") motorQuery.block = block;
// Fetch motor data for the customerId within the time range
const motorDataDocs = await MotorData.find(motorQuery)
.where("date")
.gte(start) // Greater than or equal to startDate
.lte(end) // Less than or equal to stopDate
.exec();
reply.send({
status_code: 200,
data: motorDataDocs,
count: motorDataDocs.length,
customerName: userName, // Add the username to the response
});
} else {
reply.send({ status_code: 404, message: "User not found" });
}
} catch (err) {
throw boom.boomify(err);
}
};
exports.updateTanklevels = async (req, reply) => {
try {
const customerId = req.params.customerId;
@ -5248,18 +5277,25 @@ exports.update_auto_mode = async (req, reply) => {
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
const { tankName, tankLocation, auto_min_percentage, auto_max_percentage, auto_mode_type } = req.body;
// Build the query filter
const filter = { customerId: customerId };
if (tankName !== "all") {
filter.tankName = tankName;
}
if (tankLocation) {
filter.tankLocation = tankLocation;
}
// Update auto_min_percentage and auto_max_percentage
await Tank.updateOne(
{ customerId: customerId,tankLocation, tankName},
// Update auto_min_percentage, auto_max_percentage, and auto_mode_type
await Tank.updateMany(
filter,
{
$set: {
"auto_min_percentage": auto_min_percentage,
"auto_max_percentage": auto_max_percentage
"auto_max_percentage": auto_max_percentage,
"auto_mode_type": auto_mode_type
}
}
);
@ -5271,6 +5307,7 @@ exports.update_auto_percentage = async (req, reply) => {
};
//storing water level for every 15 minutes
const getFormattedISTTime = () => {
@ -5498,9 +5535,7 @@ exports.getBlockData = async (req, reply) => {
// }
// });
const mqtt = require('mqtt');
const { setMaxIdleHTTPParsers } = require('http');
const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker
client.on('connect', () => {
@ -5610,50 +5645,27 @@ client.on('message', async (topic, message) => {
const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name
if (inputConnection) {
inputConnection.motor_status = status; // Update motor status
const tankName = motorTank.tankName;
console.log(tankName,"tankName")
if (inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") {
const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
inputConnection.motor_stop_status = "2";
inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = currentTime;
// Emit motor start notification with tankName
// eventEmitter.emit(
// "sendMotorStartNotification",
// fcmToken, // FCM tokens
// hw_Id, // Motor ID
// inputConnection.water_level || 0, // Water level
// motorTank.blockName || "N/A", // Block name
// tankName, // Tank name
// inputConnection.motor_on_type, // Motor on type
// "threshold", // Stop criteria
// manual_threshold_time // Threshold time in mins
// );
// Define logic to determine stopCriteria
let stopCriteria = "";
let highThreshold = 90; // Example high threshold value
let stopConditionMessage = "";
if (stopCriteria === "manual") {
stopConditionMessage = `Will stop at Manually \n`;
} else if (stopCriteria === "highThreshold") {
stopConditionMessage = `🚨 Pump will stop when the water level reaches the high threshold of ${highThreshold}%.\n`;
}
// Emit the event
try {
eventEmitter.emit("sendMotorStartNotification",
fcmToken,
motorTank.blockName || "N/A",
motorTank.tankName,
"Forced Manual",
stopCriteria,
motorTank.typeOfWater || "Drinking Water",
highThreshold
eventEmitter.emit(
"sendMotorStartNotification",
fcmToken, // FCM tokens
hw_Id, // Motor ID
inputConnection.water_level || 0, // Water level
motorTank.blockName || "N/A", // Block name
tankName, // Tank name
inputConnection.motor_on_type, // Motor on type
"threshold", // Stop criteria
manual_threshold_time // Threshold time in mins
);
} catch (error) {
console.error('Error emitting motor start notification:', error);
}
}
@ -5661,20 +5673,18 @@ client.on('message', async (topic, message) => {
inputConnection.motor_stop_status = "1";
// Emit motor stop notification with tankName
try {
eventEmitter.emit("sendMotorStopNotification",
fcmToken,
motorTank.blockName || "N/A",
motorTank.tankName,
"Forced Manual",
motorTank.typeOfWater || "Drinking Water"
eventEmitter.emit(
"sendMotorStopNotification",
fcmToken, // FCM tokens
hw_Id, // Motor ID
inputConnection.water_level || 0, // Water level
motorTank.blockName || "N/A", // Block name
tankName, // Tank name
inputConnection.motor_on_type // Motor on type
);
} catch (error) {
console.error('Error emitting motor stop notification:', error);
}
}
await motorTank.save();
await motorTank.save(); // Save the updated tank
}
console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name

@ -55,6 +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" },
auto_mode_type: { type: String, default: "default" },
notificationSentCritical: { type: Boolean },
notificationSentVeryLow: { type: Boolean },
notificationSentLow: { type: Boolean },
@ -63,6 +64,7 @@ const tanksSchema = new mongoose.Schema({
notificationSentHigh: { type: Boolean },
all_motor_status: { type: Boolean },
connections: {
source: { type: String },
inputConnections: [

@ -821,13 +821,54 @@ module.exports = function (fastify, opts, next) {
handler: tanksController.deletemotordatarecordsbefore7days,
});
fastify.get("/api/getTankmotordata", {
// fastify.get("/api/getTankmotordata", {
// schema: {
// tags: ["Tank"],
// description: "This is for Get Tank Motor Data",
// summary: "This is for to Get Tank Motor Data",
// querystring: {
// customerId: {type: 'string'}
// },
// security: [
// {
// basicAuth: [],
// },
// ],
// },
// preHandler: fastify.auth([fastify.authenticate]),
// handler: tanksController.getTankmotordata,
// });
fastify.route({
method: "PUT",
url: "/api/getTankmotordata/:customerId",
schema: {
tags: ["Tank"],
description: "This is for Get Tank Motor Data",
summary: "This is for to Get Tank Motor Data",
querystring: {
customerId: {type: 'string'}
summary: "This is for Get Tank Motor Data",
params: {
required: ["customerId"],
type: "object",
properties: {
customerId: {
type: "string",
description: "customerId",
},
},
},
body: {
type: "object",
// required: ['phone'],
properties: {
startDate:{ type: "string" },
stopDate:{type:"string"},
block:{type:"string"},
},
},
security: [
{
@ -835,7 +876,7 @@ module.exports = function (fastify, opts, next) {
},
],
},
preHandler: fastify.auth([fastify.authenticate]),
//preHandler: fastify.auth([fastify.authenticate]),
handler: tanksController.getTankmotordata,
});
@ -843,6 +884,7 @@ module.exports = function (fastify, opts, next) {
fastify.post('/api/motor/write', {
schema: {
tags: ["Tank"],
@ -1070,6 +1112,7 @@ module.exports = function (fastify, opts, next) {
auto_min_percentage: { type: "string", default: null },
auto_max_percentage: { type: "string", default: null },
tankLocation: { type: "string", default: null },
auto_mode_type: { type: "string", default: "default" },
},
},

Loading…
Cancel
Save