From 80a4775e2aa114eb3ed2e827a1846b4e9c72670e Mon Sep 17 00:00:00 2001 From: Varun Date: Tue, 28 Jan 2025 14:37:57 +0530 Subject: [PATCH 1/3] changes in auto mode --- src/controllers/tanksController.js | 248 ++++++++++++++--------------- src/models/tanks.js | 1 + src/routes/tanksRoute.js | 1 + 3 files changed, 119 insertions(+), 131 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 93fed795..2f3a9375 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -4985,18 +4985,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; + 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 - 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 } } ); @@ -5008,6 +5015,7 @@ exports.update_auto_percentage = async (req, reply) => { }; + //storing water level for every 15 minutes const getFormattedISTTime = () => { @@ -5234,164 +5242,142 @@ exports.getBlockData = async (req, reply) => { // } // } // }); - - const mqtt = require('mqtt'); -const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker + +// Connect to MQTT broker +const client = mqtt.connect('mqtt://35.207.198.4:1883'); client.on('connect', () => { console.log('Connected to MQTT broker'); - client.subscribe('water/iot-data', (err) => { + + // Subscribe to all topics under water/iot-data/ + client.subscribe('water/iot-data/#', (err) => { if (err) { console.error('Error subscribing to topic:', err); } else { - console.log('Subscribed to water/iot-data topic'); + console.log('Subscribed to water/iot-data/#'); } }); }); -// Handling incoming MQTT messages +// Handle incoming MQTT messages client.on('message', async (topic, message) => { - console.log(`Message received on topic ${topic}:`, message.toString()); + try { + const data = JSON.parse(message.toString()); + const topicParts = topic.split('/'); // Split the topic to get the hardwareId + const hardwareId = topicParts[2]; // Extract hardwareId from topic - if (topic === 'water/iot-data') { - try { - const data = JSON.parse(message.toString()); - const { hw_Id, Motor_status, tanks } = data.objects; // Updated variable names according to new format - - // Get the current date and time in the required format - const currentDate = new Date(); - const date = currentDate.toISOString(); // ISO string for date - const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); // Time in 'HH:MM:SS' - - // Create array of tank documents with current date and time - const tankDocuments = tanks.map(tank => ({ - tankhardwareId: tank.Id, // Updated to match the new format - tankHeight: tank.level, // Updated to match the new format - date, - time - })); + const { Motor_status, tanks } = data.objects; - + // Process data for the specific device + await processDeviceData(hardwareId, Motor_status, tanks); + } catch (err) { + console.error('Error processing message:', err.message); + } +}); - // Save IoT data for the received tanks - const iotTankData = new IotData({ - hardwareId: hw_Id, // Updated variable name - Motor_status, - tanks: tankDocuments, - date, - time - }); - await iotTankData.save(); +// Function to process data for each device +async function processDeviceData(hw_Id, Motor_status, tanks) { + try { + const currentDate = new Date(); + const date = currentDate.toISOString(); // ISO string for date + const time = moment().tz('Asia/Kolkata').format('HH:mm:ss'); // Time in 'HH:mm:ss' - // Delete excess records (keep only the latest three records) - const recordsToKeep = 3; - const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) // Updated variable name - .sort({ date: -1, time: -1 }) - .skip(recordsToKeep); + // Prepare tank documents + const tankDocuments = tanks.map(tank => ({ + tankhardwareId: tank.Id, + tankHeight: tank.level, + date, + time + })); - for (const record of recordsToDelete) { - await record.remove(); - } + // Save IoT data for the device + const iotTankData = new IotData({ + hardwareId: hw_Id, + Motor_status, + tanks: tankDocuments, + date, + time + }); + await iotTankData.save(); - // Process each tank to update water level and connections - for (const tank of tanks) { - const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format - // Find the corresponding tank in the Tank schema using hardwareId and tankhardwareId - const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); // Updated variable name - if (!existingTank) continue; - - const customerId = existingTank.customerId; - const tank_name = existingTank.tankName; - - // Calculate water level using tank height and capacity - const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; // Convert height to cm - const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); - const waterLevelHeight = tank_height - tankHeight; - const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); - - const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level - - // Update water level in the existing tank - console.log(tankHeight,"this is located in tank controllers at iot-data mqtt sub ") - if (tankHeight>0 && waterLevel >= 0) { - existingTank.waterlevel = waterLevel; - await existingTank.save(); - - // Update linked tanks (input/output connections) - 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 = waterLevel; // Update water level for linked tank - await linkedTank.save(); // Save updated linked tank - } + // Delete excess records (keep only the latest three records) + const recordsToKeep = 3; + const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) + .sort({ date: -1, time: -1 }) + .skip(recordsToKeep); + + for (const record of recordsToDelete) { + await record.remove(); + } + + // Update water levels for tanks + for (const tank of tanks) { + const { Id: tankhardwareId, level: tankHeight } = tank; + + const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); + if (!existingTank) continue; + + const customerId = existingTank.customerId; + const tank_name = existingTank.tankName; + + const tankHeightInCm = parseInt(existingTank.height.replace(/,/g, ''), 10) * 30.48; + const waterLevelHeight = tankHeightInCm - tankHeight; + const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); + const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); + + if (tankHeight > 0 && waterLevel >= 0) { + existingTank.waterlevel = waterLevel; + 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 = waterLevel; + await linkedTank.save(); } } } } } + } - // Update motor status - const status = Motor_status; - const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); // Updated variable name + // Update motor status + const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); + if (motorTank) { + const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); - if (!motorTank) { - console.log('Motor not found for the specified motor_id'); - return; - } - - // Find the inputConnection for the motor and update motor status - 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; - 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_status = Motor_status; + + if (inputConnection.motor_stop_status === "1" && Motor_status === 2 && inputConnection.motor_on_type !== "forced_manual") { 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 - // ); - + inputConnection.startTime = moment().tz('Asia/Kolkata').format('DD-MMM-YYYY - HH:mm'); } - - if (inputConnection.motor_stop_status === "2" && status === 1) { - inputConnection.motor_stop_status = "1"; - // Emit motor stop notification with tankName - // 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 - // ); + if (inputConnection.motor_stop_status === "2" && Motor_status === 1) { + inputConnection.motor_stop_status = "1"; } - - await motorTank.save(); // Save the updated tank - } - console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name - - } catch (err) { - console.error('Error processing message:', err.message); + await motorTank.save(); + } } + + console.log(`Data processed successfully for hardwareId: ${hw_Id}`); + } catch (err) { + console.error(`Error processing data for hardwareId ${hw_Id}:`, err.message); } -}); +} + diff --git a/src/models/tanks.js b/src/models/tanks.js index 31884e11..ad7c5005 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -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 }, diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 0f6acb37..9b52a1b3 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -1070,6 +1070,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" }, }, }, From 2471c903f20159900e2aad93950d02e1a2acdfa4 Mon Sep 17 00:00:00 2001 From: Varun Date: Tue, 28 Jan 2025 14:54:54 +0530 Subject: [PATCH 2/3] changes in motor data --- src/controllers/tanksController.js | 44 +++++++++++++++++++----- src/routes/tanksRoute.js | 54 ++++++++++++++++++++++++++---- 2 files changed, 84 insertions(+), 14 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 2f3a9375..dae6bd1a 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -352,15 +352,43 @@ 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); } diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 9b52a1b3..6ba0858f 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -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"}, + typeofwater:{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"], From 08b6f134d6027673e961555491c13372a4847a95 Mon Sep 17 00:00:00 2001 From: Varun Date: Tue, 28 Jan 2025 14:55:45 +0530 Subject: [PATCH 3/3] changes --- src/controllers/tanksController.js | 1 + src/models/tanks.js | 1 + 2 files changed, 2 insertions(+) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index dae6bd1a..d31b37c1 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -395,6 +395,7 @@ exports.getTankmotordata = async (req, reply) => { }; + exports.updateTanklevels = async (req, reply) => { try { const customerId = req.params.customerId; diff --git a/src/models/tanks.js b/src/models/tanks.js index ad7c5005..d53a79cb 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -64,6 +64,7 @@ const tanksSchema = new mongoose.Schema({ notificationSentHigh: { type: Boolean }, all_motor_status: { type: Boolean }, + connections: { source: { type: String }, inputConnections: [