master^2
Bhaskar 6 months ago
parent 0c2d6bb04d
commit 3804e908ca

@ -1298,112 +1298,200 @@ exports.getMasterSlaveSummary = async (req, reply) => {
// }; // };
exports.getIotDataByCustomer = async (req, reply) => {
try {
const { customerId } = req.params;
if (!customerId) {
return reply.code(400).send({ error: "customerId is required" });
}
// Fetch all sensors for the customer
const sensors = await Insensors.find({ customerId });
if (!sensors || sensors.length === 0) {
return reply.code(404).send({ message: "No sensors found for this customer." });
}
// Extract unique hardwareIds that are connected to sensors
const hardwareIds = [
...new Set(
sensors.map(sensor => sensor.connected_to?.trim()).filter(Boolean)
)
];
if (hardwareIds.length === 0) {
return reply.send({ status_code: 200, message: "No connected hardwareIds found", data: [] });
}
// Fetch the latest IoT data and enrich it with sensor details
const latestDataPromises = hardwareIds.map(async hardwareId => {
// Fetch the latest IoT data for this hardwareId
const latestRecord = await IotData.findOne({ hardwareId })
.sort({ date: -1 }) // Sorting to get the latest record based on the date
.lean();
// If no IoT data is found for this hardwareId, return a placeholder
if (!latestRecord) {
return {
hardwareId,
message: "No IoT data found",
tanks: []
};
}
// Find sensors related to this hardwareId
const relatedSensors = sensors.filter(sensor => sensor.connected_to?.trim() === hardwareId);
// Check if this hardwareId is "disconnected" in Insensors (based on your logic, e.g., isConnected=false)
const isDisconnected = relatedSensors.some(sensor => sensor.isConnected === false); // You can adjust this check based on your schema.
// Default message for GSM connection status
let message = isDisconnected ? "GSM is disconnected" : "GSM is not connected";
// If any tank data has height > 0, assume GSM is connected, overriding the disconnected state
if (latestRecord?.tanks?.some(tank => parseFloat(tank.tankHeight || 0) > 0)) {
message = "GSM is connected";
}
// Enrich each tank with the IoT data
const tanksStatus = relatedSensors.map(sensor => {
const tankhardwareId = sensor.hardwareId?.trim();
const matchedTank = latestRecord?.tanks?.find(
tank => tank.tankhardwareId === tankhardwareId
);
// Check if LoRa is connected based on the tankHeight
const loraMessage =
matchedTank && parseFloat(matchedTank.tankHeight || 0) > 0
? "LORA is connected"
: "LORA is not connected";
return {
tankhardwareId,
tankName: sensor.tankName ?? null,
tankLocation: sensor.tankLocation ?? null,
masterName: sensor.masterName ?? null,
location: sensor.location ?? null,
loraMessage,
latestTankData: matchedTank || null
};
});
return {
hardwareId,
message,
masterName: relatedSensors[0]?.masterName ?? null,
location: relatedSensors[0]?.location ?? null,
tanks: tanksStatus
};
});
// Wait for all promises to resolve to gather all the enriched data
const iotDataGrouped = await Promise.all(latestDataPromises);
// Return the final response
return reply.send({
status_code: 200,
message: "Success",
data: iotDataGrouped
});
} catch (err) {
console.error("Error fetching IoT data by customerId:", err);
return reply.code(500).send({ error: "Internal Server Error" });
}
};
//important
// exports.getIotDataByCustomer = async (req, reply) => { // exports.getIotDataByCustomer = async (req, reply) => {
// try { // try {
// const { customerId } = req.params; // const { customerId } = req.params;
// if (!customerId) { // if (!customerId) {
// return reply.code(400).send({ error: "customerId is required" }); // return reply.status(400).send({ error: "customerId is required" });
// } // }
// // Fetch all sensors for the customer // console.log("Fetching data for customerId:", customerId);
// // Step 1: Fetch all sensors for the customer
// const sensors = await Insensors.find({ customerId }); // const sensors = await Insensors.find({ customerId });
// if (!sensors || sensors.length === 0) { // if (!sensors || sensors.length === 0) {
// return reply.code(404).send({ message: "No sensors found for this customer." }); // return reply.send({ status_code: 404, message: "No sensors found for this customer", data: [] });
// } // }
// // Extract unique hardwareIds that are connected to sensors // // Step 2: Fetch latest IoT data for each sensor's hardwareId
// const hardwareIds = [ // const enrichedSensors = await Promise.all(sensors.map(async (sensor) => {
// ...new Set( // const { connected_to: hardwareId, masterName, location } = sensor;
// sensors.map(sensor => sensor.connected_to?.trim()).filter(Boolean)
// )
// ];
// if (hardwareIds.length === 0) {
// return reply.send({ status_code: 200, message: "No connected hardwareIds found", data: [] });
// }
// // Fetch the latest IoT data and enrich it with sensor details
// const latestDataPromises = hardwareIds.map(async hardwareId => {
// // Fetch the latest IoT data for this hardwareId // // Fetch the latest IoT data for this hardwareId
// const latestRecord = await IotData.findOne({ hardwareId }) // const iotData = await IotData.findOne({ hardwareId })
// .sort({ date: -1 }) // Sorting to get the latest record based on the date // .sort({ date: -1 }) // Sort to get the latest data
// .lean(); // .lean();
// // If no IoT data is found for this hardwareId, return a placeholder // if (!iotData) {
// if (!latestRecord) {
// return { // return {
// hardwareId, // hardwareId,
// message: "No IoT data found", // message: "No IoT data found",
// masterName,
// location,
// tanks: [] // tanks: []
// }; // };
// } // }
// // Find sensors related to this hardwareId // // Step 3: Get GSM status based on the latest IoT data
// const relatedSensors = sensors.filter(sensor => sensor.connected_to?.trim() === hardwareId); // const latestRecord = iotData;
// const indiaTime = moment.tz(latestRecord.date, "Asia/Kolkata");
// // Check if this hardwareId is "disconnected" in Insensors (based on your logic, e.g., isConnected=false) // const connected_gsm_date = indiaTime.format("YYYY-MM-DD");
// const isDisconnected = relatedSensors.some(sensor => sensor.isConnected === false); // You can adjust this check based on your schema. // const connected_gsm_time = indiaTime.format("HH:mm:ss");
// // Default message for GSM connection status
// let message = isDisconnected ? "GSM is disconnected" : "GSM is not connected";
// // If any tank data has height > 0, assume GSM is connected, overriding the disconnected state
// if (latestRecord?.tanks?.some(tank => parseFloat(tank.tankHeight || 0) > 0)) {
// message = "GSM is connected";
// }
// // Enrich each tank with the IoT data // const now = moment.tz("Asia/Kolkata");
// const tanksStatus = relatedSensors.map(sensor => { // const diffInMinutes = now.diff(indiaTime, "minutes");
// const tankhardwareId = sensor.hardwareId?.trim(); // const isGSMConnected = diffInMinutes <= 1;
// const matchedTank = latestRecord?.tanks?.find( // const gsmStatus = isGSMConnected ? "GSM Connected" : "GSM Not Connected";
// tank => tank.tankhardwareId === tankhardwareId
// );
// // Check if LoRa is connected based on the tankHeight // // Step 4: Annotate each tank with LoRa connection status
// const loraMessage = // const tanksWithConnectionStatus = latestRecord.tanks.map(tank => {
// matchedTank && parseFloat(matchedTank.tankHeight || 0) > 0 // const tankMoment = moment.tz(tank.date, "Asia/Kolkata");
// ? "LORA is connected" // const tankDiff = now.diff(tankMoment, "minutes");
// : "LORA is not connected";
// const loraStatus = tankDiff <= 1 ? "LORA is connected" : "LORA is not connected";
// return { // return {
// tankhardwareId, // tankhardwareId: tank.tankhardwareId,
// tankName: sensor.tankName ?? null, // tankName: sensor.tankName ?? null,
// tankLocation: sensor.tankLocation ?? null, // tankLocation: sensor.tankLocation ?? null,
// masterName: sensor.masterName ?? null, // masterName: sensor.masterName ?? null,
// location: sensor.location ?? null, // location: sensor.location ?? null,
// loraMessage, // loraMessage: loraStatus,
// latestTankData: matchedTank || null // latestTankData: tank
// }; // };
// }); // });
// // Step 5: Return enriched sensor data in the desired format
// return { // return {
// hardwareId, // hardwareId,
// message, // message: gsmStatus,
// masterName: relatedSensors[0]?.masterName ?? null, // masterName,
// location: relatedSensors[0]?.location ?? null, // location,
// tanks: tanksStatus // tanks: tanksWithConnectionStatus
// }; // };
// }); // }));
// // Wait for all promises to resolve to gather all the enriched data
// const iotDataGrouped = await Promise.all(latestDataPromises);
// // Return the final response // // Step 6: Return the enriched data for the customer
// return reply.send({ // return reply.send({
// status_code: 200, // status_code: 200,
// message: "Success", // message: "Success",
// data: iotDataGrouped // data: enrichedSensors
// }); // });
// } catch (err) { // } catch (err) {
// console.error("Error fetching IoT data by customerId:", err); // console.error("Error in getAllDataForCustomer:", err);
// return reply.code(500).send({ error: "Internal Server Error" }); // return reply.status(500).send({ error: "Internal Server Error" });
// } // }
// }; // };
//important
// exports.getIotDataByCustomer = async (req, reply) => { // exports.getIotDataByCustomer = async (req, reply) => {
// try { // try {
// const { customerId } = req.params; // const { customerId } = req.params;
@ -1452,7 +1540,7 @@ exports.getMasterSlaveSummary = async (req, reply) => {
// const gsmStatus = isGSMConnected ? "GSM Connected" : "GSM Not Connected"; // const gsmStatus = isGSMConnected ? "GSM Connected" : "GSM Not Connected";
// // Step 4: Annotate each tank with LoRa connection status // // Step 4: Annotate each tank with LoRa connection status
// const tanksWithConnectionStatus = latestRecord.tanks.map(tank => { // const tanksWithConnectionStatus = latestRecord.tanks.slice(0, 2).map(tank => { // Limit to 2 tanks
// const tankMoment = moment.tz(tank.date, "Asia/Kolkata"); // const tankMoment = moment.tz(tank.date, "Asia/Kolkata");
// const tankDiff = now.diff(tankMoment, "minutes"); // const tankDiff = now.diff(tankMoment, "minutes");
@ -1490,91 +1578,3 @@ exports.getMasterSlaveSummary = async (req, reply) => {
// return reply.status(500).send({ error: "Internal Server Error" }); // return reply.status(500).send({ error: "Internal Server Error" });
// } // }
// }; // };
exports.getIotDataByCustomer = async (req, reply) => {
try {
const { customerId } = req.params;
if (!customerId) {
return reply.status(400).send({ error: "customerId is required" });
}
console.log("Fetching data for customerId:", customerId);
// Step 1: Fetch all sensors for the customer
const sensors = await Insensors.find({ customerId });
if (!sensors || sensors.length === 0) {
return reply.send({ status_code: 404, message: "No sensors found for this customer", data: [] });
}
// Step 2: Fetch latest IoT data for each sensor's hardwareId
const enrichedSensors = await Promise.all(sensors.map(async (sensor) => {
const { connected_to: hardwareId, masterName, location } = sensor;
// Fetch the latest IoT data for this hardwareId
const iotData = await IotData.findOne({ hardwareId })
.sort({ date: -1 }) // Sort to get the latest data
.lean();
if (!iotData) {
return {
hardwareId,
message: "No IoT data found",
masterName,
location,
tanks: []
};
}
// Step 3: Get GSM status based on the latest IoT data
const latestRecord = iotData;
const indiaTime = moment.tz(latestRecord.date, "Asia/Kolkata");
const connected_gsm_date = indiaTime.format("YYYY-MM-DD");
const connected_gsm_time = indiaTime.format("HH:mm:ss");
const now = moment.tz("Asia/Kolkata");
const diffInMinutes = now.diff(indiaTime, "minutes");
const isGSMConnected = diffInMinutes <= 1;
const gsmStatus = isGSMConnected ? "GSM Connected" : "GSM Not Connected";
// Step 4: Annotate each tank with LoRa connection status
const tanksWithConnectionStatus = latestRecord.tanks.slice(0, 2).map(tank => { // Limit to 2 tanks
const tankMoment = moment.tz(tank.date, "Asia/Kolkata");
const tankDiff = now.diff(tankMoment, "minutes");
const loraStatus = tankDiff <= 1 ? "LORA is connected" : "LORA is not connected";
return {
tankhardwareId: tank.tankhardwareId,
tankName: sensor.tankName ?? null,
tankLocation: sensor.tankLocation ?? null,
masterName: sensor.masterName ?? null,
location: sensor.location ?? null,
loraMessage: loraStatus,
latestTankData: tank
};
});
// Step 5: Return enriched sensor data in the desired format
return {
hardwareId,
message: gsmStatus,
masterName,
location,
tanks: tanksWithConnectionStatus
};
}));
// Step 6: Return the enriched data for the customer
return reply.send({
status_code: 200,
message: "Success",
data: enrichedSensors
});
} catch (err) {
console.error("Error in getAllDataForCustomer:", err);
return reply.status(500).send({ error: "Internal Server Error" });
}
};

Loading…
Cancel
Save