84 lines
2.0 KiB
TypeScript
84 lines
2.0 KiB
TypeScript
import { useRef, useCallback, useEffect } from "react";
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import { CAM_BASE } from "../utils/config";
|
|
|
|
const apiUrl = CAM_BASE;
|
|
|
|
async function fetchSnapshot() {
|
|
const response = await fetch(`${apiUrl}/CameraRear-preview`);
|
|
if (!response.ok) {
|
|
throw new Error("Cannot reach endpoint");
|
|
}
|
|
|
|
return await response.blob();
|
|
}
|
|
|
|
export function useGetOverviewSnapshot() {
|
|
const latestUrlRef = useRef<string | null>(null);
|
|
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
|
const imageRef = useRef<HTMLImageElement | null>(null);
|
|
|
|
const drawImage = useCallback(() => {
|
|
const canvas = canvasRef.current;
|
|
const ctx = canvas?.getContext("2d");
|
|
const img = imageRef.current;
|
|
|
|
if (!canvas || !ctx || !img) return;
|
|
|
|
canvas.width = canvas.clientWidth;
|
|
canvas.height = canvas.clientHeight;
|
|
|
|
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
|
}, []);
|
|
|
|
const {
|
|
data: snapshotBlob,
|
|
isError,
|
|
error,
|
|
isPending,
|
|
} = useQuery({
|
|
queryKey: ["overviewSnapshot"],
|
|
queryFn: () => fetchSnapshot(),
|
|
refetchOnWindowFocus: false,
|
|
refetchInterval: 250,
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (!snapshotBlob) return;
|
|
|
|
const imgUrl = URL.createObjectURL(snapshotBlob);
|
|
const img = new Image();
|
|
imageRef.current = img;
|
|
|
|
img.onload = () => {
|
|
drawImage();
|
|
};
|
|
img.src = imgUrl;
|
|
|
|
if (latestUrlRef.current) {
|
|
URL.revokeObjectURL(latestUrlRef.current);
|
|
}
|
|
latestUrlRef.current = imgUrl;
|
|
|
|
return () => {
|
|
if (latestUrlRef.current) {
|
|
URL.revokeObjectURL(latestUrlRef.current);
|
|
latestUrlRef.current = null;
|
|
}
|
|
};
|
|
}, [snapshotBlob, drawImage]);
|
|
|
|
useEffect(() => {
|
|
window.addEventListener("resize", drawImage);
|
|
return () => {
|
|
window.removeEventListener("resize", drawImage);
|
|
};
|
|
}, [drawImage]);
|
|
|
|
if (isError) {
|
|
console.error("Snapshot error:", error);
|
|
}
|
|
|
|
return { canvasRef, isError, isPending };
|
|
}
|