Files
Mav-Mobile-UI/src/hooks/useCameraZoom.ts

91 lines
2.6 KiB
TypeScript
Raw Normal View History

import { useMutation, useQuery, type QueryFunctionContext } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import type { zoomConfig, ZoomInOptions } from "../types/types";
import { toast } from "sonner";
import { useEffect } from "react";
const getCameraMode = async (options: { camera: string }) => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Ip${options.camera}`);
if (!response.ok) throw new Error("Cannot get camera mode");
return response.json();
};
const updateCameraMode = async (options: { camera: string; mode: string }) => {
2025-11-10 13:44:29 +00:00
console.log(options);
const dayNightPayload = {
id: options.camera,
fields: [
{
property: "propDayNightMode",
value: options.mode,
},
],
};
const response = await fetch(`${CAM_BASE}/Ip${options.camera}-command?dayNightMode=${options.mode}`, {
method: "post",
body: JSON.stringify(dayNightPayload),
});
if (!response.ok) throw new Error("cannot update camera mode");
return response.json();
};
async function zoomIn(options: ZoomInOptions) {
const response = await fetch(
`${CAM_BASE}/Ip${options.camera}-command?magnification=${options.multiplierText?.toLowerCase()}`,
{
signal: AbortSignal.timeout(300000),
}
);
if (!response.ok) {
throw new Error("Cannot reach camera zoom endpoint");
}
return response.json();
}
async function fetchZoomInConfig({ queryKey }: QueryFunctionContext<[string, zoomConfig]>) {
const [, { camera }] = queryKey;
2025-11-04 15:29:48 +00:00
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Ip${camera}`, {
signal: AbortSignal.timeout(300000),
});
if (!response.ok) {
throw new Error("Cannot get camera zoom settings");
}
2025-11-04 15:29:48 +00:00
return response.json();
}
//change to string
export const useCameraZoom = (options: zoomConfig) => {
const mutation = useMutation({
mutationKey: ["zoomIn"],
mutationFn: (options: ZoomInOptions) => zoomIn(options),
});
const query = useQuery({
queryKey: ["fetchZoomInConfig", options],
queryFn: fetchZoomInConfig,
});
useEffect(() => {
2025-11-04 15:29:48 +00:00
if (query.isError) toast.error(query.error.message, { id: "zoom" });
}, [query?.error?.message, query.isError]);
return { mutation, query };
};
export const useCameraMode = (option: { camera: string }) => {
const cameraModeQuery = useQuery({
queryKey: ["getCameraMode"],
queryFn: () => getCameraMode(option),
});
const cameraModeMutation = useMutation({
mutationKey: ["updateCameraMode"],
mutationFn: updateCameraMode,
});
return {
cameraModeQuery,
cameraModeMutation,
};
};