diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index b89edb99..fc37403a 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1086,10 +1086,7 @@ exports.consumption = async (request, reply) => { const total_water_added_from_midnight = parseInt(tank.total_water_added_from_midnight.replace(/,/g, ''), 10); const waterlevel = parseInt(tank.waterlevel.replace(/,/g, ''), 10); const tankname = tank.tankName; - const capacity = tank.capacity - - - + const capacity = parseInt(tank.capacity.replace(/,/g, ''), 10); const tankConsumptions = await TankConsumptionOriginalSchema.find({ customerId, @@ -1130,11 +1127,13 @@ exports.consumption = async (request, reply) => { waterlevel: tank.waterlevel }); } - + const totalConsumptionPercentage = ((totalConsumptionForSelectedBlockAndTypeOfWater / totalCapacityForSelectedBlockAndTypeOfWater) * 100).toFixed(2) ; + // Include the total consumption in the response const response = { status_code: 200, tankData,consumptiorecordsdatewise:tankconsumptionData, + totalConsumptionPercentage:totalConsumptionPercentage, [`total consumption of ${typeofwater} and selected block`]: totalConsumptionForSelectedBlockAndTypeOfWater }; @@ -4894,165 +4893,298 @@ exports.getBlockData = async (req, reply) => { -const mqtt = require('mqtt'); -// const moment = require('moment-timezone'); -// const IotData = require('./models/IotData'); // Replace with your actual model -// const Tank = require('./models/Tank'); // Replace with your actual model - -// A map to keep track of MQTT clients by hw_Id -const mqttClients = new Map(); - -// Function to create a new MQTT client for a specific hw_Id -function createMqttClient(hw_Id) { - const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to the MQTT broker - - client.on('connect', () => { - console.log(`Client for hw_Id ${hw_Id} connected to MQTT broker`); - client.subscribe('water/iot-data', (err) => { - if (err) { - console.error(`Error subscribing to topic for hw_Id ${hw_Id}:`, err); - } else { - console.log(`Client for hw_Id ${hw_Id} subscribed to water/iot-data topic`); - } - }); - }); +// const mqtt = require('mqtt'); +// // const moment = require('moment-timezone'); +// // const IotData = require('./models/IotData'); // Replace with your actual model +// // const Tank = require('./models/Tank'); // Replace with your actual model - client.on('message', async (topic, message) => { - if (topic === 'water/iot-data') { - try { - const data = JSON.parse(message.toString()); - const { hw_Id: receivedHwId, Motor_status, tanks } = data.objects; - - // Ensure we process data only for the current client - if (receivedHwId !== hw_Id) return; - - // Get the current date and time - 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 tank documents for the received tanks - const tankDocuments = tanks.map(tank => ({ - tankhardwareId: tank.Id, - tankHeight: tank.level, - date, - time - })); - - // Save IoT data - const iotTankData = new IotData({ - hardwareId: receivedHwId, - Motor_status, - tanks: tankDocuments, - date, - time - }); - await iotTankData.save(); +// // A map to keep track of MQTT clients by hw_Id +// const mqttClients = new Map(); - // Delete excess records (keep only the latest three) - const recordsToKeep = 3; - const recordsToDelete = await IotData.find({ hardwareId: receivedHwId }) - .sort({ date: -1, time: -1 }) - .skip(recordsToKeep); +// // Function to create a new MQTT client for a specific hw_Id +// function createMqttClient(hw_Id) { +// const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to the MQTT broker - for (const record of recordsToDelete) { - await record.remove(); - } +// client.on('connect', () => { +// console.log(`Client for hw_Id ${hw_Id} connected to MQTT broker`); +// client.subscribe('water/iot-data', (err) => { +// if (err) { +// console.error(`Error subscribing to topic for hw_Id ${hw_Id}:`, err); +// } else { +// console.log(`Client for hw_Id ${hw_Id} subscribed to water/iot-data topic`); +// } +// }); +// }); + +// client.on('message', async (topic, message) => { +// if (topic === 'water/iot-data') { +// try { +// const data = JSON.parse(message.toString()); +// const { hw_Id: receivedHwId, Motor_status, tanks } = data.objects; + +// // Ensure we process data only for the current client +// if (receivedHwId !== hw_Id) return; + +// // Get the current date and time +// 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 tank documents for the received tanks +// const tankDocuments = tanks.map(tank => ({ +// tankhardwareId: tank.Id, +// tankHeight: tank.level, +// date, +// time +// })); + +// // Save IoT data +// const iotTankData = new IotData({ +// hardwareId: receivedHwId, +// Motor_status, +// tanks: tankDocuments, +// date, +// time +// }); +// await iotTankData.save(); - // Process tanks - for (const tank of tanks) { - const { Id: tankhardwareId, level: tankHeight } = tank; - const existingTank = await Tank.findOne({ hardwareId: receivedHwId, tankhardwareId }); - if (!existingTank) continue; - - const customerId = existingTank.customerId; - const tank_name = existingTank.tankName; - - 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); - - const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); - - if (tankHeight > 0 && waterLevel >= 0) { - existingTank.waterlevel = waterLevel; - await existingTank.save(); - - 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(); - } - } - } - } - } - } +// // Delete excess records (keep only the latest three) +// const recordsToKeep = 3; +// const recordsToDelete = await IotData.find({ hardwareId: receivedHwId }) +// .sort({ date: -1, time: -1 }) +// .skip(recordsToKeep); - // Update motor status - const status = Motor_status; - const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": receivedHwId }); - - if (motorTank) { - const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === receivedHwId); - if (inputConnection) { - inputConnection.motor_status = status; - 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; - } +// for (const record of recordsToDelete) { +// await record.remove(); +// } - if (inputConnection.motor_stop_status === "2" && status === 1) { - inputConnection.motor_stop_status = "1"; - } +// // Process tanks +// for (const tank of tanks) { +// const { Id: tankhardwareId, level: tankHeight } = tank; +// const existingTank = await Tank.findOne({ hardwareId: receivedHwId, tankhardwareId }); +// if (!existingTank) continue; + +// const customerId = existingTank.customerId; +// const tank_name = existingTank.tankName; + +// 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); + +// const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); + +// if (tankHeight > 0 && waterLevel >= 0) { +// existingTank.waterlevel = waterLevel; +// await existingTank.save(); + +// 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(); +// } +// } +// } +// } +// } +// } - await motorTank.save(); - } - } +// // Update motor status +// const status = Motor_status; +// const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": receivedHwId }); + +// if (motorTank) { +// const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === receivedHwId); +// if (inputConnection) { +// inputConnection.motor_status = status; +// 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; +// } - console.log(`Data processed successfully for hw_Id: ${receivedHwId}`); - } catch (err) { - console.error(`Error processing message for hw_Id ${hw_Id}:`, err.message); - } - } - }); +// if (inputConnection.motor_stop_status === "2" && status === 1) { +// inputConnection.motor_stop_status = "1"; +// } - return client; -} +// await motorTank.save(); +// } +// } + +// console.log(`Data processed successfully for hw_Id: ${receivedHwId}`); +// } catch (err) { +// console.error(`Error processing message for hw_Id ${hw_Id}:`, err.message); +// } +// } +// }); -// Handle incoming MQTT messages for water/iot-data topic -const mainClient = mqtt.connect('mqtt://35.207.198.4:1883'); -mainClient.on('connect', () => { - console.log('Main client connected to MQTT broker'); - mainClient.subscribe('water/iot-data', (err) => { +// return client; +// } + +// // Handle incoming MQTT messages for water/iot-data topic +// const mainClient = mqtt.connect('mqtt://35.207.198.4:1883'); +// mainClient.on('connect', () => { +// console.log('Main client connected to MQTT broker'); +// mainClient.subscribe('water/iot-data', (err) => { +// if (err) { +// console.error('Error subscribing to water/iot-data topic:', err); +// } +// }); +// }); + +// mainClient.on('message', (topic, message) => { +// if (topic === 'water/iot-data') { +// try { +// const data = JSON.parse(message.toString()); +// const { hw_Id } = data.objects; + +// if (!mqttClients.has(hw_Id)) { +// const client = createMqttClient(hw_Id); +// mqttClients.set(hw_Id, client); +// } +// } catch (err) { +// console.error('Error handling message in main client:', err.message); +// } +// } +// }); + + +const mqtt = require('mqtt'); +const client = mqtt.connect('mqtt://35.207.198.4:1883'); // Connect to MQTT broker + +client.on('connect', () => { + console.log('Connected to MQTT broker'); + client.subscribe('water/iot-data', (err) => { if (err) { - console.error('Error subscribing to water/iot-data topic:', err); + console.error('Error subscribing to topic:', err); + } else { + console.log('Subscribed to water/iot-data topic'); } }); }); -mainClient.on('message', (topic, message) => { +// Handling incoming MQTT messages +client.on('message', async (topic, message) => { + console.log(`Message received on topic ${topic}:`, message.toString()); + if (topic === 'water/iot-data') { try { const data = JSON.parse(message.toString()); - const { hw_Id } = data.objects; + 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 + })); + + + + // 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(); - if (!mqttClients.has(hw_Id)) { - const client = createMqttClient(hw_Id); - mqttClients.set(hw_Id, client); + // 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); + + 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 + 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 + } + } + } + } + } + } + + // Update motor status + const status = Motor_status; + const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); // Updated variable name + + 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 + 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; + } + + if (inputConnection.motor_stop_status === "2" && 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 handling message in main client:', err.message); + console.error('Error processing message:', err.message); } } });