Bhaskar 8 months ago
commit 11f5e32c95

@ -352,21 +352,50 @@ exports.getTanksofParticularInstaller = async (req, reply) => {
exports.getTankmotordata = async (req, reply) => { exports.getTankmotordata = async (req, reply) => {
try { try {
await MotorData.find({customerId: req.query.customerId}) const { startDate, stopDate, block } = req.body;
.exec() const { customerId } = req.params;
.then((docs) => { const start = moment(startDate, "DD-MMM-YYYY - HH:mm").toDate();
reply.send({ status_code: 200, data: docs, count: docs.length }); const end = moment(stopDate, "DD-MMM-YYYY - HH:mm").toDate();
})
.catch((err) => { // Fetch the name from the User collection based on customerId, only from profile
console.log(err); const user = await User.findOne({ customerId })
reply.send({ error: err }); .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) { } catch (err) {
throw boom.boomify(err); throw boom.boomify(err);
} }
}; };
exports.updateTanklevels = async (req, reply) => { exports.updateTanklevels = async (req, reply) => {
try { try {
const customerId = req.params.customerId; const customerId = req.params.customerId;
@ -5248,18 +5277,25 @@ exports.update_auto_mode = async (req, reply) => {
exports.update_auto_percentage = async (req, reply) => { exports.update_auto_percentage = async (req, reply) => {
try { try {
const customerId = req.params.customerId; const customerId = req.params.customerId;
const { tankName,tankLocation, auto_min_percentage, auto_max_percentage } = req.body; const { tankName, tankLocation, auto_min_percentage, auto_max_percentage, auto_mode_type } = req.body;
// Update inputConnections' auto_mode
// 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 // Update auto_min_percentage, auto_max_percentage, and auto_mode_type
await Tank.updateOne( await Tank.updateMany(
{ customerId: customerId,tankLocation, tankName}, filter,
{ {
$set: { $set: {
"auto_min_percentage": auto_min_percentage, "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 //storing water level for every 15 minutes
const getFormattedISTTime = () => { const getFormattedISTTime = () => {
@ -5498,9 +5535,7 @@ exports.getBlockData = async (req, reply) => {
// } // }
// }); // });
const mqtt = require('mqtt'); const mqtt = require('mqtt');
const { setMaxIdleHTTPParsers } = require('http');
const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker
client.on('connect', () => { 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 const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name
if (inputConnection) { if (inputConnection) {
inputConnection.motor_status = status; // Update motor status inputConnection.motor_status = status; // Update motor status
const tankName = motorTank.tankName; const tankName = motorTank.tankName;
console.log(tankName,"tankName")
if (inputConnection.motor_stop_status === "1" && status === 2 && inputConnection.motor_on_type !== "forced_manual") { 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'); const currentTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm');
inputConnection.motor_stop_status = "2"; inputConnection.motor_stop_status = "2";
inputConnection.motor_on_type = "forced_manual"; inputConnection.motor_on_type = "forced_manual";
inputConnection.startTime = currentTime; inputConnection.startTime = currentTime;
// Emit motor start notification with tankName // Emit motor start notification with tankName
// eventEmitter.emit( eventEmitter.emit(
// "sendMotorStartNotification", "sendMotorStartNotification",
// fcmToken, // FCM tokens fcmToken, // FCM tokens
// hw_Id, // Motor ID hw_Id, // Motor ID
// inputConnection.water_level || 0, // Water level inputConnection.water_level || 0, // Water level
// motorTank.blockName || "N/A", // Block name motorTank.blockName || "N/A", // Block name
// tankName, // Tank name tankName, // Tank name
// inputConnection.motor_on_type, // Motor on type inputConnection.motor_on_type, // Motor on type
// "threshold", // Stop criteria "threshold", // Stop criteria
// manual_threshold_time // Threshold time in mins 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
); );
} 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"; inputConnection.motor_stop_status = "1";
// Emit motor stop notification with tankName // Emit motor stop notification with tankName
try { eventEmitter.emit(
eventEmitter.emit("sendMotorStopNotification", "sendMotorStopNotification",
fcmToken, fcmToken, // FCM tokens
motorTank.blockName || "N/A", hw_Id, // Motor ID
motorTank.tankName, inputConnection.water_level || 0, // Water level
"Forced Manual", motorTank.blockName || "N/A", // Block name
motorTank.typeOfWater || "Drinking Water" 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 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" }, auto_min_percentage: { type: String, default: "20" },
reserved_percentage: { type: String, default: "20" }, reserved_percentage: { type: String, default: "20" },
auto_max_percentage: { type: String, default: "80" }, auto_max_percentage: { type: String, default: "80" },
auto_mode_type: { type: String, default: "default" },
notificationSentCritical: { type: Boolean }, notificationSentCritical: { type: Boolean },
notificationSentVeryLow: { type: Boolean }, notificationSentVeryLow: { type: Boolean },
notificationSentLow: { type: Boolean }, notificationSentLow: { type: Boolean },
@ -63,6 +64,7 @@ const tanksSchema = new mongoose.Schema({
notificationSentHigh: { type: Boolean }, notificationSentHigh: { type: Boolean },
all_motor_status: { type: Boolean }, all_motor_status: { type: Boolean },
connections: { connections: {
source: { type: String }, source: { type: String },
inputConnections: [ inputConnections: [

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

Loading…
Cancel
Save