changes in mqtt and added get sensors of particular store

master
Varun 9 months ago
parent 5c7ab91a5e
commit 023a1398ef

@ -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) => { exports.getusersofParticularInstaller = async (req, reply) => {
try { try {
await User.find({installationId: req.query.InstallerId}) await User.find({installationId: req.query.InstallerId})

@ -4622,82 +4622,65 @@ exports.getBlockData = async (req, reply) => {
const mqtt = require('mqtt'); const mqtt = require('mqtt');
// Temporary generic client ID to start
let client;
let isConnected = false;
const connectToBroker = (hw_Id) => { const activeClients = {}; // Store unique clients by hw_Id
if (!client) {
client = mqtt.connect('mqtt://35.207.198.4:1883', { clientId: `iot-client-${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', () => { client.on('connect', () => {
isConnected = true; console.log(`Connected to MQTT broker for hw_Id: ${hw_Id}`);
console.log(`Connected to MQTT broker as client iot-client-${hw_Id}`);
client.subscribe('water/iot-data', { qos: 1 }, (err) => { client.subscribe('water/iot-data', { qos: 1 }, (err) => {
if (err) { if (err) {
console.error('Error subscribing to topic:', err); console.error('Error subscribing for hw_Id:', hw_Id, err);
} else {
console.log('Subscribed to water/iot-data topic');
} }
}); });
}); });
client.on('close', () => { client.on('close', () => {
isConnected = false; console.log(`Disconnected MQTT client for hw_Id: ${hw_Id}`);
console.log('Disconnected from MQTT broker'); delete activeClients[hw_Id];
}); });
}
};
// Handling incoming MQTT messages
client = mqtt.connect('mqtt://35.207.198.4:1883', { clientId: `temp-client-${Math.random().toString(16).slice(2, 10)}` });
client.on('connect', () => { client.on('error', (err) => {
console.log('Connected temporarily to MQTT broker'); console.error(`Error for hw_Id ${hw_Id}:`, err);
client.subscribe('water/iot-data', { qos: 1 });
}); });
// 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, Motor_status, tanks } = data.objects; // Updated variable names according to new format
if (!isConnected) {
connectToBroker(hw_Id); // Reconnect with the correct hw_Id
} }
// Get the current date and time in the required format processIoTData(hw_Id, data);
};
// 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 currentDate = new Date();
const date = currentDate.toISOString(); // ISO string for date const date = currentDate.toISOString();
const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' }); // Time in 'HH:MM:SS' const time = currentDate.toLocaleTimeString('en-IN', { hour12: false, timeZone: 'Asia/Kolkata' });
// Create array of tank documents with current date and time const tankDocuments = data.objects.tanks.map(tank => ({
const tankDocuments = tanks.map(tank => ({ tankhardwareId: tank.Id,
tankhardwareId: tank.Id, // Updated to match the new format tankHeight: tank.level,
tankHeight: tank.level, // Updated to match the new format
date, date,
time time
})); }));
// Save IoT data for the received tanks
const iotTankData = new IotData({ const iotTankData = new IotData({
hardwareId: hw_Id, // Updated variable name hardwareId: hw_Id,
Motor_status, Motor_status: data.objects.Motor_status,
tanks: tankDocuments, tanks: tankDocuments,
date, date,
time time
}); });
await iotTankData.save(); await iotTankData.save();
// Delete excess records (keep only the latest three records)
const recordsToKeep = 3; const recordsToKeep = 3;
const recordsToDelete = await IotData.find({ hardwareId: hw_Id }) // Updated variable name const recordsToDelete = await IotData.find({ hardwareId: hw_Id })
.sort({ date: -1, time: -1 }) .sort({ date: -1, time: -1 })
.skip(recordsToKeep); .skip(recordsToKeep);
@ -4705,37 +4688,36 @@ client.on('message', async (topic, message) => {
await record.remove(); await record.remove();
} }
// Process each tank to update water level and connections for (const tank of data.objects.tanks) {
for (const tank of tanks) { const { Id: tankhardwareId, level: tankHeight } = tank;
const { Id: tankhardwareId, level: tankHeight } = tank; // Updated to match the new format const existingTank = await Tank.findOne({ hardwareId: hw_Id, tankhardwareId });
// 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; if (!existingTank) continue;
const customerId = existingTank.customerId; const customerId = existingTank.customerId;
const tank_name = existingTank.tankName; const tank_name = existingTank.tankName;
// Calculate water level using tank height and capacity const tankHeightInCm = parseInt(existingTank.height.replace(/,/g, ''), 10) * 30.48;
const tankHeightInCm = (parseInt(existingTank.height.replace(/,/g, ''), 10)) * 30.48; // Convert height to cm
const tank_height = parseInt(tankHeightInCm.toFixed(0), 10); const tank_height = parseInt(tankHeightInCm.toFixed(0), 10);
const waterLevelHeight = tank_height - tankHeight; const waterLevelHeight = tank_height - tankHeight;
const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10); const waterCapacityPerCm = parseInt(existingTank.waterCapacityPerCm.replace(/,/g, ''), 10);
const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10); // Calculated water level const waterLevel = parseInt(waterLevelHeight * waterCapacityPerCm, 10);
// Update water level in the existing tank
if (waterLevel >= 0) { if (waterLevel >= 0) {
existingTank.waterlevel = waterLevel; existingTank.waterlevel = waterLevel;
await existingTank.save(); await existingTank.save();
// Update linked tanks (input/output connections)
for (const outputConnection of existingTank.connections.outputConnections) { for (const outputConnection of existingTank.connections.outputConnections) {
const linkedTank = await Tank.findOne({ customerId, tankName: outputConnection.outputConnections, tankLocation: outputConnection.output_type }); const linkedTank = await Tank.findOne({
customerId,
tankName: outputConnection.outputConnections,
tankLocation: outputConnection.output_type
});
if (linkedTank) { if (linkedTank) {
for (const inputConnection of linkedTank.connections.inputConnections) { for (const inputConnection of linkedTank.connections.inputConnections) {
if (inputConnection.inputConnections === tank_name) { if (inputConnection.inputConnections === tank_name) {
inputConnection.water_level = waterLevel; // Update water level for linked tank inputConnection.water_level = waterLevel;
await linkedTank.save(); // Save updated linked tank await linkedTank.save();
} }
} }
} }
@ -4743,78 +4725,61 @@ client.on('message', async (topic, message) => {
} }
} }
// Update motor status const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id });
const status = Motor_status;
const motorTank = await Tank.findOne({ "connections.inputConnections.motor_id": hw_Id }); // Updated variable name
if (!motorTank) { if (!motorTank) {
console.log('Motor not found for the specified motor_id'); console.log('Motor not found for the specified motor_id');
return; return;
} }
// Find the inputConnection for the motor and update motor status const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id);
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 = data.objects.Motor_status;
console.log(inputConnection.motor_stop_status,"inputConnection.motor_stop_status")
if (inputConnection.motor_stop_status === "1" && status === "2") { if (inputConnection.motor_stop_status === "1" && data.objects.Motor_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") { if (inputConnection.motor_on_type !== "forced_manual") {
inputConnection.motor_on_type = "forced_manual"; inputConnection.motor_on_type = "forced_manual";
console.log("entered forced manual of if")
inputConnection.motor_stop_status = "2"; inputConnection.motor_stop_status = "2";
// Update startTime to the current time in the specified format const formattedTime = new Date().toLocaleString('en-GB', {
const currentTime = new Date();
const formattedTime = currentTime.toLocaleString('en-GB', {
day: '2-digit', day: '2-digit',
month: 'short', month: 'short',
year: 'numeric', year: 'numeric',
hour: '2-digit', hour: '2-digit',
minute: '2-digit', minute: '2-digit',
hour12: false, hour12: false
}).replace(',', ''); }).replace(',', '');
inputConnection.startTime = formattedTime; inputConnection.startTime = formattedTime;
} }
} }
if (inputConnection.motor_stop_status === "2" && data.objects.Motor_status === "1") {
if (inputConnection.motor_stop_status === "2" && status === "1") { if (inputConnection.motor_on_type === "forced_manual") {
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"; 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"; 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 });
});
mainClient.on('message', (topic, message) => {
if (topic === 'water/iot-data') {
const data = JSON.parse(message.toString());
const { hw_Id } = data.objects;
await motorTank.save(); // Save the updated tank connectAndProcessMessage(hw_Id, data);
}
console.log('Data processed successfully for hardwareId:', hw_Id); // Updated variable name
} catch (err) {
console.error('Error processing message:', err.message);
}
} }
}); });
// Function to publish motor stop status // Function to publish motor stop status
// exports.publishMotorStopStatus = async (motor_id, motor_stop_status) => { // exports.publishMotorStopStatus = async (motor_id, motor_stop_status) => {
// const payload = { // const payload = {

@ -1138,6 +1138,35 @@ fastify.get("/api/getbatchnumbers/:storeId/:type", {
handler: storeController.getbatchnumbers, 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", { fastify.post("/api/createquotationforSensor/:installationId", {
schema: { schema: {

Loading…
Cancel
Save