Skip to content

Commit

Permalink
get camera uptime status every minute (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
khavinshankar authored Jul 28, 2023
1 parent 9f9926d commit b0b1703
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 20 deletions.
68 changes: 49 additions & 19 deletions src/controller/CameraController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,50 @@
import { CameraUtils } from "../utils/CameraUtils.js";
import { catchAsync } from "../utils/catchAsync.js";

var assets = [];
var statuses = [];
var fetchStatusesInterval = null;

const filterStatus = () => {
const MIN_IN_MS = 60000;
statuses = statuses.filter(
(status) => new Date() - new Date(status.time) <= 30 * MIN_IN_MS
);
};

const fetchCameraStatuses = async () => {
filterStatus();

const cameraStatuses = await Promise.all(
assets.map(async (camera) => {
try {
const camParams = CameraController._getCamParams(camera);
const status = await CameraUtils.getStatus({ camParams });

return {
deviceId: camera.hostname,
status: status?.error === "NO error" ? "up" : "down",
};
} catch (error) {
console.error(error);

return {
deviceId: camera.hostname,
status: "down",
};
}
})
);

statuses.push({
time: new Date().toISOString(),
status: cameraStatuses.reduce((acc, curr) => {
acc[curr.deviceId] = curr.status;
return acc;
}, {}),
});
};

export class CameraController {
static _getCamParams = (body) => {
const { hostname, username, password, port } = body;
Expand Down Expand Up @@ -184,27 +228,13 @@ export class CameraController {
* enum: [up, down]
*/
static getCameraStatuses = catchAsync(async (req, res) => {
const cameras = req.body;

const cameraStatuses = await Promise.all(
cameras.map(async (camera) => {
const camParams = this._getCamParams(camera);
const status = await CameraUtils.getStatus({ camParams });
assets = req.body;
await fetchCameraStatuses();

return {
deviceId: camera.hostname,
status: status?.error === "NO error" ? "up" : "down",
};
})
);
clearInterval(fetchStatusesInterval);
fetchStatusesInterval = setInterval(fetchCameraStatuses, 60 * 1000);

return res.json({
time: new Date().toISOString(),
status: cameraStatuses.reduce(
(acc, curr) => (acc[curr.deviceId] = curr.status),
{}
),
});
return res.json(statuses);
});

/**
Expand Down
2 changes: 1 addition & 1 deletion src/router/cameraRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ router.get(
);

router.post(
"cameras/status",
"/cameras/status",
validate(camerasStatusBodyValidators),
CameraController.getCameraStatuses
);
Expand Down

0 comments on commit b0b1703

Please sign in to comment.