15 Commits

Author SHA1 Message Date
104c53c127 Merge pull request 'feature/userReset' (#23) from feature/userReset into develop
Reviewed-on: #23
2026-01-07 09:52:42 +00:00
bec28b91e1 add ResetUserSettings component and integrate it into SystemConfigFields 2026-01-07 09:52:01 +00:00
71e23c7d45 - removed console.log 2026-01-07 09:41:19 +00:00
f9188bb46f - implement user settings reset functionality with modal confirmation
and bug fixes regarding lane IDs to sighting endpoints
2026-01-07 09:39:46 +00:00
f046ae6dfc Merge pull request 'develop' (#22) from develop into main
Reviewed-on: #22
2026-01-06 12:37:48 +00:00
4e5bff60ae - bumped to 1.0.24
- removed stray console.log
2026-01-06 12:37:07 +00:00
4da2e4a975 Merge pull request 'bugfix/feedback-Jan-26' (#21) from bugfix/feedback-Jan-26 into develop
Reviewed-on: #21
2026-01-06 12:29:21 +00:00
ac9b3cc1ea - updated version to 1.0.23, enhance audio file handling, and improve UTC synchronization checks 2026-01-06 12:28:08 +00:00
79e759d811 refactor: clean up unused imports and improve code readability and fixed endpoint to use window location 2025-12-22 15:57:07 +00:00
b79fde777d bump version to 1.0.21 2025-12-22 15:40:53 +00:00
a8ef18d2b9 Merge pull request 'develop' (#20) from develop into main
Reviewed-on: #20
2025-12-22 15:39:22 +00:00
6a1d63d98a Merge pull request 'feature/lastSync' (#19) from feature/lastSync into develop
Reviewed-on: #19
2025-12-22 15:39:02 +00:00
24ea41205f - updated endpoint 2025-12-22 15:26:34 +00:00
5b188747a5 Merge pull request 'develop' (#18) from develop into main
Reviewed-on: #18
2025-12-16 12:23:59 +00:00
1c760cb2a8 Merge pull request 'bugfix/fixesAndEnhancments' (#17) from bugfix/fixesAndEnhancments into develop
Reviewed-on: #17
2025-12-16 12:23:35 +00:00
25 changed files with 332 additions and 176 deletions

View File

@@ -1,7 +1,7 @@
{
"name": "in-car-system-fe",
"private": true,
"version": "1.0.20",
"version": "1.0.25",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -9,28 +9,25 @@ import { IntegrationsProvider } from "./context/providers/IntegrationsContextPro
import { AlertHitProvider } from "./context/providers/AlertHitProvider";
import { SoundProvider } from "react-sounds";
import SoundContextProvider from "./context/providers/SoundContextProvider";
import WebSocketProvider from "./context/providers/WebSocketProvider";
function App() {
return (
<SoundContextProvider>
<SoundProvider initialEnabled={true}>
<WebSocketProvider>
<IntegrationsProvider>
<AlertHitProvider>
<Routes>
<Route path="/" element={<Container />}>
<Route index element={<Dashboard />} />
<Route path="a-camera-settings" element={<FrontCamera />} />
<Route path="b-camera-settings" element={<RearCamera />} />
<Route path="system-settings" element={<SystemSettings />} />
<Route path="session-settings" element={<Session />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Route>
</Routes>
</AlertHitProvider>
</IntegrationsProvider>
</WebSocketProvider>
<IntegrationsProvider>
<AlertHitProvider>
<Routes>
<Route path="/" element={<Container />}>
<Route index element={<Dashboard />} />
<Route path="a-camera-settings" element={<FrontCamera />} />
<Route path="b-camera-settings" element={<RearCamera />} />
<Route path="system-settings" element={<SystemSettings />} />
<Route path="session-settings" element={<Session />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Route>
</Routes>
</AlertHitProvider>
</IntegrationsProvider>
</SoundProvider>
</SoundContextProvider>
);

View File

@@ -22,7 +22,6 @@ const CameraSettingFields = ({
onZoomLevelChange,
}: CameraSettingsProps) => {
const [showPwd, setShowPwd] = useState(false);
const cameraControllerSide = initialData?.id === "CameraA" ? "CameraControllerA" : "CameraControllerB";
const { mutation, query } = useCameraZoom({ camera: cameraControllerSide });
const { cameraModeQuery, cameraModeMutation } = useCameraMode({ camera: cameraControllerSide });

View File

@@ -1,7 +1,7 @@
import { Form, Formik } from "formik";
import BearerTypeCard from "../BearerType/BearerTypeCard";
import ChannelCard from "../Channel1-JSON/ChannelCard";
import { useCameraOutput, useGetDispatcherConfig } from "../../../hooks/useCameraOutput";
import { useCameraOutput, useGetDispatcherConfig, useLaneIds } from "../../../hooks/useCameraOutput";
import type {
BearerTypeFieldType,
InitialValuesForm,
@@ -14,25 +14,37 @@ import { useUpdateBackOfficeConfig } from "../../../hooks/useBackOfficeConfig";
import { useFormVaidate } from "../../../hooks/useFormValidate";
import { useSightingAmend } from "../../../hooks/useSightingAmend";
import StoreCard from "../Store/StoreCard";
import { useEffect } from "react";
const SettingForms = () => {
const qc = useQueryClient();
const { dispatcherQuery, dispatcherMutation, backOfficeDispatcherMutation, bof2LandMutation, laneIdQuery } =
useCameraOutput();
const { dispatcherQuery, dispatcherMutation, backOfficeDispatcherMutation } = useCameraOutput();
const { laneIdQuery: laneIDAQuery, laneIdMutation: laneIDAMutation } = useLaneIds("A");
const { laneIdQuery: laneIDBQuery, laneIdMutation: laneIDBMutation } = useLaneIds("B");
const { backOfficeMutation } = useUpdateBackOfficeConfig();
const { bof2ConstantsQuery } = useGetDispatcherConfig();
const { validateMutation } = useFormVaidate();
const { sightingAmendQuery, sightingAmendMutation } = useSightingAmend();
const { sightingAmendQuery: sightingAmendAQuery, sightingAmendMutation: sightingAmendMutationA } =
useSightingAmend("A");
const { sightingAmendMutation: sightingAmendMutationB } = useSightingAmend("B");
useEffect(() => {
async function fetchData() {
await Promise.all([laneIDAQuery.refetch(), laneIDBQuery.refetch()]);
}
fetchData();
}, [laneIDAQuery, laneIDBQuery]);
const format = dispatcherQuery?.data?.propFormat?.value;
const enabled = dispatcherQuery?.data?.propEnabled?.value;
const sightingQuality = sightingAmendQuery?.data?.propOverviewQuality?.value;
const cropSizeFactor = sightingAmendQuery?.data?.propOverviewImageScaleFactor?.value;
const sightingQualityA = sightingAmendAQuery?.data?.propOverviewQuality?.value;
const cropSizeFactorA = sightingAmendAQuery?.data?.propOverviewImageScaleFactor?.value;
const laneID = laneIdQuery?.data?.id;
const LID1 = laneIdQuery?.data?.propLaneID1?.value;
const LID2 = laneIdQuery?.data?.propLaneID2?.value;
const laneIDA = laneIDAQuery?.data?.id;
const LID1 = laneIDAQuery?.data?.propLaneID1?.value;
const LID2 = laneIDBQuery?.data?.propLaneID1?.value;
const FFID = bof2ConstantsQuery?.data?.propFeedIdentifier?.value;
const SCID = bof2ConstantsQuery?.data?.propSourceIdentifier?.value;
@@ -50,8 +62,8 @@ const SettingForms = () => {
password: "",
connectTimeoutSeconds: Number(5),
readTimeoutSeconds: Number(15),
overviewQuality: sightingQuality ?? "HIGH",
cropSizeFactor: cropSizeFactor ?? "3/4",
overviewQuality: sightingQualityA ?? "HIGH",
cropSizeFactor: cropSizeFactorA ?? "3/4",
// Bof2 - optional constants
FFID: FFID ?? "",
@@ -60,7 +72,7 @@ const SettingForms = () => {
GPSFormat: GPSFormat ?? "",
//BOF2 - optional Lane IDs
laneId: laneID ?? "",
laneId: laneIDA ?? "",
LID1: LID1 ?? "",
LID2: LID2 ?? "",
};
@@ -101,7 +113,8 @@ const SettingForms = () => {
if (validResponse?.reason === "OK") {
await backOfficeMutation.mutateAsync(values);
await sightingAmendMutation.mutateAsync(values);
await sightingAmendMutationA.mutateAsync(values);
await sightingAmendMutationB.mutateAsync(values);
if (values.format.toLowerCase() === "bof2") {
const bof2ConstantsData: OptionalBOF2Constants = {
@@ -111,12 +124,17 @@ const SettingForms = () => {
GPSFormat: values.GPSFormat,
};
const bof2LaneData: OptionalBOF2LaneIDs = {
laneId: laneIdQuery?.data?.id,
const bof2LaneAData: OptionalBOF2LaneIDs = {
laneId: laneIDAQuery?.data?.id,
LID1: values.LID1,
LID2: values.LID2,
};
await bof2LandMutation.mutateAsync(bof2LaneData);
const bof2LaneBData: OptionalBOF2LaneIDs = {
laneId: laneIDBQuery?.data?.id,
LID1: values.LID2,
};
await laneIDAMutation.mutateAsync(bof2LaneAData);
await laneIDBMutation.mutateAsync(bof2LaneBData);
await backOfficeDispatcherMutation.mutateAsync(bof2ConstantsData);
}
} else {

View File

@@ -5,13 +5,13 @@ import { useSoundContext } from "../../../context/SoundContext";
import { toast } from "sonner";
import { useCameraBlackboard } from "../../../hooks/useCameraBlackboard";
import { useFileUpload } from "../../../hooks/useFileUpload";
import { useEffect, useRef } from "react";
const SoundUpload = () => {
const { state, dispatch } = useSoundContext();
const { mutation } = useCameraBlackboard();
const { mutation: fileMutation } = useFileUpload({
queryKey: state.sightingSound ? [state.sightingSound] : undefined,
});
const currentUrlRef = useRef<string | null>(null);
const { mutation: fileMutation } = useFileUpload();
const initialValues: SoundUploadValue = {
name: "",
@@ -43,6 +43,10 @@ const SoundUpload = () => {
value: updatedValues,
});
await fileMutation.mutateAsync(values.soundFile);
if (currentUrlRef.current) {
URL.revokeObjectURL(currentUrlRef.current);
currentUrlRef.current = null;
}
if (result.reason !== "OK") {
toast.error("Cannot update sound settings");
}
@@ -54,6 +58,14 @@ const SoundUpload = () => {
dispatch({ type: "ADD", payload: values });
};
useEffect(() => {
return () => {
if (currentUrlRef.current) {
URL.revokeObjectURL(currentUrlRef.current);
}
};
}, []);
return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
{({ setFieldValue, errors, setFieldError }) => (
@@ -69,14 +81,26 @@ const SoundUpload = () => {
accept="audio/mpeg"
className="mt-4 w-full flex flex-col items-center justify-center rounded-2xl border border-slate-800 bg-slate-900/40 p-10 text-center file:px-3 file:border file:border-gray-500 file:rounded-lg file:bg-blue-800 file:mr-5"
onChange={(e) => {
if (e.target?.files && e.target?.files[0]?.type === "audio/mpeg") {
const url = URL.createObjectURL(e.target.files[0]);
if (currentUrlRef.current) {
URL.revokeObjectURL(currentUrlRef.current);
}
const files = e.target?.files;
if (
files &&
(files[0]?.type === "audio/mp3" ||
files[0]?.type === "audio/mpeg" ||
files[0]?.name.endsWith(".wav"))
) {
const file = e.target?.files;
if(file === null) return;
currentUrlRef.current = URL.createObjectURL(file[0]);
const url = currentUrlRef.current;
setFieldValue("soundUrl", url);
setFieldValue("name", e.target.files[0].name);
setFieldValue("soundFileName", e.target.files[0].name);
setFieldValue("soundFile", e.target.files[0]);
setFieldValue("name", file[0].name);
setFieldValue("soundFileName", file[0].name);
setFieldValue("soundFile", file[0]);
setFieldValue("uploadedAt", Date.now());
if (e?.target?.files[0]?.size >= 1 * 1024 * 1024) {
if (file[0]?.size >= 1 * 1024 * 1024) {
setFieldError("soundFile", "larger than 1mb");
toast.error("File larger than 1MB");
return;

View File

@@ -5,21 +5,40 @@ import { timezones } from "./timezones";
import SystemFileUpload from "./SystemFileUpload";
import type { SystemValues, SystemValuesErrors } from "../../../types/types";
import { useDNSSettings, useSystemConfig } from "../../../hooks/useSystemConfig";
import { ValidateIPaddress } from "../../../utils/utils";
import { ValidateIPaddress, isUtcOutOfSync } from "../../../utils/utils";
import { toast } from "sonner";
import { useSystemStatus } from "../../../hooks/useSystemStatus";
import ResetUserSettings from "./resetUserSettings/ResetUserSettings";
const SystemConfigFields = () => {
const { saveSystemSettings, systemSettingsData, saveSystemSettingsLoading } = useSystemConfig();
const { systemStatusQuery } = useSystemStatus();
const { hardRebootMutation } = useReboots();
const { dnsQuery, dnsMutation } = useDNSSettings();
if (systemStatusQuery?.isLoading || !systemStatusQuery?.data) {
return <div>Loading...</div>;
}
const utcTime = systemStatusQuery?.data?.SystemStatus?.utctime;
const localDate = systemStatusQuery?.data?.SystemStatus?.localdate;
const localTime = systemStatusQuery?.data?.SystemStatus?.localtime;
const utcOutOfSync = isUtcOutOfSync({
utctime: utcTime,
localdate: localDate,
localtime: localTime,
});
const syncTime = new Date(systemStatusQuery?.data?.SystemStatus?.synctime * 1000).toLocaleString();
const sntpInterval = systemSettingsData?.sntpInterval;
const dnsPrimary = dnsQuery?.data?.propNameServerPrimary?.value;
const dnsSecondary = dnsQuery?.data?.propNameServerSecondary?.value;
const initialvalues: SystemValues = {
deviceName: systemSettingsData?.deviceName ?? "",
timeZone: systemSettingsData?.timeZone ?? "",
sntpServer: systemSettingsData?.sntpServer ?? "",
sntpInterval: systemSettingsData?.sntpInterval ?? 60,
sntpInterval: sntpInterval ?? 60,
serverPrimary: dnsPrimary ?? "",
serverSecondary: dnsSecondary ?? "",
softwareUpdate: null,
@@ -165,6 +184,14 @@ const SystemConfigFields = () => {
autoComplete="off"
/>
</FormGroup>
<div className="flex flex-col gap-2 w-70">
{utcOutOfSync?.outOfSync ? (
<span className="text-red-800 bg-red-300 border border-red-800 rounded-lg p-2 ">UTC is out of sync</span>
) : (
<span className="text-green-300 bg-green-800 border border-green-600 rounded-lg p-2">UTC is in sync</span>
)}
<p className="mt-2">Last Sync Time: {syncTime}</p>
</div>
<button
type="submit"
className="w-full md:w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
@@ -191,6 +218,7 @@ const SystemConfigFields = () => {
>
{hardRebootMutation.isPending || isSubmitting ? "Rebooting" : "Hardware Reboot"}
</button>
<ResetUserSettings />
</Form>
)}
</Formik>

View File

@@ -2,6 +2,7 @@ import { useFormikContext } from "formik";
import FormGroup from "../components/FormGroup";
import { toast } from "sonner";
import { useSystemConfig } from "../../../hooks/useSystemConfig";
import { CAM_BASE } from "../../../utils/config";
type SystemFileUploadProps = {
name: string;
@@ -19,7 +20,7 @@ const SystemFileUpload = ({ name, selectedFile }: SystemFileUploadProps) => {
opts: {
timeoutMs: 30000,
fieldName: "upload",
uploadUrl: "http://192.168.75.11/upload/software-update/2",
uploadUrl: `${CAM_BASE}/upload/software-update/4`,
},
};
uploadSettings(settings);

View File

@@ -0,0 +1,26 @@
import { useState } from "react";
import ResetUserSettingsModal from "./ResetUserSettingsModal";
const ResetUserSettings = () => {
const [isUserSettingsModalOpen, setIsUserSettingsModalOpen] = useState(false);
const handleResetButtonClick = () => {
setIsUserSettingsModalOpen(true);
};
return (
<>
<button
type="button"
onClick={handleResetButtonClick}
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full md:w-[50%]"
>
Reset user settings
</button>
<ResetUserSettingsModal
isUserSettingsModalOpen={isUserSettingsModalOpen}
setIsUserSettingsModalOpen={setIsUserSettingsModalOpen}
/>
</>
);
};
export default ResetUserSettings;

View File

@@ -0,0 +1,68 @@
import { useSoundContext } from "../../../../context/SoundContext";
import { useCameraBlackboard } from "../../../../hooks/useCameraBlackboard";
import ModalComponent from "../../../UI/ModalComponent";
type ResetUserSettingsModalProps = {
isUserSettingsModalOpen: boolean;
setIsUserSettingsModalOpen: (isOpen: boolean) => void;
};
const ResetUserSettingsModal = ({
isUserSettingsModalOpen,
setIsUserSettingsModalOpen,
}: ResetUserSettingsModalProps) => {
const { state, dispatch } = useSoundContext();
const { mutation } = useCameraBlackboard();
const handleClose = () => {
setIsUserSettingsModalOpen(false);
};
const handleResetAll = async () => {
// Logic to reset all user settings goes here
dispatch({ type: "RESET" });
await mutation.mutateAsync({
operation: "INSERT",
path: "soundSettings",
value: state,
});
handleClose();
};
return (
<ModalComponent isModalOpen={isUserSettingsModalOpen} close={handleClose}>
<div className="p-4">
<h2 className="text-xl font-bold mb-4">Reset All User Settings</h2>
<p className="mb-4">Are you sure you want to reset all user settings to their default values?</p>
<p> This action cannot be undone.</p>
<div className="my-4 flex flex-col items-center justify-center rounded-2xl border border-slate-800 bg-slate-900/40 p-10 text-center">
<p className="max-w-md text-slate-300">
This will <span className="font-bold">RESET ALL</span> user settings including{" "}
<span className="text-blue-400">Uploaded user sounds</span> ,
<span className="text-emerald-400"> Hotlist Sound hits</span> and{" "}
<span className="text-amber-600">NPED Sound hits</span>.
{/* It will also reset any customized settings within
the app to their original defaults and Clear out the session data and{" "}
<span className="text-rose-400">alert history sightings.</span> */}
</p>
</div>
<div className="flex justify-end gap-4">
<button
onClick={handleResetAll}
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 hover:cursor-pointer"
>
Reset
</button>
<button
onClick={handleClose}
className="bg-gray-600 text-white px-4 py-2 rounded hover:bg-gray-700 hover:cursor-pointer "
>
Cancel
</button>
</div>
</div>
</ModalComponent>
);
};
export default ResetUserSettingsModal;

View File

@@ -227,10 +227,6 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
<dt className="text-gray-300">Motion</dt>
<dd className="font-medium text-2xl ">{sighting?.motion ?? "-"}</dd>
</div>
<div>
<dt className="text-gray-300">Seen Count</dt>
<dd className="font-medium text-2xl">{sighting?.seenCount ?? "-"}</dd>
</div>
{sighting?.make && sighting.make.trim() && sighting.make.toLowerCase() !== "disabled" && (
<div>

View File

@@ -1,5 +1,6 @@
import type React from "react";
import Modal from "react-modal";
import clsx from "clsx";
type ModalComponentProps = {
isModalOpen: boolean;
@@ -12,7 +13,9 @@ const ModalComponent = ({ isModalOpen, children, close }: ModalComponentProps) =
<Modal
isOpen={isModalOpen}
onRequestClose={close}
className="bg-[#1e2a38] p-3 rounded-lg shadow-lg w-[95%] mt-[2%] md:w-[60%] h-[100%] md:h-[95%] lg:h-[80%] z-[100] overflow-y-hidden border border-gray-500"
className={clsx(
"bg-[#1e2a38] p-3 rounded-lg shadow-lg w-[95%] mt-[2%] md:w-[60%] h-[100%] md:h-[95%] lg:h-[80%] z-[100] overflow-y-hidden border border-gray-500"
)}
overlayClassName="fixed inset-0 bg-[#1e2a38]/70 flex justify-center items-start z-100 "
style={{
overlay: {

View File

@@ -1,33 +0,0 @@
import { createContext, useContext } from "react";
import type { InfoBarData } from "../types/types";
import { ReadyState } from "react-use-websocket";
type InfoSocketState = {
data: InfoBarData | null;
readyState: ReadyState;
sendJson: (msg: unknown) => void;
send?: (msg: string) => void;
};
type heatmapSocketState = {
data: null;
readyState: ReadyState;
sendJson: (msg: unknown) => void;
send?: (msg: string) => void;
};
export type WebsocketContextValue = {
info: InfoSocketState;
heatmap?: heatmapSocketState;
};
export const WebsocketContext = createContext<WebsocketContextValue | null>(null);
const useWebSocketContext = () => {
const ctx = useContext(WebsocketContext);
if (!ctx) throw new Error("useWebSocketContext must be used inside <WebSocketConext.Provider>");
return ctx;
};
export const useInfoBarSocket = () => useWebSocketContext().info;
export const useHeatmapSocket = () => useWebSocketContext().heatmap;

View File

@@ -1,40 +0,0 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import type { InfoBarData } from "../../types/types";
import useWebSocket from "react-use-websocket";
import { ws_config } from "../../utils/ws_config";
import { WebsocketContext, type WebsocketContextValue } from "../WebsocketContext";
type WebSocketProviderProps = {
children: ReactNode;
};
const WebSocketProvider = ({ children }: WebSocketProviderProps) => {
const [systemData, setSystemData] = useState<InfoBarData | null>(null);
const infoSocket = useWebSocket(ws_config.infoBar, { share: true, shouldReconnect: () => true });
useEffect(() => {
async function parseData() {
if (infoSocket.lastMessage) {
const text = await infoSocket.lastMessage.data.text();
const data = JSON.parse(text);
setSystemData(data);
}
}
parseData();
}, [infoSocket.lastMessage]);
const value = useMemo<WebsocketContextValue>(
() => ({
info: {
data: systemData,
readyState: infoSocket.readyState,
sendJson: infoSocket.sendJsonMessage,
},
}),
[systemData, infoSocket.readyState, infoSocket.sendJsonMessage]
);
return <WebsocketContext.Provider value={value}>{children}</WebsocketContext.Provider>;
};
export default WebSocketProvider;

View File

@@ -69,6 +69,8 @@ export function reducer(state: SoundState, action: SoundAction): SoundState {
...state,
uploadedSound: action.payload,
};
case "RESET":
return initialState;
default:
return state;
}

View File

@@ -78,7 +78,11 @@ const updateBOF2LaneId = async (data: OptionalBOF2LaneIDs) => {
},
{
property: "propLaneID2",
value: data?.LID2,
value: data?.LID1,
},
{
property: "propLaneID3",
value: data?.LID1,
},
],
};
@@ -91,8 +95,8 @@ const updateBOF2LaneId = async (data: OptionalBOF2LaneIDs) => {
return response.json();
};
const getBOF2LaneId = async () => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=SightingAmmendA-lane-ids`);
const getBOF2LaneId = async (cameraID: string) => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=SightingAmmend${cameraID}-lane-ids`);
if (!response.ok) throw new Error("Canot get Lane Ids");
return response.json();
};
@@ -124,16 +128,6 @@ export const useCameraOutput = () => {
},
});
const bof2LandMutation = useMutation({
mutationKey: ["updateBOF2LaneId"],
mutationFn: updateBOF2LaneId,
});
const laneIdQuery = useQuery({
queryKey: ["getBOF2LaneId"],
queryFn: getBOF2LaneId,
});
useEffect(() => {
if (dispatcherQuery.isError) toast.error(dispatcherQuery.error.message);
}, [dispatcherQuery?.error?.message, dispatcherQuery.isError]);
@@ -142,8 +136,6 @@ export const useCameraOutput = () => {
dispatcherQuery,
dispatcherMutation,
backOfficeDispatcherMutation,
bof2LandMutation,
laneIdQuery,
};
};
@@ -155,3 +147,17 @@ export const useGetDispatcherConfig = () => {
return { bof2ConstantsQuery };
};
export const useLaneIds = (cameraID: string) => {
const laneIdQuery = useQuery({
queryKey: ["getBOF2LaneId", cameraID],
queryFn: () => getBOF2LaneId(cameraID),
});
const laneIdMutation = useMutation({
mutationKey: ["updateBOF2LaneId", cameraID],
mutationFn: (data: OptionalBOF2LaneIDs) => updateBOF2LaneId(data),
});
return { laneIdQuery, laneIdMutation };
};

View File

@@ -1,12 +1,8 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { useMutation } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import { toast } from "sonner";
import { getOrCacheBlob } from "../utils/cacheSound";
const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : CAM_BASE;
type UseFileUploadProps = {
queryKey?: string[];
};
const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : CAM_BASE;
const uploadFile = async (file: File) => {
const form = new FormData();
@@ -21,19 +17,7 @@ const uploadFile = async (file: File) => {
return response.text();
};
const getUploadFiles = async ({ queryKey }: { queryKey: string[] }) => {
const [, fileName] = queryKey;
const url = fileName;
return getOrCacheBlob(url);
};
export const useFileUpload = ({ queryKey }: UseFileUploadProps) => {
const query = useQuery({
queryKey: ["getUploadFiles", ...(queryKey ?? [])],
queryFn: () => getUploadFiles({ queryKey: ["getUploadFiles", ...(queryKey ?? [])] }),
enabled: !!queryKey,
});
export const useFileUpload = () => {
const mutation = useMutation({
mutationFn: (file: File) => uploadFile(file),
mutationKey: ["uploadFile"],
@@ -41,5 +25,5 @@ export const useFileUpload = ({ queryKey }: UseFileUploadProps) => {
onSuccess: async (msg) => toast.success(msg),
});
return { query: queryKey ? query : undefined, mutation };
return { mutation };
};

View File

@@ -0,0 +1,22 @@
import { useQuery } from "@tanstack/react-query";
import { getOrCacheBlob } from "../utils/cacheSound";
type UseFileUploadProps = {
queryKey?: string[];
};
const getUploadFiles = async ({ queryKey }: { queryKey: string[] }) => {
const [, fileName] = queryKey;
const url = fileName;
return getOrCacheBlob(url);
};
export const useGetUploadedFiles = ({ queryKey }: UseFileUploadProps) => {
const query = useQuery({
queryKey: ["getUploadFiles", ...(queryKey ?? [])],
queryFn: () => getUploadFiles({ queryKey: ["getUploadFiles", ...(queryKey ?? [])] }),
enabled: !!queryKey,
});
return { query: queryKey ? query : undefined };
};

View File

@@ -2,15 +2,15 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import type { InitialValuesForm } from "../types/types";
const getSightingAmend = async () => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=SightingAmmendA`);
const getSightingAmend = async (cameraId: string) => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=SightingAmmend${cameraId}`);
if (!response.ok) throw new Error("Cannot reach sighting amend endpoint");
return response.json();
};
const updateSightingAmend = async (data: InitialValuesForm) => {
const updateSightingAmend = async (data: InitialValuesForm, cameraID: string) => {
const updateSightingAmendPayload = {
id: "SightingAmmendA",
id: `SightingAmmend${cameraID}`,
fields: [
{
property: "propOverviewQuality",
@@ -30,15 +30,15 @@ const updateSightingAmend = async (data: InitialValuesForm) => {
return response.json();
};
export const useSightingAmend = () => {
export const useSightingAmend = (cameraID: string) => {
const sightingAmendQuery = useQuery({
queryKey: ["getSightingAmend"],
queryFn: getSightingAmend,
queryFn: () => getSightingAmend(cameraID),
});
const sightingAmendMutation = useMutation({
mutationKey: ["updateSightingAmend"],
mutationFn: updateSightingAmend,
mutationKey: ["updateSightingAmend", cameraID],
mutationFn: (data: InitialValuesForm) => updateSightingAmend(data, cameraID),
});
return {

View File

@@ -0,0 +1,20 @@
import { useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
const fetchSystemStatus = async () => {
const response = await fetch(`${CAM_BASE}/sysstatus?func=getstatus`);
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
};
export const useSystemStatus = () => {
const systemStatusQuery = useQuery({
queryKey: ["get systemStatus"],
queryFn: fetchSystemStatus,
refetchInterval: 60000,
});
return { systemStatusQuery };
};

View File

@@ -1,8 +1,8 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useFileUpload } from "./useFileUpload";
import { getSoundFileURL } from "../utils/utils";
import type { SoundUploadValue } from "../types/types";
import { resolveSoundSource } from "../utils/soundResolver";
import { useGetUploadedFiles } from "./useGetUploadedFiles";
export function useCachedSoundSrc(
selected: string | undefined,
@@ -13,7 +13,7 @@ export function useCachedSoundSrc(
const resolved = resolveSoundSource(selected, soundOptions);
const { query } = useFileUpload({
const { query } = useGetUploadedFiles({
queryKey: resolved?.type === "uploaded" ? [resolved?.url] : undefined,
});

View File

@@ -363,7 +363,11 @@ type UploadedState = {
payload: Blob | undefined;
};
export type SoundAction = UpdateAction | AddAction | VolumeAction | UploadedState;
type ResetAction = {
type: "RESET";
};
export type SoundAction = UpdateAction | AddAction | VolumeAction | UploadedState | ResetAction;
export type WifiSettingValues = {
ssid: string;
password: string;

View File

@@ -1,4 +1,12 @@
export async function getOrCacheBlob(url: string) {
const cacheAvailable = typeof window !== "undefined" && "caches" in window;
if (!cacheAvailable) {
const res = await fetch(url, { cache: "no-store" });
if (!res.ok) throw new Error(`Fetch failed: ${res.status}`);
return await res.blob();
}
const cache = await caches.open("app-sounds-v1");
const hit = await cache.match(url);
if (hit) return await hit.blob();
@@ -11,6 +19,11 @@ export async function getOrCacheBlob(url: string) {
}
export async function evictFromCache(url: string) {
const cacheAvailable = typeof window !== "undefined" && "caches" in window;
if (!cacheAvailable) {
return;
}
const cache = await caches.open("app-sounds-v1");
await cache.delete(url);
}

View File

@@ -1,5 +1,4 @@
const rawCamBase = import.meta.env.VITE_AGX_BOX_URL;
const rawCamBase = import.meta.env.VITE_CHRIS_BOX_URL;
const environment = import.meta.env.MODE;
export const CAM_BASE =
environment === "development" ? rawCamBase : window.location.origin;
export const CAM_BASE = environment === "development" ? rawCamBase : window.location.origin;

View File

@@ -197,3 +197,21 @@ export const ValidateIPaddress = (value: string | undefined) => {
return "Invalid IP address format";
}
};
export function isUtcOutOfSync(
data: {
utctime: number;
localdate: string;
localtime: string;
},
maxDriftMs = 60_000
) {
const utc = new Date(data.utctime);
const [d, m, y] = data.localdate.split("/").map(Number);
const [hh, mm, ss] = data.localtime.split(":").map(Number);
// Construct local Date in devices local timezone
const local = new Date(y, m - 1, d, hh, mm, ss);
const driftMs = Math.abs(utc.getTime() - local.getTime() + utc.getTimezoneOffset() * 60_000);
return { driftMs, outOfSync: driftMs > maxDriftMs };
}

View File

@@ -27,7 +27,7 @@ export default defineConfig({
host: true,
proxy: {
"/api": {
target: "http://100.118.196.113:8080",
target: "http://100.72.72.70:8080",
changeOrigin: true,
},
},
@@ -40,3 +40,4 @@ export default defineConfig({
__GIT_TIMESTAMP__: JSON.stringify(gitCommitTimeStamp),
},
});
// Previous target: "http://100.118.196.113:8080",