api calculate the time gap between the sensor data

master
varun 3 years ago
parent 02c1276966
commit 3c4a636e65

@ -668,7 +668,7 @@ exports.IotDevice = async (req, reply) => {
// create a new tank document with the current date and time
const currentDate = new Date();
const date = currentDate.toLocaleDateString('en-IN');
const date = currentDate.toISOString(); // save the date as an ISO string
const time = currentDate.toLocaleTimeString('en-IN', {hour12:false, timeZone: 'Asia/Kolkata' });
const tank = new IotData({ hardwareId, tankHeight, maxLevel, minLevel, mode, date, time });
@ -713,3 +713,33 @@ exports.getIotD = async(req, reply) => {
throw boom.boomify(err);
}
}
exports.getLatestData = async (req, reply) => {
try {
const hardwareId = req.params.hardwareId;
// get the latest two tank documents for the current hardwareId sorted in descending order of date and time
const latestTanks = await IotData.find({ hardwareId }).sort({ date: -1, time: -1 }).limit(2);
// if the number of documents for the current hardwareId is less than two, return an error response
if (latestTanks.length < 2) {
return reply.code(404).send({ error: 'Not enough data' });
}
// calculate the time difference between the latest and previous documents
const latestDate = new Date(latestTanks[0].date);
const previousDate = new Date(latestTanks[1].date);
const latestTime = latestTanks[0].time.split('.')[0]; // remove milliseconds
const previousTime = latestTanks[1].time.split('.')[0]; // remove milliseconds
latestDate.setHours(parseInt(latestTime.substring(0, 2)), parseInt(latestTime.substring(3, 5)), parseInt(latestTime.substring(6, 8)));
previousDate.setHours(parseInt(previousTime.substring(0, 2)), parseInt(previousTime.substring(3, 5)), parseInt(previousTime.substring(6, 8)));
const timeDiff = (latestDate.getTime() - previousDate.getTime()) / 1000; // convert from milliseconds to seconds
console.log(latestDate,previousDate,latestTime,previousTime,timeDiff)
reply.code(200).send({ timeDiff });
} catch (err) {
// send an error response
reply.code(500).send({ error: err.message });
}
};

@ -372,6 +372,35 @@ module.exports = function (fastify, opts, next) {
handler: tanksController.getIotD,
});
fastify.route({
method: "GET",
url: "/api/calculateTimedifference/:hardwareId",
schema: {
tags: ["Tank"],
summary: "This is for calculating the time gap between iot data",
params: {
required: ["hardwareId"],
type: "object",
properties: {
hardwareId: {
type: "string",
description: "hardwareId",
},
},
},
// querystring: {
// tankName: {type: 'string'}
// },
security: [
{
basicAuth: [],
},
],
},
preHandler: fastify.auth([fastify.authenticate]),
handler: tanksController.getLatestData,
});
next();
}

Loading…
Cancel
Save