From 023a1398efb2aacf8ca479365d8bbb077d68e96c Mon Sep 17 00:00:00 2001 From: Varun Date: Wed, 8 Jan 2025 10:54:49 +0530 Subject: [PATCH] changes in mqtt and added get sensors of particular store --- src/controllers/storeController.js | 24 +++ src/controllers/tanksController.js | 273 +++++++++++++---------------- src/routes/storeRoute.js | 29 +++ 3 files changed, 172 insertions(+), 154 deletions(-) diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index a2893398..82d85639 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -1290,6 +1290,30 @@ exports.getbatchnumbers = async (req, reply) => { }; +exports.getiots = async (req, reply) => { + try { + const storeId = req.params.storeId; + let type = req.params.type ? req.params.type.toUpperCase() : null; // Convert type to uppercase + + let query = { storeId: storeId }; + + if (type !== "ALL") { + query.type = type; + } + + // Fetch data based on the query + const result = await Insensors.find(query); + + if (!result || result.length === 0) { + return reply.send({ status_code: 404, error: "not found" }); + } + + reply.send({ status_code: 200, data: result }); + } catch (err) { + throw boom.boomify(err); + } +}; + exports.getusersofParticularInstaller = async (req, reply) => { try { await User.find({installationId: req.query.InstallerId}) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 5ff0c1ef..64094233 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -4622,199 +4622,164 @@ exports.getBlockData = async (req, reply) => { - const mqtt = require('mqtt'); -// Temporary generic client ID to start -let client; -let isConnected = false; -const connectToBroker = (hw_Id) => { - if (!client) { - client = mqtt.connect('mqtt://35.207.198.4:1883', { clientId: `iot-client-${hw_Id}` }); - +const activeClients = {}; // Store unique clients by hw_Id + +// Connect and process message for a specific hardware ID +const connectAndProcessMessage = (hw_Id, data) => { + if (!activeClients[hw_Id]) { + const client = mqtt.connect('mqtt://35.207.198.4:1883', { clientId: `iot-client-${hw_Id}` }); + activeClients[hw_Id] = client; + client.on('connect', () => { - isConnected = true; - console.log(`Connected to MQTT broker as client iot-client-${hw_Id}`); + console.log(`Connected to MQTT broker for hw_Id: ${hw_Id}`); client.subscribe('water/iot-data', { qos: 1 }, (err) => { if (err) { - console.error('Error subscribing to topic:', err); - } else { - console.log('Subscribed to water/iot-data topic'); + console.error('Error subscribing for hw_Id:', hw_Id, err); } }); }); client.on('close', () => { - isConnected = false; - console.log('Disconnected from MQTT broker'); + console.log(`Disconnected MQTT client for hw_Id: ${hw_Id}`); + delete activeClients[hw_Id]; + }); + + client.on('error', (err) => { + console.error(`Error for hw_Id ${hw_Id}:`, err); }); } + + processIoTData(hw_Id, data); }; -// Handling incoming MQTT messages -client = mqtt.connect('mqtt://35.207.198.4:1883', { clientId: `temp-client-${Math.random().toString(16).slice(2, 10)}` }); +// Process IoT data and update database +const processIoTData = async (hw_Id, data) => { + console.log(`Processing data for hw_Id: ${hw_Id}`, data); + const currentDate = new Date(); + const date = currentDate.toISOString(); + const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); + + const tankDocuments = data.objects.tanks.map(tank => ({ + tankhardwareId: tank.Id, + tankHeight: tank.level, + date, + time + })); + + const iotTankData = new IotData({ + hardwareId: hw_Id, + Motor_status: data.objects.Motor_status, + tanks: tankDocuments, + date, + time + }); + + await iotTankData.save(); + + 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(); + } -client.on('connect', () => { - console.log('Connected temporarily to MQTT broker'); - client.subscribe('water/iot-data', { qos: 1 }); -}); + for (const tank of data.objects.tanks) { + const { Id: tankhardwareId, level: tankHeight } = tank; + const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId }); + if (!existingTank) continue; -// Handling incoming MQTT messages -client.on('message', async (topic, message) => { - console.log(`Message received on topic ${topic}:`, message.toString()); + const customerId = existingTank.customerId; + const tank_name = existingTank.tankName; - 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 - if (!isConnected) { - connectToBroker(hw_Id); // Reconnect with the correct hw_Id - } + const tankHeightInCm = parseInt(existingTank.height.replace(/,/g, ''), 10) * 30.48; + const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); + const waterLevelHeight = tank_height - tankHeight; + const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); - // 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 - })); - - // 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(); + const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); - // 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); + if (waterLevel >= 0) { + existingTank.waterlevel = waterLevel; + await existingTank.save(); - for (const record of recordsToDelete) { - await record.remove(); - } - - // 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 - if (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 - } - } + 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 + const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); + if (!motorTank) { + console.log('Motor not found for the specified motor_id'); + return; + } - if (!motorTank) { - console.log('Motor not found for the specified motor_id'); - return; - } + const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); + if (inputConnection) { + inputConnection.motor_status = data.objects.Motor_status; - // 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 - console.log(inputConnection.motor_stop_status,"inputConnection.motor_stop_status") - - if (inputConnection.motor_stop_status === "1" && status === "2") { - console.log("got into forced manual") - console.log(inputConnection.motor_on_type,"before if motor on type") - // Check if motor_on_type is not already "forced_manual" - if (inputConnection.motor_on_type !== "forced_manual") { - inputConnection.motor_on_type = "forced_manual"; - console.log("entered forced manual of if") - inputConnection.motor_stop_status = "2"; - // Update startTime to the current time in the specified format - const currentTime = new Date(); - const formattedTime = currentTime.toLocaleString('en-GB', { - day: '2-digit', - month: 'short', - year: 'numeric', - hour: '2-digit', - minute: '2-digit', - hour12: false, - }).replace(',', ''); - inputConnection.startTime = formattedTime; - } + if (inputConnection.motor_stop_status === "1" && data.objects.Motor_status === "2") { + if (inputConnection.motor_on_type !== "forced_manual") { + inputConnection.motor_on_type = "forced_manual"; + inputConnection.motor_stop_status = "2"; + const formattedTime = new Date().toLocaleString('en-GB', { + day: '2-digit', + month: 'short', + year: 'numeric', + hour: '2-digit', + minute: '2-digit', + hour12: false + }).replace(',', ''); + inputConnection.startTime = formattedTime; } - - - if (inputConnection.motor_stop_status === "2" && status === "1") { - console.log("got into forced manual stop") - console.log(inputConnection.motor_on_type,"before if motor on type stop") - // Check if motor_on_type is not already "forced_manual" - if (inputConnection.motor_on_type = "forced_manual") { - inputConnection.motor_on_type = "manual"; - console.log("entered forced manual of if of stop") - - // Update startTime to the current time in the specified format - - - inputConnection.motor_stop_status = "1"; - } } + if (inputConnection.motor_stop_status === "2" && data.objects.Motor_status === "1") { + if (inputConnection.motor_on_type === "forced_manual") { + inputConnection.motor_on_type = "manual"; + inputConnection.motor_stop_status = "1"; + } + } + await motorTank.save(); + } + console.log('Data processed successfully for hardwareId:', hw_Id); +}; +const mainClient = mqtt.connect('mqtt://35.207.198.4:1883', { clientId: `listener-client-${Date.now()}` }); +mainClient.on('connect', () => { + console.log('Main listener connected'); + mainClient.subscribe('water/iot-data', { qos: 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); - } +mainClient.on('message', (topic, message) => { + if (topic === 'water/iot-data') { + const data = JSON.parse(message.toString()); + const { hw_Id } = data.objects; + connectAndProcessMessage(hw_Id, data); } }); + // Function to publish motor stop status // exports.publishMotorStopStatus = async (motor_id, motor_stop_status) => { // const payload = { diff --git a/src/routes/storeRoute.js b/src/routes/storeRoute.js index 50b48792..705ae5ac 100644 --- a/src/routes/storeRoute.js +++ b/src/routes/storeRoute.js @@ -1138,6 +1138,35 @@ fastify.get("/api/getbatchnumbers/:storeId/:type", { handler: storeController.getbatchnumbers, }); +fastify.get("/api/getiots/:storeId/:type", { + schema: { + tags: ["Store-Data"], + description: "This is to Get iots of particular store", + summary: "This is to iots of particular store", + params: { + type: "object", + properties: { + storeId: { + type: "string", + description: "storeId", + }, + type: { + type: "string", + description: "type", + }, + }, + required: ["storeId", "type"], + }, + security: [ + { + basicAuth: [], + }, + ], + }, + // preHandler: fastify.auth([fastify.authenticate]), + handler: storeController.getiots, +}); + fastify.post("/api/createquotationforSensor/:installationId", { schema: {