54 Commits

Author SHA1 Message Date
630261ac21 Merged develop into bugfix/uploadsounds-2 2025-11-04 11:37:59 +00:00
c948192f10 Merged in bugfix/bearertype (pull request #34)
Bugfix/bearertype
2025-11-04 11:37:05 +00:00
f47459d116 - added validation endpoint 2025-11-04 11:31:37 +00:00
705d7c7040 - removed other options 2025-11-04 11:17:04 +00:00
ca625673e9 - updated to retrieve and set BOF2 data 2025-11-04 11:05:40 +00:00
538b623ac6 - updated form to include bof2 constants
- refactored code to make more scalable and use one form
2025-11-04 10:24:06 +00:00
933c101cbc - refactored to fetch confis based on formats
- send configs based on formats
2025-11-03 15:01:13 +00:00
af1dabc8fc Merged main into bugfix/uploadsounds-2 2025-10-31 08:27:59 +00:00
a839502421 - added sound file size limit 2025-10-30 11:16:06 +00:00
39629897d4 - removed console.logs 2025-10-30 10:53:48 +00:00
cd26b3b68f Merged main into develop 2025-10-30 10:41:07 +00:00
a8abed2246 - added feature to cache sounds for cross devices - should work in theory 2025-10-29 15:04:40 +00:00
cf72a1e1d3 - fixed file size bug 2025-10-28 15:23:28 +00:00
c8eed55801 - uploaded files seems to work on desktop version 2025-10-28 13:53:11 +00:00
907555cb0d - storing changes for now 2025-10-28 09:54:29 +00:00
d6c39843c8 Merged in develop (pull request #33)
Develop
2025-10-28 08:52:54 +00:00
a64fa76ecb - saving current work before refactor 2025-10-28 08:50:55 +00:00
93dcde4459 Merge branch 'develop' into bugfix/uploadsounds-2 2025-10-27 14:28:56 +00:00
a5b07333da Merged in bugfix/minorchanges (pull request #32)
bugfix/minorChanges
2025-10-27 14:20:56 +00:00
ae0a6f9249 - added debouncing of sounds
- added new sound files
- moved soung hits to sighting list
2025-10-27 14:00:28 +00:00
350d7cf41c Merge branch 'bugfix/uploadsounds-2' of bitbucket.org:mavsystemsltd/mav-in-car-fe into bugfix/uploadsounds-2 2025-10-27 11:31:25 +00:00
78e5da45ca Merged develop into bugfix/uploadsounds-2 2025-10-27 11:29:07 +00:00
e46460f41d Merged in enhancement/sessionstats (pull request #31)
Enhancement/sessionstats
2025-10-27 11:23:29 +00:00
6c441a0a4b Merged in enhancement-refactor (pull request #30)
Enhancement refactor
2025-10-27 11:11:15 +00:00
2d5b264041 - refactored state for sessionlist, and session active and pause states 2025-10-27 11:04:53 +00:00
251a2f5e7b - refactored NPED Login & logout 2025-10-27 09:35:59 +00:00
18534ceb2c - added functionality to save sighting sessions to black board 2025-10-27 08:28:44 +00:00
9975e6a6ca Merged develop into enhancement/sessionstats 2025-10-24 11:12:51 +00:00
c83122cd52 - added session sighting component
- add new session paused state and stop adding to session when true
2025-10-24 12:10:10 +01:00
abc8007fc6 Merged in enhancement/sightingHits (pull request #29)
Enhancement/sightingHits
2025-10-24 09:56:25 +00:00
7903633809 - removed console.log 2025-10-24 10:55:05 +01:00
359f3781f2 - refactored to allow for stacking of special hits (NPED + Hotlist) 2025-10-24 10:49:04 +01:00
f264f4e808 - resolved coding error 2025-10-23 09:19:18 +01:00
0c6e4b57be - need to find better way to fetch file urls to use for sound 2025-10-22 16:12:49 +01:00
a958901bed - will pick up later 2025-10-22 12:20:15 +01:00
4519700561 - added new sound files
- new functionality to upload files
- need to get and locatate uploaded files
2025-10-22 11:51:37 +01:00
b58181e551 - started improvements on session page to include pause and save buttons 2025-10-22 08:54:42 +01:00
df6bf75184 Merged in bugfix/uploadsounds (pull request #28)
Bugfix/uploadsounds
2025-10-21 14:20:33 +00:00
c5cea81532 Merged develop into bugfix/uploadsounds 2025-10-21 14:19:14 +00:00
78905b09e0 - added framework for playing uploaded music files. need to permanently store and retreive files 2025-10-21 12:52:14 +01:00
1ffad51503 fixed feature to upload sound files 2025-10-20 16:17:37 +01:00
d16f55413c Merged main into develop 2025-10-20 10:54:41 +00:00
3598f8d069 Merged in develop (pull request #27)
Develop
2025-10-20 10:53:48 +00:00
0a3a543d6f Merged in bugfix/hostlistsound (pull request #26)
bugfix/hotlistsound
2025-10-20 10:35:44 +00:00
0867b3b743 - added sounds for all hotlist sounds 2025-10-20 11:32:45 +01:00
a152c15ec7 - removed console.log 2025-10-20 10:59:38 +01:00
617ea60f26 Merged in bugfix/AlanFeedback (pull request #25)
Bugfix/AlanFeedback
2025-10-20 09:54:13 +00:00
1b0790a841 Merged develop into bugfix/AlanFeedback 2025-10-20 09:53:46 +00:00
a54e6a79c1 - updated button to match 2025-10-20 10:50:16 +01:00
b2dd35b311 - added volume functionality for NPED notifications 2025-10-20 09:11:05 +01:00
82b84dc46e - added volume setting for sighting hits 2025-10-17 16:12:02 +01:00
34c996c990 Merged main into develop 2025-10-17 10:39:28 +00:00
bb82fad583 Merged in develop (pull request #23)
Develop
2025-10-17 10:30:02 +00:00
3eb539fd9d - start addressing Alans feedback 2025-10-17 10:17:01 +01:00
55 changed files with 1375 additions and 748 deletions

View File

@@ -22,6 +22,7 @@
"country-flag-icons": "^1.5.19",
"formik": "^2.4.6",
"howler": "^2.2.4",
"rc-slider": "^11.1.9",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-modal": "^3.16.3",
@@ -31,7 +32,8 @@
"react-tabs": "^6.1.0",
"react-use": "^17.6.0",
"sonner": "^2.0.7",
"tailwindcss": "^4.1.11"
"tailwindcss": "^4.1.11",
"use-debounce": "^10.0.6"
},
"devDependencies": {
"@eslint/js": "^9.32.0",

View File

@@ -5,7 +5,7 @@ import FrontCamera from "./pages/FrontCamera";
import RearCamera from "./pages/RearCamera";
import SystemSettings from "./pages/SystemSettings";
import Session from "./pages/Session";
import { NPEDUserProvider } from "./context/providers/NPEDUserContextProvider";
import { IntegrationsProvider } from "./context/providers/IntegrationsContextProvider";
import { AlertHitProvider } from "./context/providers/AlertHitProvider";
import { SoundProvider } from "react-sounds";
import SoundContextProvider from "./context/providers/SoundContextProvider";
@@ -14,7 +14,7 @@ function App() {
return (
<SoundContextProvider>
<SoundProvider initialEnabled={true}>
<NPEDUserProvider>
<IntegrationsProvider>
<AlertHitProvider>
<Routes>
<Route path="/" element={<Container />}>
@@ -27,7 +27,7 @@ function App() {
</Route>
</Routes>
</AlertHitProvider>
</NPEDUserProvider>
</IntegrationsProvider>
</SoundProvider>
</SoundContextProvider>
);

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -1,5 +1,5 @@
// import { EU } from "country-flag-icons/react/3x2";
import { formatNumberPlateEU } from "../../utils/utils";
import { GB } from "country-flag-icons/react/3x2";
import { formatNumberPlate } from "../../utils/utils";
type NumberPlateProps = {
vrm?: string | undefined;
@@ -40,16 +40,19 @@ const NumberPlate = ({ motion, vrm, size }: NumberPlateProps) => {
return (
<div
className={`relative ${options.plateWidth} ${options.borderWidth} border-black rounded-xl text-nowrap
className={`relative ${options.plateWidth} ${
options.borderWidth
} border-black rounded-xl text-nowrap
text-black px-6 py-2
${motion ? "bg-white" : "bg-white"}`}
${motion ? "bg-yellow-400" : "bg-white"}`}
>
<div>
{/* <div className="absolute inset-y-0 left-0 bg-[#003399] w-8 flex flex-col">
<EU />
<small className="text-white font-semibold text-center">FIN</small>
</div> */}
<p className={`pl-4 font-extrabold ${options.textSize} text-center`}>{vrm && formatNumberPlateEU(vrm)}</p>
<div className="absolute inset-y-0 left-0 bg-blue-600 w-8 flex flex-col">
<GB />
</div>
<p className={`pl-4 font-extrabold ${options.textSize} text-right`}>
{vrm && formatNumberPlate(vrm)}
</p>
</div>
</div>
);

View File

@@ -1,30 +1,36 @@
import Card from "../UI/Card";
import CardHeader from "../UI/CardHeader";
import { useNPEDContext } from "../../context/NPEDUserContext";
import { useIntegrationsContext } from "../../context/IntegrationsContext";
import type { ReducedSightingType } from "../../types/types";
import { toast } from "sonner";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faFloppyDisk, faPause, faPlay, faStop } from "@fortawesome/free-solid-svg-icons";
import VehicleSessionItem from "../UI/VehicleSessionItem";
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
const SessionCard = () => {
const { sessionStarted, setSessionStarted, sessionList } = useNPEDContext();
const { state, dispatch } = useIntegrationsContext();
const { mutation } = useCameraBlackboard();
const handleStartClick = () => {
setSessionStarted(!sessionStarted);
toast(`${sessionStarted ? "Vehicle tracking session Ended" : "Vehicle tracking session Started"}`);
};
const sessionStarted = state.sessionStarted;
const sessionPaused = state.sessionPaused;
const sessionList = state.sessionList;
const sightings = [...new Map(sessionList.map((vehicle) => [vehicle.vrm, vehicle]))];
const sightings = [...new Map(sessionList?.map((vehicle) => [vehicle.vrm, vehicle]))];
const dedupedSightings = sightings.map((sighting) => sighting[1]);
const vehicles = dedupedSightings.reduce<Record<string, ReducedSightingType[]>>(
(acc, item) => {
const hotlisthit = Object.values(item.metadata?.hotlistMatches ?? {}).includes(true);
if (item.metadata?.npedJSON["NPED CATEGORY"] === "A") acc.npedCatA.push(item);
if (item.metadata?.npedJSON["NPED CATEGORY"] === "B") acc.npedCatB.push(item);
if (item.metadata?.npedJSON["NPED CATEGORY"] === "C") acc.npedCatC.push(item);
if (item.metadata?.npedJSON["NPED CATEGORY"] === "D") acc.npedCatD.push(item);
if (item.metadata?.npedJSON["TAX STATUS"] === false) acc.notTaxed.push(item);
if (item.metadata?.npedJSON["MOT STATUS"] === false) acc.notMOT.push(item);
if (hotlisthit) acc.hotlistHit.push(item);
acc.vehicles.push(item);
return acc;
},
{
@@ -34,9 +40,32 @@ const SessionCard = () => {
npedCatD: [],
notTaxed: [],
notMOT: [],
hotlistHit: [],
vehicles: [],
}
);
const handleStartClick = () => {
dispatch({ type: "SESSIONSTART", payload: !sessionStarted });
dispatch({ type: "SESSIONPAUSE", payload: false });
toast(`${sessionStarted ? "Vehicle tracking session ended" : "Vehicle tracking session started"}`);
};
const handlepauseClick = () => {
dispatch({ type: "SESSIONPAUSE", payload: !sessionPaused });
toast(`${sessionStarted ? "Vehicle tracking session paused" : "Vehicle tracking session resumed"}`);
};
const handleSaveCick = async () => {
const result = await mutation.mutateAsync({
operation: "INSERT",
path: "sessionStats",
value: dedupedSightings,
});
if (result.reason === "OK") toast.success("Session saved");
};
return (
<Card className="p-4 col-span-3">
<CardHeader title="Session" />
@@ -47,34 +76,72 @@ const SessionCard = () => {
} transition w-full`}
onClick={handleStartClick}
>
{sessionStarted ? "End Session" : "Start Session"}
<div className="flex flex-row gap-3 items-center justify-self-center">
<FontAwesomeIcon icon={sessionStarted ? faStop : faPlay} />
<p>{sessionStarted ? "End Session" : "Start Session"}</p>
</div>
</button>
<div className="flex flex-col lg:flex-row gap-5">
{sessionStarted && (
<button
className={`bg-blue-600 text-white px-4 py-2 rounded transition w-full lg:w-[50%]`}
onClick={handleSaveCick}
>
<div className="flex flex-row gap-3 items-center justify-self-center">
<FontAwesomeIcon icon={faFloppyDisk} />
<p>Save session</p>
</div>
</button>
)}
{sessionStarted && (
<button
className={`bg-gray-300 text-gray-800 px-4 py-2 rounded transition w-full lg:w-[50%]`}
onClick={handlepauseClick}
>
<div className="flex flex-row gap-3 items-center justify-self-center">
<FontAwesomeIcon icon={sessionPaused ? faPlay : faPause} />
<p>{sessionPaused ? "Resume session" : "Pause session"}</p>
</div>
</button>
)}
</div>
<ul className="text-white space-y-2">
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
<p>Number of Vehicles:</p>
<span className="font-bold text-green-600 text-xl">{dedupedSightings.length}</span>
</li>
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
<p>Vehicles without Tax:</p>
<span className="font-bold text-amber-600 text-xl">{vehicles.notTaxed.length}</span>
</li>
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
<p>Vehicles without MOT:</p>{" "}
<span className="font-bold text-red-500 text-xl">{vehicles.notMOT.length}</span>
</li>
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
<p>Vehicles with NPED Cat A:</p>
<span className="font-bold text-gray-300 text-xl">{vehicles.npedCatA.length}</span>
</li>
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
<p>Vehicles with NPED Cat B:</p>{" "}
<span className="font-bold text-gray-300text-xl">{vehicles.npedCatB.length}</span>
</li>
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
Vehicles with NPED Cat C:{" "}
<span className="font-bold text-gray-300 text-xl">{vehicles.npedCatC.length}</span>
</li>
<VehicleSessionItem
sessionNumber={vehicles.vehicles.length}
textColour="text-green-400"
vehicleTag={"Number of Vehicles sightings:"}
/>
<VehicleSessionItem
sessionNumber={vehicles.notTaxed.length}
textColour="text-amber-400"
vehicleTag={"Vehicles without Tax:"}
/>
<VehicleSessionItem
sessionNumber={vehicles.notMOT.length}
textColour="text-red-500"
vehicleTag={"Vehicles without MOT:"}
/>
<VehicleSessionItem
sessionNumber={vehicles.hotlistHit.length}
textColour="text-blue-400"
vehicleTag={"Vehicles on Hotlists:"}
/>
<VehicleSessionItem
sessionNumber={vehicles.npedCatA.length}
textColour="text-gray-300"
vehicleTag={"Vehicles with NPED Cat A:"}
/>
<VehicleSessionItem
sessionNumber={vehicles.npedCatB.length}
textColour="text-gray-300"
vehicleTag={"Vehicles with NPED Cat B:"}
/>
<VehicleSessionItem
sessionNumber={vehicles.npedCatC.length}
textColour="text-gray-300"
vehicleTag={"Vehicles with NPED Cat C:"}
/>
</ul>
</div>
</Card>

View File

@@ -1,41 +1,12 @@
import { Field, Form, Formik } from "formik";
import { Field, useFormikContext } from "formik";
import FormToggle from "../components/FormToggle";
import { useCameraOutput } from "../../../hooks/useCameraOutput";
import { cleanArray } from "../../../utils/utils";
import FormGroup from "../components/FormGroup";
import type { BearerTypeFieldType } from "../../../types/types";
export const ValuesComponent = () => {
return null;
};
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
const BearerTypeFields = () => {
const { dispatcherQuery, dispatcherMutation } = useCameraOutput();
const format = dispatcherQuery?.data?.propFormat?.value;
const rawOptions = dispatcherQuery?.data?.propFormat?.accepted;
const enabled = dispatcherQuery?.data?.propEnabled?.value;
const verbose = dispatcherQuery?.data?.propVerbose?.value;
const options = cleanArray(rawOptions);
const initialValues: BearerTypeFieldType = {
format: format ?? "JSON",
enabled: enabled === "true",
verbose: verbose === "true",
};
const handleSubmit = async (values: BearerTypeFieldType) => {
await dispatcherMutation.mutateAsync(values);
};
useFormikContext<BearerTypeFieldType & InitialValuesForm>();
return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize
>
{({ isSubmitting }) => (
<Form>
<div className="flex flex-col space-y-4 px-2">
<FormGroup>
<label htmlFor="format">Format</label>
@@ -45,31 +16,20 @@ const BearerTypeFields = () => {
id="format"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
{options?.map((option: string) => (
<option key={option} value={option}>
{option}
<option key={"JSON"} value={"JSON"}>
JSON
</option>
<option key={"BOF2"} value={"BOF2"}>
BOF2
</option>
))}
</Field>
</FormGroup>
<FormGroup>
<div className="flex flex-col space-y-4">
<FormToggle name="enabled" label="Enabled" />
<FormToggle name="verbose" label="Verbose" />
</div>
</FormGroup>
<button
type="submit"
className="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full md:w-[50%]"
>
{isSubmitting || dispatcherMutation.isPending
? "Saving..."
: "Save Changes"}
</button>
</div>
</Form>
)}
</Formik>
);
};

View File

@@ -1,12 +1,47 @@
import { useFormikContext, type FormikTouched } from "formik";
import Card from "../../UI/Card";
import CardHeader from "../../UI/CardHeader";
import ChannelFields from "./ChannelFields";
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
import { useCameraBackOfficeOutput } from "../../../hooks/useBackOfficeConfig";
import { useEffect, useMemo } from "react";
type ChannelCardProps = {
touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>;
isSubmitting: boolean;
};
const ChannelCard = ({ touched, isSubmitting }: ChannelCardProps) => {
const { values, setFieldValue } = useFormikContext<BearerTypeFieldType & InitialValuesForm>();
const { backOfficeQuery } = useCameraBackOfficeOutput(values?.format);
const mapped = useMemo(() => {
const d = backOfficeQuery.data;
return {
backOfficeURL: d?.propBackofficeURL?.value ?? "",
username: d?.propUsername?.value ?? "",
password: d?.propPassword?.value ?? "",
connectTimeoutSeconds: Number(d?.propConnectTimeoutSeconds?.value),
readTimeoutSeconds: Number(d?.propReadTimeoutSeconds?.value),
};
}, [backOfficeQuery.data]);
useEffect(() => {
if (!backOfficeQuery.isSuccess) return;
for (const [key, value] of Object.entries(mapped)) {
setFieldValue(key, value);
}
}, [backOfficeQuery.isSuccess, mapped, setFieldValue]);
const ChannelCard = () => {
return (
<Card className="p-4">
<CardHeader title="Channel 1 (JSON)" />
<ChannelFields />
<CardHeader title={`Channel (${values?.format})`} />
<ChannelFields
touched={touched}
isSubmitting={isSubmitting}
backOfficeData={backOfficeQuery}
format={values?.format}
/>
</Card>
);
};

View File

@@ -1,91 +1,52 @@
import { Field, Form, Formik, useFormikContext } from "formik";
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Field, useFormikContext, type FormikTouched } from "formik";
import FormGroup from "../components/FormGroup";
import { useEffect, useState } from "react";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useCameraOutput } from "../../../hooks/useCameraOutput";
import type {
InitialValuesForm,
InitialValuesFormErrors,
} from "../../../types/types";
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
import { toast } from "sonner";
import type { UseQueryResult } from "@tanstack/react-query";
const ChannelFields = () => {
type ChannelFieldsProps = {
touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>;
isSubmitting: boolean;
backOfficeData: UseQueryResult<any, Error>;
format?: string;
};
const ChannelFields = ({ touched, isSubmitting, format }: ChannelFieldsProps) => {
const [showPwd, setShowPwd] = useState(false);
const { backOfficeQuery, backOfficeMutation } = useCameraOutput();
const backOfficeURL = backOfficeQuery?.data?.propBackofficeURL?.value;
const username = backOfficeQuery?.data?.propUsername?.value;
const password = backOfficeQuery?.data?.propPassword?.value;
const connectTimeoutSeconds =
backOfficeQuery?.data?.propConnectTimeoutSeconds?.value;
const readTimeoutSeconds =
backOfficeQuery?.data?.propReadTimeoutSeconds?.value;
const initialValues: InitialValuesForm = {
backOfficeURL: backOfficeURL ?? "",
username: username ?? "",
password: password ?? "",
connectTimeoutSeconds: Number(connectTimeoutSeconds),
readTimeoutSeconds: Number(readTimeoutSeconds),
};
const handleSubmit = async (values: InitialValuesForm) => {
await backOfficeMutation.mutateAsync(values);
};
const { submitCount, isValid, values, errors } = useFormikContext<BearerTypeFieldType & InitialValuesForm>();
const ValidationToastOnce = () => {
const { submitCount, isValid } = useFormikContext();
useEffect(() => {
if (submitCount > 0 && !isValid) {
toast.error("Check fields are filled in");
}
}, [submitCount, isValid]);
}, []);
return null;
};
const validateValues = (
values: InitialValuesForm
): InitialValuesFormErrors => {
const errors: InitialValuesFormErrors = {};
const url = values.backOfficeURL?.trim();
const username = values.username?.trim();
const password = values.password?.trim();
if (!url) {
errors.backOfficeURL = "Required";
}
if (!username) errors.username = "Required";
if (!password) errors.password = "Required";
const read = Number(values.readTimeoutSeconds);
if (!Number.isFinite(read)) {
errors.readTimeoutSeconds = "Must be a number";
} else if (read < 0) {
errors.readTimeoutSeconds = "Must be ≥ 0";
}
const connect = Number(values.connectTimeoutSeconds);
if (!Number.isFinite(connect)) {
errors.connectTimeoutSeconds = "Must be a number";
} else if (connect < 0) {
errors.connectTimeoutSeconds = "Must be ≥ 0";
}
return errors;
};
return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize
validate={validateValues}
>
{({ errors, touched, isSubmitting }) => (
<Form>
<>
{format?.toLowerCase() !== "bof2" && format?.toLowerCase() !== "json" ? (
<>
<div className="mt-4 flex flex-col items-center justify-center rounded-2xl border border-slate-800 bg-slate-900/40 p-10 text-center">
<div className="mb-3 rounded-xl bg-slate-800 px-3 py-1 text-xs uppercase tracking-wider text-slate-400">
Format coming soon
</div>
<p className="max-w-md text-slate-300">
Output configuration currently supports <span className="font-bold text-blue-400">JSON</span> or{" "}
<span className="font-bold text-emerald-400">BOF2</span>. <br /> More formats will be added in future
updates.
</p>
</div>
</>
) : (
<>
<div className="flex flex-col space-y-2 px-2">
<FormGroup>
<label htmlFor="backoffice" className="m-0">
@@ -98,9 +59,7 @@ const ChannelFields = () => {
id="backoffice"
placeholder="https://www.backoffice.com"
className={`p-1.5 border ${
errors.backOfficeURL && touched.backOfficeURL
? "border-red-500"
: "border-gray-400 "
errors.backOfficeURL && touched.backOfficeURL ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
/>
</FormGroup>
@@ -112,9 +71,7 @@ const ChannelFields = () => {
id="username"
placeholder="Back office username"
className={`p-1.5 border ${
errors.username && touched.username
? "border-red-500"
: "border-gray-400 "
errors.username && touched.username ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
/>
</FormGroup>
@@ -127,9 +84,7 @@ const ChannelFields = () => {
id="password"
placeholder="Back office password"
className={`p-1.5 border ${
errors.password && touched.password
? "border-red-500"
: "border-gray-400 "
errors.password && touched.password ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
/>
<FontAwesomeIcon
@@ -142,17 +97,13 @@ const ChannelFields = () => {
</FormGroup>
<FormGroup>
<label htmlFor="connectTimeoutSeconds">
Connect Timeout Seconds
</label>
<label htmlFor="connectTimeoutSeconds">Connect Timeout Seconds</label>
<Field
name={"connectTimeoutSeconds"}
type="number"
id="connectTimeoutSeconds"
className={`p-1.5 border ${
errors.connectTimeoutSeconds && touched.connectTimeoutSeconds
? "border-red-500"
: "border-gray-400 "
errors.connectTimeoutSeconds && touched.connectTimeoutSeconds ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
/>
</FormGroup>
@@ -164,25 +115,82 @@ const ChannelFields = () => {
id="readTimeoutSeconds"
placeholder="https://example.com"
className={`p-1.5 border ${
errors.readTimeoutSeconds && touched.readTimeoutSeconds
? "border-red-500"
: "border-gray-400 "
errors.readTimeoutSeconds && touched.readTimeoutSeconds ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
/>
</FormGroup>
{format?.toLowerCase() === "bof2" && (
<>
<div className="border-b border-gray-500 my-3">
<h2 className="font-bold">{values.format} Constants</h2>
</div>
<FormGroup>
<label htmlFor="FFID">Feed ID / Force ID</label>
<Field
name={"FFID"}
type="text"
id="FFID"
placeholder="ABC123"
className={`p-1.5 border ${
errors.readTimeoutSeconds && touched.readTimeoutSeconds ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
/>
</FormGroup>
<FormGroup>
<label htmlFor="SCID">Source ID / Camera ID</label>
<Field
name={"SCID"}
type="text"
id="SCID"
placeholder="DEF345"
className={`p-1.5 border ${
errors.readTimeoutSeconds && touched.readTimeoutSeconds ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
/>
</FormGroup>
<FormGroup>
<label htmlFor="timestampSource">Timestamp Source</label>
<Field
name={"timestampSource"}
as="select"
id="timestampSource"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
<option value="">-- Select format --</option>
<option value={"UTC"}>UTC</option>
<option value={"local"}>Local</option>
</Field>
</FormGroup>
<FormGroup>
<label htmlFor="GPSFormat">GPS Format</label>
<Field
name={"GPSFormat"}
as="select"
id="GPSFormat"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
<option value="">-- Select format --</option>
<option value={"Decimal degrees"}>Decimal degrees</option>
<option value={"minutes"}>Minutes</option>
</Field>
</FormGroup>
</>
)}
</div>
<button
type="submit"
className="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full md:w-[50%]"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
>
{isSubmitting || backOfficeMutation.isPending
? "Saving..."
: "Save Changes"}
{isSubmitting ? "Saving..." : "Save Changes"}
</button>
<ValidationToastOnce />
</Form>
</>
)}
</Formik>
</>
);
};

View File

@@ -6,16 +6,18 @@ import { toast } from "sonner";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useState } from "react";
import { useIntegrationsContext } from "../../../context/IntegrationsContext";
const NPEDFields = () => {
const { state } = useIntegrationsContext();
const [showPwd, setShowPwd] = useState(false);
const { signIn, user, signOut } = useNPEDAuth();
const { signIn, signOut } = useNPEDAuth();
const initialValues = user
const initialValues = state.npedUser
? {
username: user?.propUsername?.value,
password: user?.propPassword?.value,
clientId: user?.propClientID?.value,
username: state.npedUser?.propUsername?.value,
password: state.npedUser?.propPassword?.value,
clientId: state.npedUser?.propClientID?.value,
frontId: "NPED",
rearId: "NPED",
}
@@ -48,20 +50,13 @@ const NPEDFields = () => {
};
return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
validate={validateValues}
enableReinitialize
>
<Formik initialValues={initialValues} onSubmit={handleSubmit} validate={validateValues} enableReinitialize>
{({ errors, touched, isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2">
<FormGroup>
<label htmlFor="username">Username</label>
{touched.username && errors.username && (
<small className="absolute right-0 -top-5 text-red-500">
{errors.username}
</small>
<small className="absolute right-0 -top-5 text-red-500">{errors.username}</small>
)}
<Field
name="username"
@@ -82,9 +77,7 @@ const NPEDFields = () => {
className="p-2 border border-gray-400 rounded-lg w-full"
/>
{touched.password && errors.password && (
<small className="absolute right-0 -top-5 text-red-500">
{errors.password}
</small>
<small className="absolute right-0 -top-5 text-red-500">{errors.password}</small>
)}
<FontAwesomeIcon
type="button"
@@ -97,9 +90,7 @@ const NPEDFields = () => {
<FormGroup>
<label htmlFor="clientId">Client ID</label>
{touched.clientId && errors.clientId && (
<small className="absolute right-0 -top-5 text-red-500">
{errors.clientId}
</small>
<small className="absolute right-0 -top-5 text-red-500">{errors.clientId}</small>
)}
<Field
name="clientId"
@@ -109,7 +100,7 @@ const NPEDFields = () => {
className="p-1.5 border border-gray-400 rounded-lg"
/>
</FormGroup>
{!user?.propClientID?.value ? (
{!state.npedUser?.propClientID?.value ? (
<button
type="submit"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5 hover:cursor-pointer"

View File

@@ -31,7 +31,7 @@ const NPEDHotlist = () => {
type="file"
name="file"
id="file"
className="file:px-3 file:border file:border-gray-500 file:rounded-lg file:bg-blue-800 file:mr-5"
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) {
if (e.target.files[0].type !== "text/csv") {

View File

@@ -1,12 +1,120 @@
import { Form, Formik } from "formik";
import BearerTypeCard from "../BearerType/BearerTypeCard";
import ChannelCard from "../Channel1-JSON/ChannelCard";
import { useCameraOutput, useGetDispatcherConfig } from "../../../hooks/useCameraOutput";
import type {
BearerTypeFieldType,
InitialValuesForm,
InitialValuesFormErrors,
OptionalBOF2Constants,
} from "../../../types/types";
import { useQueryClient } from "@tanstack/react-query";
import { useUpdateBackOfficeConfig } from "../../../hooks/useBackOfficeConfig";
import { useFormVaidate } from "../../../hooks/useFormValidate";
const SettingForms = () => {
const qc = useQueryClient();
const { dispatcherQuery, dispatcherMutation, backOfficeDispatcherMutation } = useCameraOutput();
const { backOfficeMutation } = useUpdateBackOfficeConfig();
const { bof2ConstantsQuery } = useGetDispatcherConfig();
const { validateMutation } = useFormVaidate();
const format = dispatcherQuery?.data?.propFormat?.value;
const enabled = dispatcherQuery?.data?.propEnabled?.value;
const FFID = bof2ConstantsQuery?.data?.propFeedIdentifier?.value;
const SCID = bof2ConstantsQuery?.data?.propSourceIdentifier?.value;
const GPSFormat = bof2ConstantsQuery?.data?.propGpsFormat?.value;
const timestampSource = bof2ConstantsQuery?.data?.propTimeZoneType?.value;
const initialValues: BearerTypeFieldType & InitialValuesForm & OptionalBOF2Constants = {
format: format ?? "JSON",
enabled: enabled === "true",
backOfficeURL: "",
username: "",
password: "",
connectTimeoutSeconds: Number(5),
readTimeoutSeconds: Number(15),
// Bof2 - optional constants
FFID: FFID ?? "",
SCID: SCID ?? "",
timestampSource: timestampSource ?? "",
GPSFormat: GPSFormat ?? "",
};
const validateValues = (values: InitialValuesForm): InitialValuesFormErrors => {
const errors: InitialValuesFormErrors = {};
const url = values.backOfficeURL?.trim();
const username = values.username?.trim();
const password = values.password?.trim();
if (!url) {
errors.backOfficeURL = "Required";
}
if (!username) errors.username = "Required";
if (!password) errors.password = "Required";
const read = Number(values.readTimeoutSeconds);
if (!Number.isFinite(read)) {
errors.readTimeoutSeconds = "Must be a number";
} else if (read < 0) {
errors.readTimeoutSeconds = "Must be ≥ 0";
}
const connect = Number(values.connectTimeoutSeconds);
if (!Number.isFinite(connect)) {
errors.connectTimeoutSeconds = "Must be a number";
} else if (connect < 0) {
errors.connectTimeoutSeconds = "Must be ≥ 0";
}
return errors;
};
const handleSubmit = async (values: BearerTypeFieldType & InitialValuesForm & OptionalBOF2Constants) => {
// if (formErrors && Object.entries(formErrors).length > 0) {
// return;
// }
const dispatcherData = {
format: values.format,
enabled: values.enabled,
};
const result = await dispatcherMutation.mutateAsync(dispatcherData);
if (result?.id) {
qc.invalidateQueries({ queryKey: ["dispatcher"] });
qc.invalidateQueries({ queryKey: ["backoffice", values.format] });
const validResponse = await validateMutation.mutateAsync(values);
if (validResponse?.reason === "OK") {
await backOfficeMutation.mutateAsync(values);
} else {
return;
}
}
if (values.format.toLowerCase() === "bof2") {
const bof2ConstantsData: OptionalBOF2Constants = {
FFID: values.FFID,
SCID: values.SCID,
timestampSource: values.timestampSource,
GPSFormat: values.GPSFormat,
};
await backOfficeDispatcherMutation.mutateAsync(bof2ConstantsData);
}
};
return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} validate={validateValues} enableReinitialize>
{({ isSubmitting, touched }) => (
<Form>
<div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-2 sm:px-4 lg:px-0 w-full">
<BearerTypeCard />
<ChannelCard />
<ChannelCard touched={touched} isSubmitting={isSubmitting} />
</div>
</Form>
)}
</Formik>
);
};

View File

@@ -4,7 +4,7 @@ import SoundSettingsFields from "./SoundSettingsFields";
const SoundSettingsCard = () => {
return (
<Card className="p-4">
<Card className="p-4 col-span-5 w-full">
<CardHeader title={"Sound Settings"} />
<SoundSettingsFields />
</Card>

View File

@@ -1,9 +1,10 @@
import { Field, FieldArray, Form, Formik } from "formik";
import { Field, Form, Formik } from "formik";
import FormGroup from "../components/FormGroup";
import type { FormValues, Hotlist } from "../../../types/types";
import { useSoundContext } from "../../../context/SoundContext";
import { useCameraBlackboard } from "../../../hooks/useCameraBlackboard";
import { toast } from "sonner";
import SliderComponent from "../../UI/Slider";
const SoundSettingsFields = () => {
const { state, dispatch } = useSoundContext();
@@ -12,22 +13,31 @@ const SoundSettingsFields = () => {
const hotlists: Hotlist[] = state.hotlists;
const soundOptions = state?.soundOptions?.map((soundOption) => ({
value: soundOption?.name,
value: soundOption?.soundFileName,
label: soundOption?.name,
}));
const initialValues: FormValues = {
sightingSound: state.sightingSound ?? "switch",
NPEDsound: state.NPEDsound ?? "popup",
hotlistSound: state.hotlistSound ?? "notification",
hotlists,
};
const handleSubmit = async (values: FormValues) => {
dispatch({ type: "UPDATE", payload: values });
const updatedValues = {
...values,
sightingVolume: state.sightingVolume,
NPEDsoundVolume: state.NPEDsoundVolume,
hotlistSoundVolume: state.hotlistSoundVolume,
soundOptions: [...(state.soundOptions ?? [])],
};
dispatch({ type: "UPDATE", payload: updatedValues });
const result = await mutation.mutateAsync({
operation: "INSERT",
path: "soundSettings",
value: values,
value: updatedValues,
});
if (result.reason !== "OK") {
toast.error("Cannot update sound settings");
@@ -37,9 +47,10 @@ const SoundSettingsFields = () => {
};
return (
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
{({ values }) => (
{() => (
<Form className="flex flex-col space-y-3">
<FormGroup>
<div className="flex flex-col md:flex-row space-y-2 w-full justify-between gap-3">
<label htmlFor="sightingSound">Sighting Sound</label>
<Field
as="select"
@@ -48,14 +59,17 @@ const SoundSettingsFields = () => {
>
{soundOptions?.map(({ value, label }) => {
return (
<option key={value} value={value}>
<option key={label} value={value}>
{label}
</option>
);
})}
</Field>
<SliderComponent soundCategory="SIGHTINGVOLUME" />
</div>
</FormGroup>
<FormGroup>
<div className="flex flex-col md:flex-row space-y-2 w-full justify-between gap-3">
<label htmlFor="NPEDsound">NPED notification Sound</label>
<Field
as="select"
@@ -68,24 +82,37 @@ const SoundSettingsFields = () => {
</option>
))}
</Field>
<SliderComponent soundCategory="NPEDVOLUME" />
</div>
</FormGroup>
<div>
<h3 className="text-lg font-semibold mb-2">Hotlist Sounds</h3>
<FormGroup>
<div className="flex flex-col md:flex-row space-y-2 w-full justify-between gap-3">
<label htmlFor="hotlistSound">All hotlist Sounds</label>
<Field
as="select"
name="hotlistSound"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
{soundOptions?.map(({ value, label }) => (
<option key={value} value={value}>
{label}
</option>
))}
</Field>
<SliderComponent soundCategory="HOTLISTVOLUME" />
</div>
</FormGroup>
{/* <FormGroup>
<FieldArray
name="hotlists"
render={() => (
<div className="w-full m-2">
{values?.hotlists?.length > 0 ? (
values?.hotlists?.map((hotlist, index) => (
<div
key={hotlist.name}
className="flex items-center m-2 w-full justify-between"
>
<label
htmlFor={`hotlists.${index}.sound`}
className="w-32 shrink-0"
>
<div key={hotlist.name} className="flex items-center m-2 w-full justify-between">
<label htmlFor={`hotlists.${index}.sound`} className="w-32 shrink-0">
{hotlist.name}
</label>
<Field
@@ -108,7 +135,7 @@ const SoundSettingsFields = () => {
</div>
)}
/>
</FormGroup>
</FormGroup> */}
</div>
<button
type="submit"

View File

@@ -3,45 +3,80 @@ import FormGroup from "../components/FormGroup";
import type { SoundUploadValue } from "../../../types/types";
import { useSoundContext } from "../../../context/SoundContext";
import { toast } from "sonner";
import { useCameraBlackboard } from "../../../hooks/useCameraBlackboard";
import { useFileUpload } from "../../../hooks/useFileUpload";
const SoundUpload = () => {
const { dispatch } = useSoundContext();
const { state, dispatch } = useSoundContext();
const { mutation } = useCameraBlackboard();
const { mutation: fileMutation } = useFileUpload({
queryKey: state.sightingSound ? [state.sightingSound] : undefined,
});
const initialValues: SoundUploadValue = {
name: "",
soundFile: null,
soundFileName: "",
soundUrl: "",
uploadedAt: Date.now(),
};
const handleSubmit = (values: SoundUploadValue) => {
const handleSubmit = async (values: SoundUploadValue) => {
if (!values.soundFile) {
toast.warning("Please select an audio file");
} else {
dispatch({ type: "ADD", payload: values });
toast.success("Sound file upload successfully");
return;
}
const alreadyExists = state?.soundOptions?.some((soundOption) => soundOption.name === values.name);
if (state.soundOptions?.includes(values) || alreadyExists) {
toast.warning("Sound already in list");
return;
}
const updatedValues = {
...state,
soundOptions: [...(state.soundOptions ?? []), values],
};
const result = await mutation.mutateAsync({
operation: "INSERT",
path: "soundSettings",
value: updatedValues,
});
await fileMutation.mutateAsync(values.soundFile);
if (result.reason !== "OK") {
toast.error("Cannot update sound settings");
}
dispatch({ type: "ADD", payload: values });
};
return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize
>
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
{({ setFieldValue, errors, setFieldError }) => (
<Form>
<label htmlFor="soundFile" className="">
Sound File
</label>
<FormGroup>
<label htmlFor="soundFile">Sound File</label>
<input
type="file"
name="soundFile"
id="sightingSoundinput"
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"
) {
if (e.target?.files && e.target?.files[0]?.type === "audio/mpeg") {
const url = URL.createObjectURL(e.target.files[0]);
setFieldValue("soundUrl", url);
setFieldValue("name", e.target.files[0].name);
setFieldValue("soundFileName", e.target.files[0].name);
setFieldValue("soundFile", e.target.files[0]);
setFieldValue("uploadedAt", Date.now());
if (e?.target?.files[0]?.size >= 1 * 1024 * 1024) {
setFieldError("soundFile", "larger than 1mb");
toast.error("File larger than 1MB");
return;
}
} else {
setFieldError("soundFile", "Not an mp3 file");
toast.error("Not an mp3 file");
@@ -49,12 +84,19 @@ const SoundUpload = () => {
}}
/>
</FormGroup>
{errors.soundFile && (
<p className="text-red-500 text-sm mt-1">Not an mp3 file</p>
)}
<div className="mt-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">
Uploaded Sound files will appear in the <span className="font-bold">drop downs</span> once they are
uploaded. They can be used for any <span className="text-blue-400">Sighting,</span>{" "}
<span className="text-emerald-400">Hotlist</span> or <span className="text-amber-600">NPED</span> hits.
</p>
</div>
{errors.soundFile && <p className="text-red-500 text-sm mt-1">Not an mp3 file</p>}
<button
type="submit"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5 mt-[5%]"
disabled={errors.soundFile ? true : false}
>
Upload

View File

@@ -4,7 +4,7 @@ import SoundUpload from "./SoundUpload";
const SoundUploadCard = () => {
return (
<Card className="p-4">
<Card className="p-4 col-span-5 lg:col-span-3 w-full">
<CardHeader title={"Sound upload"} />
<SoundUpload />
</Card>

View File

@@ -7,8 +7,7 @@ import type { SystemValues, SystemValuesErrors } from "../../../types/types";
import { useSystemConfig } from "../../../hooks/useSystemConfig";
const SystemConfigFields = () => {
const { saveSystemSettings, systemSettingsData, saveSystemSettingsLoading } =
useSystemConfig();
const { saveSystemSettings, systemSettingsData, saveSystemSettingsLoading } = useSystemConfig();
const { softRebootMutation, hardRebootMutation } = useReboots();
const initialvalues: SystemValues = {
@@ -26,8 +25,7 @@ const SystemConfigFields = () => {
const interval = Number(values.sntpInterval);
if (!values.deviceName) errors.deviceName = "Required";
if (!values.timeZone) errors.timeZone = "Required";
if (isNaN(interval) || interval <= 0)
errors.sntpInterval = "Cannot be less than 0";
if (isNaN(interval) || interval <= 0) errors.sntpInterval = "Cannot be less than 0";
if (!values.sntpServer) errors.sntpServer = "Required";
return errors;
};
@@ -52,16 +50,11 @@ const SystemConfigFields = () => {
{({ values, errors, touched, isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2">
<FormGroup>
<label
htmlFor="deviceName"
className="font-medium whitespace-nowrap md:w-1/2 text-left"
>
<label htmlFor="deviceName" className="font-medium whitespace-nowrap md:w-1/2 text-left">
Device Name
</label>
{touched.deviceName && errors.deviceName && (
<small className="absolute right-0 -top-5 text-red-500">
{errors.deviceName}
</small>
<small className="absolute right-0 -top-5 text-red-500">{errors.deviceName}</small>
)}
<Field
id="deviceName"
@@ -73,16 +66,11 @@ const SystemConfigFields = () => {
/>
</FormGroup>
<FormGroup>
<label
htmlFor="timeZone"
className="font-medium whitespace-nowrap md:w-1/2 text-left"
>
<label htmlFor="timeZone" className="font-medium whitespace-nowrap md:w-1/2 text-left">
Local Time Zone
</label>
{touched.timeZone && errors.timeZone && (
<small className="absolute right-0 -top-5 text-red-500">
{errors.timeZone}
</small>
<small className="absolute right-0 -top-5 text-red-500">{errors.timeZone}</small>
)}
<Field
id="timeZone"
@@ -99,16 +87,11 @@ const SystemConfigFields = () => {
</Field>
</FormGroup>
<FormGroup>
<label
htmlFor="sntpServer"
className="font-medium whitespace-nowrap md:w-1/2 text-left"
>
<label htmlFor="sntpServer" className="font-medium whitespace-nowrap md:w-1/2 text-left">
SNTP Server
</label>
{touched.sntpServer && errors.sntpServer && (
<small className="absolute right-0 -top-5 text-red-500">
{errors.sntpServer}
</small>
<small className="absolute right-0 -top-5 text-red-500">{errors.sntpServer}</small>
)}
<Field
id="sntpServer"
@@ -120,16 +103,11 @@ const SystemConfigFields = () => {
/>
</FormGroup>
<FormGroup>
<label
htmlFor="sntpInterval"
className="font-medium whitespace-nowrap md:w-1/2 text-left"
>
<label htmlFor="sntpInterval" className="font-medium whitespace-nowrap md:w-1/2 text-left">
SNTP Interval minutes
</label>
{touched.sntpInterval && errors.sntpInterval && (
<small className="absolute right-0 -top-5 text-red-500">
{errors.sntpInterval}
</small>
<small className="absolute right-0 -top-5 text-red-500">{errors.sntpInterval}</small>
)}
<Field
id="sntpInterval"
@@ -142,15 +120,12 @@ const SystemConfigFields = () => {
</FormGroup>
<button
type="submit"
className="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full md:w-[50%]"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
disabled={isSubmitting}
>
{saveSystemSettingsLoading ? "Saving..." : "Save System Settings"}
</button>
<SystemFileUpload
name={"softwareUpdate"}
selectedFile={values.softwareUpdate}
/>
<SystemFileUpload name={"softwareUpdate"} selectedFile={values.softwareUpdate} />
<div className="border-b border-gray-600">
<p>Reboot</p>
</div>
@@ -160,18 +135,14 @@ const SystemConfigFields = () => {
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full md:w-[50%]"
onClick={handleSoftReboot}
>
{softRebootMutation.isPending || isSubmitting
? "Rebooting..."
: "Software Reboot"}
{softRebootMutation.isPending || isSubmitting ? "Rebooting..." : "Software Reboot"}
</button>
<button
type="button"
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full md:w-[50%]"
onClick={handleHardReboot}
>
{hardRebootMutation.isPending || isSubmitting
? "Rebooting"
: "Hardware Reboot"}
{hardRebootMutation.isPending || isSubmitting ? "Rebooting" : "Hardware Reboot"}
</button>
</Form>
)}

View File

@@ -36,7 +36,7 @@ const SystemFileUpload = ({ name, selectedFile }: SystemFileUploadProps) => {
type="file"
name="softwareUpdate"
id="softwareUpdate"
className="file:px-10 file:border file:border-gray-500 file:rounded-lg file:bg-blue-800 file:mr-5 w-full max-w-xs"
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={(event) => {
const file = event.currentTarget.files?.[0];
if (!file) {
@@ -44,8 +44,7 @@ const SystemFileUpload = ({ name, selectedFile }: SystemFileUploadProps) => {
return;
}
if (file?.size > 8 * 1024 * 1024)
toast.error("File is too large (max 8MB).");
if (file?.size > 8 * 1024 * 1024) toast.error("File is too large (max 8MB).");
setFieldValue(name, file);
}}
/>
@@ -53,7 +52,7 @@ const SystemFileUpload = ({ name, selectedFile }: SystemFileUploadProps) => {
</FormGroup>
<button
type="button"
className="w-full md:w-[50%] text-white bg-[#26B170] hover:bg-green-700 font-small rounded-lg text-sm px-2 py-2.5 disabled:opacity-50 disabled:cursor-not-allowed"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5 disabled:opacity-50 disabled:cursor-not-allowed"
disabled={!selectedFile}
onClick={handleFileUploadClick}
>

View File

@@ -10,10 +10,7 @@ type BlobFileUpload = {
};
};
export async function sendBlobFileUpload({
file,
opts,
}: BlobFileUpload): Promise<string> {
export async function sendBlobFileUpload({ file, opts }: BlobFileUpload): Promise<string> {
if (!file) throw new Error("No file supplied");
if (!opts?.uploadUrl) throw new Error("No URL supplied");
@@ -42,9 +39,7 @@ export async function sendBlobFileUpload({
const bodyText = await resp.text();
if (!resp.ok) {
throw new Error(
`Upload failed (${resp.status} ${resp.statusText}) from ${opts.uploadUrl}${bodyText}`
);
throw new Error(`Upload failed (${resp.status} ${resp.statusText}) from ${opts.uploadUrl}${bodyText}`);
}
return bodyText;
@@ -54,9 +49,7 @@ export async function sendBlobFileUpload({
}
// In browsers, fetch throws TypeError on network-level failures
if (err instanceof TypeError) {
throw new Error(
`HTTP error uploading to ${opts.uploadUrl}: ${err.message}`
);
throw new Error(`HTTP error uploading to ${opts.uploadUrl}: ${err.message}`);
}
// Todo: fix error message response
return `Hotlist Load OK`;

View File

@@ -56,23 +56,13 @@ const ModemSettings = () => {
return (
<>
<ModemToggle
showSettings={showSettings}
onShowSettings={setShowSettings}
/>
<ModemToggle showSettings={showSettings} onShowSettings={setShowSettings} />
{!showSettings && (
<Formik
initialValues={inititalValues}
onSubmit={handleSubmit}
enableReinitialize
>
<Formik initialValues={inititalValues} onSubmit={handleSubmit} enableReinitialize>
{({ isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2">
<FormGroup>
<label
htmlFor="apn"
className="font-medium whitespace-nowrap md:w-2/3"
>
<label htmlFor="apn" className="font-medium whitespace-nowrap md:w-2/3">
APN
</label>
<Field
@@ -84,10 +74,7 @@ const ModemSettings = () => {
/>
</FormGroup>
<FormGroup>
<label
htmlFor="username"
className="font-medium whitespace-nowrap md:w-2/3"
>
<label htmlFor="username" className="font-medium whitespace-nowrap md:w-2/3">
Username
</label>
<Field
@@ -99,10 +86,7 @@ const ModemSettings = () => {
/>
</FormGroup>
<FormGroup>
<label
htmlFor="password"
className="font-medium whitespace-nowrap md:w-2/3"
>
<label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">
Password
</label>
<div className="flex gap-2 items-center relative mb-4">
@@ -122,10 +106,7 @@ const ModemSettings = () => {
</div>
</FormGroup>
<FormGroup>
<label
htmlFor="password"
className="font-medium whitespace-nowrap md:w-2/3"
>
<label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">
Password
</label>
<Field
@@ -140,11 +121,9 @@ const ModemSettings = () => {
</FormGroup>
<button
type="submit"
className="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full md:w-[50%]"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
>
{isSubmitting || modemMutation.isPending
? "Saving..."
: "Save Modem settings"}
{isSubmitting || modemMutation.isPending ? "Saving..." : "Save Modem settings"}
</button>
</Form>
)}

View File

@@ -37,18 +37,11 @@ const WiFiSettingsForm = () => {
await wifiMutation.mutateAsync(wifiConfig);
};
return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize
>
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
{({ isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2">
<FormGroup>
<label
htmlFor="ssid"
className="font-medium whitespace-nowrap md:w-2/3"
>
<label htmlFor="ssid" className="font-medium whitespace-nowrap md:w-2/3">
SSID
</label>
<Field
@@ -60,10 +53,7 @@ const WiFiSettingsForm = () => {
/>
</FormGroup>
<FormGroup>
<label
htmlFor="password"
className="font-medium whitespace-nowrap md:w-2/3"
>
<label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">
Password
</label>
<div className="flex gap-2 items-center relative mb-4">
@@ -83,10 +73,7 @@ const WiFiSettingsForm = () => {
</div>
</FormGroup>
<FormGroup>
<label
htmlFor="encryption"
className="font-medium whitespace-nowrap md:w-2/3"
>
<label htmlFor="encryption" className="font-medium whitespace-nowrap md:w-2/3">
WPA/Encryption Type
</label>
<Field
@@ -103,11 +90,9 @@ const WiFiSettingsForm = () => {
</FormGroup>
<button
type="submit"
className="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full md:w-[50%]"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
>
{isSubmitting || wifiMutation.isPending
? "Saving..."
: " Save WiFi settings"}
{isSubmitting || wifiMutation.isPending ? "Saving..." : " Save WiFi settings"}
</button>
</Form>
)}

View File

@@ -5,11 +5,7 @@ type FormGroupProps = {
};
const FormGroup = ({ children }: FormGroupProps) => {
return (
<div className="flex flex-col md:flex-row md:items-center justify-between relative">
{children}
</div>
);
return <div className="flex flex-col md:flex-row md:items-center justify-between relative space-y-2">{children}</div>;
};
export default FormGroup;

View File

@@ -23,8 +23,7 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
const { dispatch } = useAlertHitContext();
const { query, mutation } = useCameraBlackboard();
const hotlistName = getHotlistName(sighting?.metadata?.hotlistMatches);
const hotlistNames = getHotlistName(sighting?.metadata?.hotlistMatches);
const handleAcknowledgeButton = () => {
try {
if (!sighting) {
@@ -109,7 +108,7 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
onClick={handleAcknowledgeButton}
>
<FontAwesomeIcon icon={faCheck} />
Accept
Acknowledge
</button>
)}
</div>
@@ -117,16 +116,6 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
<div className="flex flex-col md:flex-row gap-3 items-center">
<NumberPlate vrm={sighting?.vrm} motion={motionAway} />
<img src={sighting?.plateUrlColour} alt="plate patch" className="h-16 object-contain rounded-md" />
{hotlistName && (
<div>
<p className="text-gray-300">Hotlist</p>
<div className="items-center px-2.5 py-0.5 rounded-sm me-2 bg-amber-500">
<p className="font-medium text-2xl break-all text-amber-800">
{hotlistName ? hotlistName[0] : "-"}
</p>
</div>
</div>
)}
</div>
{isHotListHit && <img src={HotListImg} alt="hotlistHit" className="h-20 object-contain rounded-md" />}
@@ -134,6 +123,20 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
{isNPEDHitB && <img src={NPED_CAT_B} alt="hotlistHit" className="h-20 object-contain rounded-md" />}
{isNPEDHitC && <img src={NPED_CAT_C} alt="hotlistHit" className="h-20 object-contain rounded-md" />}
</div>
{hotlistNames && (
<div className="flex flex-col border-b border-gray-600 mb-4">
<p className="text-gray-300">Hotlists</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-[90%] lg:gap-x-[15%] w-[50%]">
{hotlistNames.map((hotlistName, index) => (
<div className="items-center px-2.5 py-0.5 rounded-sm me-2 bg-amber-500 w-55 m-2" key={index}>
<p className="font-medium text-2xl break-all text-amber-800">
{hotlistName ? hotlistName?.replace(/\.csv$/i, "") : "-"}
</p>
</div>
))}
</div>
</div>
)}
<div className="flex flex-col lg:flex-row items-center gap-3">
<img
src={sighting?.overviewUrl}
@@ -157,18 +160,26 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
<dd className="font-medium text-2xl">{sighting?.seenCount ?? "-"}</dd>
</div>
{sighting?.make && (
<div>
<dt className="text-gray-300">Make</dt>
<dd className="font-medium text-2xl">{sighting?.make ?? "-"}</dd>
</div>
)}
{sighting?.model ||
(!sighting?.model.trim() && (
<div>
<dt className="text-gray-300">Model</dt>
<dd className="font-medium text-2xl">{sighting?.model ?? "-"}</dd>
</div>
))}
{sighting?.color && (
<div className="sm:col-span-2">
<dt className="text-gray-300">Colour</dt>
<dd className="font-medium text-2xl">{sighting?.color ?? "-"}</dd>
</div>
)}
<div>
<dt className="text-gray-300">Time</dt>
<dd className="font-medium text-xl">{sighting?.timeStamp ?? "-"}</dd>
@@ -192,7 +203,7 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
onClick={handleAcknowledgeButton}
>
<FontAwesomeIcon icon={faCheck} />
Accept
Acknowledge
</button>
)}
{onDelete ? (

View File

@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ReducedSightingType, SightingType } from "../../types/types";
import { BLANK_IMG, getSoundFileURL } from "../../utils/utils";
import type { HitKind, QueuedHit, ReducedSightingType, SightingType } from "../../types/types";
import { BLANK_IMG } from "../../utils/utils";
import NumberPlate from "../PlateStack/NumberPlate";
import Card from "../UI/Card";
import CardHeader from "../UI/CardHeader";
@@ -15,10 +15,11 @@ import NPED_CAT_C from "/NPED_Cat_C.svg";
import popup from "../../assets/sounds/ui/popup_open.mp3";
import notification from "../../assets/sounds/ui/notification.mp3";
import { useSound } from "react-sounds";
import { useNPEDContext } from "../../context/NPEDUserContext";
import { useIntegrationsContext } from "../../context/IntegrationsContext";
import { useSoundContext } from "../../context/SoundContext";
import Loading from "../UI/Loading";
import { checkIsHotListHit, getNPEDCategory } from "../../utils/utils";
import { useCachedSoundSrc } from "../../hooks/usecachedSoundSrc";
function useNow(tickMs = 1000) {
const [, setNow] = useState(() => Date.now());
@@ -38,23 +39,16 @@ type SightingHistoryProps = {
className?: string;
};
export default function SightingHistoryWidget({
className,
title,
}: SightingHistoryProps) {
export default function SightingHistoryWidget({ className, title }: SightingHistoryProps) {
const [modalQueue, setModalQueue] = useState<QueuedHit[]>([]);
useNow(1000);
const { state } = useSoundContext();
const soundSrcNped = useMemo(() => {
return getSoundFileURL(state.NPEDsound) ?? popup;
}, [state.NPEDsound]);
const { src: soundSrcHotlist } = useCachedSoundSrc(state?.hotlistSound, state?.soundOptions, notification);
const { src: soundSrcNped } = useCachedSoundSrc(state?.NPEDsound, state?.soundOptions, popup);
const soundSrcHotlist = useMemo(() => {
return getSoundFileURL(state?.hotlists?.[0]?.sound) ?? notification;
}, [state.hotlists]);
const { play: npedSound } = useSound(soundSrcNped);
const { play: hotlistsound } = useSound(soundSrcHotlist);
const { play: npedSound } = useSound(soundSrcNped, { volume: state.NPEDsoundVolume });
const { play: hotlistsound } = useSound(soundSrcHotlist, { volume: state.hotlistSoundVolume });
const {
sightings,
setSelectedSighting,
@@ -66,13 +60,23 @@ export default function SightingHistoryWidget({
} = useSightingFeedContext();
const { dispatch } = useAlertHitContext();
const { sessionStarted, setSessionList, sessionList } = useNPEDContext();
const { state: integrationState, dispatch: integrationDispatch } = useIntegrationsContext();
const sessionStarted = integrationState.sessionStarted;
const sessionPaused = integrationState.sessionPaused;
const processedRefs = useRef<Set<number | string>>(new Set());
const hasAutoOpenedRef = useRef(false);
const npedRef = useRef(false);
const enqueue = useCallback((sighting: SightingType, kind: HitKind) => {
const id = sighting.vrm ?? sighting.ref;
if (processedRefs.current.has(id)) return;
processedRefs.current.add(id);
setModalQueue((q) => [...q, { id, sighting, kind }]);
}, []);
const reduceObject = (obj: SightingType): ReducedSightingType => {
return {
vrm: obj.vrm,
@@ -83,11 +87,12 @@ export default function SightingHistoryWidget({
useEffect(() => {
if (sessionStarted) {
if (!mostRecent) return;
if (sessionPaused) return;
const reducedMostRecent = reduceObject(mostRecent);
setSessionList([...sessionList, reducedMostRecent]);
integrationDispatch({ type: "ADD", payload: reducedMostRecent });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [mostRecent, sessionStarted, setSessionList]);
}, [mostRecent, sessionStarted]);
const onRowClick = useCallback(
(sighting: SightingType) => {
@@ -98,10 +103,7 @@ export default function SightingHistoryWidget({
[setSelectedSighting, setSightingModalOpen]
);
const rows = useMemo(
() => sightings?.filter(Boolean) as SightingType[],
[sightings]
);
const rows = useMemo(() => sightings?.filter(Boolean) as SightingType[], [sightings]);
useEffect(() => {
if (!rows?.length) return;
@@ -110,32 +112,15 @@ export default function SightingHistoryWidget({
const id = sighting.vrm;
if (processedRefs.current.has(id)) continue;
const isHot = checkIsHotListHit(sighting);
const cat = sighting?.metadata?.npedJSON?.["NPED CATEGORY"];
const isHotlistHit = checkIsHotListHit(sighting);
const npedcategory = sighting?.metadata?.npedJSON?.["NPED CATEGORY"];
const isNPED = npedcategory === "A" || npedcategory === "B" || npedcategory === "C";
if (cat === "A" || cat === "B" || cat === "C") {
npedSound();
setSelectedSighting(sighting);
setSightingModalOpen(true);
processedRefs.current.add(id);
break; // stop after one new open per render cycle
}
if (isHot) {
hotlistsound();
setSelectedSighting(sighting);
setSightingModalOpen(true);
processedRefs.current.add(id);
break;
if (isNPED || isHotlistHit) {
enqueue(sighting, isNPED ? "NPED" : "HOTLIST"); // enqueue ONLY
}
}
}, [
rows,
hotlistsound,
npedSound,
setSightingModalOpen,
setSelectedSighting,
]);
}, [rows, enqueue]);
useEffect(() => {
rows?.forEach((obj) => {
@@ -168,31 +153,37 @@ export default function SightingHistoryWidget({
});
if (firstNPED) {
setSelectedSighting(firstNPED);
npedSound();
setSightingModalOpen(true);
enqueue(firstNPED, "NPED");
npedRef.current = true;
}
if (firstHot) {
setSelectedSighting(firstHot);
hotlistsound();
setSightingModalOpen(true);
enqueue(firstHot, "HOTLIST");
hasAutoOpenedRef.current = true;
}
}, [hotlistsound, npedSound, setSelectedSighting]);
}, [enqueue, hotlistsound, npedSound, rows, setSelectedSighting, setSightingModalOpen]);
useEffect(() => {
if (!isSightingModalOpen && modalQueue.length > 0) {
const next = modalQueue[0];
if (next.kind === "NPED") npedSound();
else hotlistsound();
setSelectedSighting(next.sighting);
setSightingModalOpen(true);
}
}, [isSightingModalOpen, npedSound, hotlistsound, setSelectedSighting, setSightingModalOpen, modalQueue]);
const handleClose = () => {
setSightingModalOpen(false);
setModalQueue((q) => q.slice(1));
};
return (
<>
<Card
className={clsx(
"overflow-y-auto min-h-[40vh] md:min-h-[60vh] max-h-[80vh] lg:w-[40%] p-4",
className
)}
>
<Card className={clsx("overflow-y-auto min-h-[40vh] md:min-h-[60vh] max-h-[80vh] lg:w-[40%] p-4", className)}>
<CardHeader title={title} />
<div className="flex flex-col gap-3 ">
{isLoading && (
@@ -215,45 +206,16 @@ export default function SightingHistoryWidget({
className={`border border-gray-700 rounded-md mb-2 p-2 cursor-pointer `}
onClick={() => onRowClick(obj)}
>
<div
className={`flex items-center gap-3 mt-2 justify-between `}
>
<div className={`flex items-center gap-3 mt-2 justify-between `}>
<div className={`border p-1 `}>
<img
src={obj?.plateUrlColour || BLANK_IMG}
height={48}
width={200}
alt="colour patch"
/>
<img src={obj?.plateUrlColour || BLANK_IMG} height={48} width={200} alt="colour patch" />
</div>
{isHotListHit && (
<img
src={HotListImg}
alt="hotlistHit"
className="h-20 object-contain rounded-md"
/>
)}
{isNPEDHitA && (
<img
src={NPED_CAT_A}
alt="hotlistHit"
className="h-20 object-contain rounded-md"
/>
)}
{isNPEDHitB && (
<img
src={NPED_CAT_B}
alt="hotlistHit"
className="h-20 object-contain rounded-md"
/>
)}
{isNPEDHitC && (
<img
src={NPED_CAT_C}
alt="hotlistHit"
className="h-20 object-contain rounded-md"
/>
<img src={HotListImg} alt="hotlistHit" className="h-20 object-contain rounded-md" />
)}
{isNPEDHitA && <img src={NPED_CAT_A} alt="hotlistHit" className="h-20 object-contain rounded-md" />}
{isNPEDHitB && <img src={NPED_CAT_B} alt="hotlistHit" className="h-20 object-contain rounded-md" />}
{isNPEDHitC && <img src={NPED_CAT_C} alt="hotlistHit" className="h-20 object-contain rounded-md" />}
<NumberPlate motion={motionAway} vrm={obj?.vrm} />
</div>
</div>
@@ -262,11 +224,7 @@ export default function SightingHistoryWidget({
</div>
</div>
</Card>
<SightingModal
isSightingModalOpen={isSightingModalOpen}
handleClose={handleClose}
sighting={selectedSighting}
/>
<SightingModal isSightingModalOpen={isSightingModalOpen} handleClose={handleClose} sighting={selectedSighting} />
</>
);
}

View File

@@ -11,25 +11,18 @@ type CameraOverviewHeaderProps = {
sighting?: SightingType | null;
};
const CardHeader = ({
title,
icon,
img,
sighting,
}: CameraOverviewHeaderProps) => {
const CardHeader = ({ title, icon, img, sighting }: CameraOverviewHeaderProps) => {
return (
<div
className={clsx(
"w-full border-b border-gray-600 flex flex-row items-center space-x-2 md:mb-6 relative justify-between"
"w-full border-b border-gray-600 flex flex-row items-center space-x-2 mb-6 relative justify-between"
)}
>
<div className="flex items-center space-x-2">
{icon && <FontAwesomeIcon icon={icon} className="size-4" />}
<h2 className="text-xl">{title}</h2>
</div>
{img && (
<img src={img} alt="Logo" width={100} height={50} className="ml-auto" />
)}
{img && <img src={img} alt="Logo" width={100} height={50} className="ml-auto" />}
{sighting?.vrm && <NumberPlate vrm={sighting.vrm} motion={false} />}
</div>
);

View File

@@ -1,21 +1,18 @@
import { Link } from "react-router";
import Logo from "/MAV.svg";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faGear,
faHome,
faListCheck,
faMaximize,
faMinimize,
faRotate,
} from "@fortawesome/free-solid-svg-icons";
import { faGear, faHome, faListCheck, faMaximize, faMinimize, faRotate } from "@fortawesome/free-solid-svg-icons";
import { useState } from "react";
import SoundBtn from "./SoundBtn";
import { useNPEDContext } from "../../context/NPEDUserContext";
import { useIntegrationsContext } from "../../context/IntegrationsContext";
export default function Header() {
const [isFullscreen, setIsFullscreen] = useState(false);
const { sessionStarted } = useNPEDContext();
const { state } = useIntegrationsContext();
const sessionStarted = state.sessionStarted;
const sessionPaused = state.sessionPaused;
const toggleFullscreen = () => {
if (!document.fullscreenElement) {
@@ -39,9 +36,13 @@ export default function Header() {
</Link>
</div>
<div className="flex flex-col lg:flex-row items-center space-x-24 justify-items-center">
{sessionStarted && (
<div className="text-green-400 font-bold">Session Active</div>
<div className="flex flex-row lg:flex-row space-x-2">
{sessionStarted && sessionPaused ? (
<p className="text-gray-400 font-bold">Session Paused</p>
) : (
sessionStarted && <p className="text-green-400 font-bold">Session Active</p>
)}
</div>
<div className="flex flex-row space-x-8">
<Link to={"/"}>
@@ -59,11 +60,7 @@ export default function Header() {
</div>
<SoundBtn />
<Link to={"/session-settings"}>
<FontAwesomeIcon
className="text-white"
icon={faListCheck}
size="2x"
/>
<FontAwesomeIcon className="text-white" icon={faListCheck} size="2x" />
</Link>
<Link to={"/system-settings"}>

View File

@@ -7,16 +7,12 @@ type ModalComponentProps = {
close: () => void;
};
const ModalComponent = ({
isModalOpen,
children,
close,
}: ModalComponentProps) => {
const ModalComponent = ({ isModalOpen, children, close }: ModalComponentProps) => {
return (
<Modal
isOpen={isModalOpen}
onRequestClose={close}
className="bg-[#1e2a38] p-6 rounded-lg shadow-lg max-w-[90%] mx-auto mt-[1%] md:w-[80%] md:h-[95%] z-[100] overflow-y-auto max-h-screen"
className="bg-[#1e2a38] p-6 rounded-lg shadow-lg max-w-[80%] mx-auto mt-[1%] md:w-[70%] md:h-[95%] z-[100] overflow-y-auto max-h-screen"
overlayClassName="fixed inset-0 bg-[#1e2a38]/70 flex justify-center items-start z-100"
>
{children}

View File

@@ -11,7 +11,6 @@ const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => {
const navigate = useNavigate();
const navigationDest = (side: string | undefined) => {
console.log(side);
if (settingsPage) {
navigate("/");
return;

View File

@@ -0,0 +1,60 @@
import "rc-slider/assets/index.css";
import Slider from "rc-slider";
import { useSoundContext } from "../../context/SoundContext";
const SliderComponent = ({ soundCategory }: { soundCategory: "SIGHTINGVOLUME" | "NPEDVOLUME" | "HOTLISTVOLUME" }) => {
const { dispatch, state } = useSoundContext();
const getVolumeOption = (soundCategory: string) => {
if (soundCategory === "SIGHTINGVOLUME") {
return state.sightingVolume;
}
if (soundCategory === "NPEDVOLUME") {
return state.NPEDsoundVolume;
}
if (soundCategory === "HOTLISTVOLUME") {
return state.hotlistSoundVolume;
}
};
const volume = getVolumeOption(soundCategory);
const handleChange = (value: number | number[]) => {
const number = typeof value === "number" ? value : value[0];
dispatch({ type: soundCategory, payload: number });
};
return (
<div className="flex flex-row w-full lg:w-[40%] space-x-5">
<Slider
min={0}
max={1}
onChange={handleChange}
value={volume}
step={0.1}
styles={{
handle: {
width: "1.2rem",
height: "1.2rem",
marginTop: -7,
backgroundColor: "#3b82f6",
border: "2px solid white",
borderRadius: "50%",
boxShadow: "0 0 5px rgba(0, 0, 0, 0.2)",
},
track: {
backgroundColor: "#3b82f6",
height: 6,
},
rail: {
backgroundColor: "#e5e7eb",
height: 6,
},
}}
/>
<span>{volume ? volume * 10 : 1}</span>
</div>
);
};
export default SliderComponent;

View File

@@ -0,0 +1,18 @@
import clsx from "clsx";
type VehicleSessionItemProps = {
sessionNumber: number;
textColour: string;
vehicleTag: string;
};
const VehicleSessionItem = ({ sessionNumber, textColour, vehicleTag }: VehicleSessionItemProps) => {
return (
<li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between items-center">
<p>{vehicleTag}</p>
<span className={`font-bold text-xl bg-slate-700 px-2 rounded-md ${clsx(textColour)}`}>{sessionNumber}</span>
</li>
);
};
export default VehicleSessionItem;

View File

@@ -0,0 +1,14 @@
import { createContext, useContext, type ActionDispatch } from "react";
import type { NPEDACTION, NPEDSTATE } from "../types/types";
type IntegrationsValue = {
state: NPEDSTATE;
dispatch: ActionDispatch<[action: NPEDACTION]>;
};
export const IntegrationsContext = createContext<IntegrationsValue | undefined>(undefined);
export const useIntegrationsContext = () => {
const ctx = useContext(IntegrationsContext);
if (!ctx) throw new Error("useNPEDContext must be used within <IntegrationsProvider>");
return ctx;
};

View File

@@ -1,21 +0,0 @@
import { createContext, useContext, type SetStateAction } from "react";
import type { NPEDUser, ReducedSightingType } from "../types/types";
type UserContextValue = {
user: NPEDUser | null;
setUser: React.Dispatch<SetStateAction<NPEDUser | null>>;
sessionStarted: boolean;
setSessionStarted: React.Dispatch<SetStateAction<boolean>>;
sessionList: ReducedSightingType[];
setSessionList: React.Dispatch<SetStateAction<ReducedSightingType[]>>;
};
export const NPEDUserContext = createContext<UserContextValue | undefined>(
undefined
);
export const useNPEDContext = () => {
const ctx = useContext(NPEDUserContext);
if (!ctx)
throw new Error("useNPEDContext must be used within <NPEDUserProvider>");
return ctx;
};

View File

@@ -7,13 +7,10 @@ type SoundContextType = {
audioArmed: boolean;
};
export const SoundContext = createContext<SoundContextType | undefined>(
undefined
);
export const SoundContext = createContext<SoundContextType | undefined>(undefined);
export const useSoundContext = () => {
const ctx = useContext(SoundContext);
if (!ctx)
throw new Error("useSoundContext must be used within <SoundContext>");
if (!ctx) throw new Error("useSoundContext must be used within <SoundContext>");
return ctx;
};

View File

@@ -0,0 +1,36 @@
import { useEffect, useReducer, type ReactNode } from "react";
import { IntegrationsContext } from "../IntegrationsContext";
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
import { initialState, reducer } from "../reducers/IntegrationsContextReducer";
type IntegrationsProviderType = {
children: ReactNode;
};
export const IntegrationsProvider = ({ children }: IntegrationsProviderType) => {
const [state, dispatch] = useReducer(reducer, initialState);
const { mutation } = useCameraBlackboard();
useEffect(() => {
const fetchData = async () => {
const result = await mutation.mutateAsync({
operation: "VIEW",
path: "sessionStats",
});
if (!result.result || typeof result.result === "string") return;
dispatch({ type: "UPDATE", payload: result?.result });
};
fetchData();
}, []);
return (
<IntegrationsContext.Provider
value={{
state,
dispatch,
}}
>
{children}
</IntegrationsContext.Provider>
);
};

View File

@@ -1,28 +0,0 @@
import { useState, type ReactNode } from "react";
import type { NPEDUser, ReducedSightingType } from "../../types/types";
import { NPEDUserContext } from "../NPEDUserContext";
type NPEDUserProviderType = {
children: ReactNode;
};
export const NPEDUserProvider = ({ children }: NPEDUserProviderType) => {
const [user, setUser] = useState<NPEDUser | null>(null);
const [sessionStarted, setSessionStarted] = useState(false);
const [sessionList, setSessionList] = useState<ReducedSightingType[]>([]);
return (
<NPEDUserContext.Provider
value={{
user,
setUser,
setSessionStarted,
sessionStarted,
sessionList,
setSessionList,
}}
>
{children}
</NPEDUserContext.Provider>
);
};

View File

@@ -1,11 +1,4 @@
import {
useEffect,
useMemo,
useReducer,
useRef,
useState,
type ReactNode,
} from "react";
import { useEffect, useMemo, useReducer, useRef, useState, type ReactNode } from "react";
import { SoundContext } from "../SoundContext";
import { initialState, reducer } from "../reducers/SoundContextReducer";
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
@@ -28,7 +21,11 @@ const SoundContextProvider = ({ children }: SoundContextProviderProps) => {
path: "soundSettings",
});
if (!result.result || typeof result.result !== "object") {
dispatch({ type: "UPDATE", payload: state });
} else {
dispatch({ type: "UPDATE", payload: result.result });
}
};
fetchSound();
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -63,13 +60,8 @@ const SoundContextProvider = ({ children }: SoundContextProviderProps) => {
};
}, []);
const value = useMemo(
() => ({ state, dispatch, audioArmed }),
[state, audioArmed]
);
return (
<SoundContext.Provider value={value}>{children}</SoundContext.Provider>
);
const value = useMemo(() => ({ state, dispatch, audioArmed }), [state, audioArmed]);
return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;
};
export default SoundContextProvider;

View File

@@ -0,0 +1,46 @@
import type { NPEDACTION, NPEDSTATE } from "../../types/types";
export const initialState = {
sessionStarted: false,
sessionList: [],
sessionPaused: false,
savedSightings: [],
npedUser: null,
};
export function reducer(state: NPEDSTATE, action: NPEDACTION) {
switch (action.type) {
case "SESSIONSTART":
return {
...state,
sessionStarted: action.payload,
};
case "LOGIN":
return {
...state,
npedUser: action.payload,
};
case "LOGOUT":
return {
...state,
npedUser: action.payload,
};
case "SESSIONPAUSE":
return {
...state,
sessionPaused: action.payload,
};
case "ADD":
return {
...state,
sessionList: [...state.sessionList, action.payload],
};
case "UPDATE":
return {
...state,
sessionList: action.payload,
};
default:
return { ...state };
}
}

View File

@@ -3,12 +3,22 @@ import type { SoundAction, SoundState } from "../../types/types";
export const initialState: SoundState = {
sightingSound: "switch",
NPEDsound: "popup",
hotlistSound: "warning",
hotlists: [{ name: "hotlistName", sound: "notification" }],
soundOptions: [
{ name: "switch (Default)", soundFile: null },
{ name: "popup", soundFile: null },
{ name: "notification", soundFile: null },
{ name: "Switch (Default)", soundFileName: "switch" },
{ name: "Popup", soundFileName: "popup" },
{ name: "Notification", soundFileName: "notification" },
{ name: "Beep", soundFileName: "beep" },
{ name: "Ding", soundFileName: "ding" },
{ name: "Shutter", soundFileName: "shutter" },
{ name: "Warning (voice)", soundFileName: "warning" },
{ name: "Attention (voice)", soundFileName: "attention" },
],
sightingVolume: 1,
NPEDsoundVolume: 1,
hotlistSoundVolume: 1,
uploadedSound: null,
};
export function reducer(state: SoundState, action: SoundAction): SoundState {
@@ -18,10 +28,15 @@ export function reducer(state: SoundState, action: SoundAction): SoundState {
...state,
sightingSound: action.payload.sightingSound,
NPEDsound: action.payload.NPEDsound,
hotlistSound: action.payload.hotlistSound,
hotlists: action.payload.hotlists?.map((hotlist) => ({
name: hotlist.name,
sound: hotlist.sound,
})),
NPEDsoundVolume: action.payload.NPEDsoundVolume,
sightingVolume: action.payload.sightingVolume,
hotlistSoundVolume: action.payload.hotlistSoundVolume,
soundOptions: action.payload.soundOptions,
};
}
@@ -31,7 +46,29 @@ export function reducer(state: SoundState, action: SoundAction): SoundState {
soundOptions: [...(state.soundOptions ?? []), action.payload],
};
}
// todo: refactor to use single state coupled with sound name. e.g : {name: <soundname>, volume: <volume>}
case "SIGHTINGVOLUME":
return {
...state,
sightingVolume: action.payload,
};
case "NPEDVOLUME":
return {
...state,
NPEDsoundVolume: action.payload,
};
case "HOTLISTVOLUME":
return {
...state,
hotlistSoundVolume: action.payload,
};
case "UPLOADEDSOUND":
return {
...state,
uploadedSound: action.payload,
};
default:
return state;
}

View File

@@ -0,0 +1,75 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { useEffect } from "react";
import { toast } from "sonner";
import type { InitialValuesForm } from "../types/types";
import { CAM_BASE } from "../utils/config";
const getBackOfficeConfig = async (format: string) => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher-${format?.toLowerCase()}`);
if (!response.ok) throw new Error("Cannot get Back Office configuration");
return response.json();
};
const updateBackOfficeConfig = async (data: InitialValuesForm) => {
const updateConfigPayload = {
id: `Dispatcher-${data.format.toLowerCase()}`,
fields: [
{
property: "propBackofficeURL",
value: data.backOfficeURL,
},
{
property: "propConnectTimeoutSeconds",
value: data.connectTimeoutSeconds,
},
{
property: "propPassword",
value: data.password,
},
{
property: "propReadTimeoutSeconds",
value: data.readTimeoutSeconds,
},
{
property: "propUsername",
value: data.username,
},
],
};
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher`, {
method: "POST",
body: JSON.stringify(updateConfigPayload),
});
if (!response.ok) throw new Error("Cannot update Back Office configuration");
return response.json();
};
export const useCameraBackOfficeOutput = (format: string) => {
const backOfficeQuery = useQuery({
queryKey: ["backoffice", format],
queryFn: () => getBackOfficeConfig(format),
enabled: !!format,
});
useEffect(() => {
if (backOfficeQuery.isError) toast.error(backOfficeQuery.error.message);
}, [backOfficeQuery?.error?.message, backOfficeQuery.isError]);
return {
backOfficeQuery,
};
};
export const useUpdateBackOfficeConfig = () => {
const backOfficeMutation = useMutation({
mutationKey: ["backOfficeUpdate"],
mutationFn: updateBackOfficeConfig,
onError: (error) => toast.error(error.message),
onSuccess: (data) => {
if (data) {
toast.success("Settings successfully updated", { id: "dispatchSettings" });
}
},
});
return { backOfficeMutation };
};

View File

@@ -2,7 +2,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import { useEffect } from "react";
import { toast } from "sonner";
import type { BearerTypeFieldType, InitialValuesForm } from "../types/types";
import type { BearerTypeFieldType, OptionalBOF2Constants } from "../types/types";
const getDispatcherConfig = async () => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher`);
@@ -18,7 +18,6 @@ const updateDispatcherConfig = async (data: BearerTypeFieldType) => {
property: "propEnabled",
value: data.enabled,
},
// Todo: figure out how to add verbose conditionally
{
property: "propFormat",
value: data.format,
@@ -33,43 +32,39 @@ const updateDispatcherConfig = async (data: BearerTypeFieldType) => {
return response.json();
};
const getBackOfficeConfig = async () => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher-json`);
if (!response.ok) throw new Error("Cannot get Back Office configuration");
return response.json();
};
const updateBackOfficeConfig = async (data: InitialValuesForm) => {
const updateConfigPayload = {
id: "Dispatcher-json",
const updateBackOfficeDispatcher = async (data: OptionalBOF2Constants) => {
const bof2ContantsPayload = {
id: "Dispatcher-bof2-constants",
fields: [
{
property: "propBackofficeURL",
value: data.backOfficeURL,
property: "propFeedIdentifier",
value: data?.FFID,
},
{
property: "propConnectTimeoutSeconds",
value: data.connectTimeoutSeconds,
property: "propSourceIdentifier",
value: data?.SCID,
},
{
property: "propPassword",
value: data.password,
property: "propTimeZoneType",
value: data?.timestampSource,
},
{
property: "propReadTimeoutSeconds",
value: data.readTimeoutSeconds,
},
{
property: "propUsername",
value: data.username,
property: "propGpsFormat",
value: data?.GPSFormat,
},
],
};
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher-json`, {
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher-bof2-constants`, {
method: "POST",
body: JSON.stringify(updateConfigPayload),
body: JSON.stringify(bof2ContantsPayload),
});
if (!response.ok) throw new Error("Cannot update Back Office configuration");
if (!response.ok) throw new Error("Cannot update dispatcher configuration");
return response.json();
};
const getBof2DispatcherData = async () => {
const response = await fetch(`http://100.118.196.113:8080/api/fetch-config?id=Dispatcher-bof2-constants`);
if (!response.ok) throw new Error("Cannot get BOF2 dispatcher config");
return response.json();
};
@@ -79,29 +74,23 @@ export const useCameraOutput = () => {
queryFn: getDispatcherConfig,
});
const backOfficeQuery = useQuery({
queryKey: ["backoffice"],
queryFn: getBackOfficeConfig,
});
const dispatcherMutation = useMutation({
mutationFn: updateDispatcherConfig,
mutationKey: ["dispatcherUpdate"],
onError: (error) => toast.error(error.message),
onSuccess: (data) => {
if (data) {
toast.success("Settings successfully updated");
toast.success("Settings successfully updated", { id: "dispatchSettings" });
}
},
});
const backOfficeMutation = useMutation({
mutationKey: ["backOfficeUpdate"],
mutationFn: updateBackOfficeConfig,
onError: (error) => toast.error(error.message),
const backOfficeDispatcherMutation = useMutation({
mutationKey: ["backofficedDispatcher"],
mutationFn: updateBackOfficeDispatcher,
onSuccess: (data) => {
if (data) {
toast.success("Settings successfully updated");
toast.success("Settings successfully updated", { id: "dispatchSettings" });
}
},
});
@@ -110,14 +99,18 @@ export const useCameraOutput = () => {
if (dispatcherQuery.isError) toast.error(dispatcherQuery.error.message);
}, [dispatcherQuery?.error?.message, dispatcherQuery.isError]);
useEffect(() => {
if (backOfficeQuery.isError) toast.error(backOfficeQuery.error.message);
}, [backOfficeQuery?.error?.message, backOfficeQuery.isError]);
return {
dispatcherQuery,
dispatcherMutation,
backOfficeQuery,
backOfficeMutation,
backOfficeDispatcherMutation,
};
};
export const useGetDispatcherConfig = () => {
const bof2ConstantsQuery = useQuery({
queryKey: ["getBof2DispatcherData"],
queryFn: getBof2DispatcherData,
});
return { bof2ConstantsQuery };
};

View File

@@ -0,0 +1,45 @@
import { useMutation, useQuery } 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 uploadFile = async (file: File) => {
const form = new FormData();
form.append("upload", file, file.name);
const response = await fetch(`${camBase}/upload/file-upload/3`, {
method: "POST",
body: form,
});
if (!response.ok) {
throw new Error("Cannot reach upload file endpoint");
}
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,
});
const mutation = useMutation({
mutationFn: (file: File) => uploadFile(file),
mutationKey: ["uploadFile"],
onError: (err) => toast.error(err ? err.message : ""),
onSuccess: async (msg) => toast.success(msg),
});
return { query: queryKey ? query : undefined, mutation };
};

View File

@@ -0,0 +1,46 @@
import { useMutation } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import type { InitialValuesForm } from "../types/types";
const sendToValidate = async (data: InitialValuesForm) => {
const updateConfigPayload = {
id: `Dispatcher-${data.format.toLowerCase()}`,
fields: [
{
property: "propBackofficeURL",
value: data.backOfficeURL,
},
{
property: "propConnectTimeoutSeconds",
value: data.connectTimeoutSeconds,
},
{
property: "propPassword",
value: data.password,
},
{
property: "propReadTimeoutSeconds",
value: data.readTimeoutSeconds,
},
{
property: "propUsername",
value: data.username,
},
],
};
const response = await fetch(`${CAM_BASE}/api/update-config-isvalid`, {
method: "post",
body: JSON.stringify(updateConfigPayload),
});
if (!response.ok) throw new Error("Cannot send to validate");
return response.json();
};
export const useFormVaidate = () => {
const validateMutation = useMutation({
mutationKey: ["sendToValidate"],
mutationFn: sendToValidate,
});
return { validateMutation };
};

View File

@@ -1,6 +1,6 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import type { NPEDFieldType } from "../types/types";
import { useNPEDContext } from "../context/NPEDUserContext";
import { useIntegrationsContext } from "../context/IntegrationsContext";
import { useEffect } from "react";
import { CAM_BASE } from "../utils/config";
import { toast } from "sonner";
@@ -42,8 +42,7 @@ async function signIn(loginDetails: NPEDFieldType) {
}),
]);
if (!frontRes.ok || !rearRes.ok)
throw new Error("Cannot reach NPED endpoint");
if (!frontRes.ok || !rearRes.ok) throw new Error("Cannot reach NPED endpoint");
return {
frontResponse: frontRes.json(),
@@ -73,7 +72,7 @@ async function signOut() {
}
export const useNPEDAuth = () => {
const { setUser, user } = useNPEDContext();
const { dispatch } = useIntegrationsContext();
const signInMutation = useMutation({
mutationKey: ["NPEDSignin"],
@@ -84,7 +83,8 @@ export const useNPEDAuth = () => {
onSuccess: async (data) => {
toast.dismiss();
toast.success("Signed in successfully!");
setUser(await data.frontResponse);
dispatch({ type: "LOGIN", payload: await data.frontResponse });
},
onError: (error) => {
toast.dismiss();
@@ -101,7 +101,7 @@ export const useNPEDAuth = () => {
mutationFn: signOut,
onSuccess: () => {
toast.success("Signed out successfully");
setUser(null);
dispatch({ type: "LOGOUT", payload: null });
},
onError: (error) => {
toast.error(`Sign-out failed: ${error.message}`);
@@ -115,11 +115,11 @@ export const useNPEDAuth = () => {
useEffect(() => {
if (fetchdataQuery.isSuccess && fetchdataQuery.data) {
setUser(fetchdataQuery.data);
dispatch({ type: "LOGIN", payload: fetchdataQuery.data });
} else {
setUser(null);
dispatch({ type: "LOGOUT", payload: null });
}
}, [fetchdataQuery.data, fetchdataQuery.isSuccess, setUser]);
}, [dispatch, fetchdataQuery.data, fetchdataQuery.isSuccess]);
useEffect(() => {
if (fetchdataQuery.isError) toast.error(fetchdataQuery.error.message);
@@ -134,8 +134,6 @@ export const useNPEDAuth = () => {
data: signInMutation.data,
fetchdataQueryError: fetchdataQuery.error,
fetchdataQueryLoading: fetchdataQuery.isLoading,
user,
setUser,
signOut: signOutMutation.mutate,
};
};

View File

@@ -1,10 +1,14 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import { Query, useQuery } from "@tanstack/react-query";
import type { SightingType } from "../types/types";
import { useSoundOnChange } from "react-sounds";
import { useSound } from "react-sounds";
import { useSoundContext } from "../context/SoundContext";
import { getSoundFileURL } from "../utils/utils";
import { checkIsHotListHit, getNPEDCategory } from "../utils/utils";
import switchSound from "../assets/sounds/ui/switch.mp3";
import notification from "../assets/sounds/ui/notification.mp3";
import popup from "../assets/sounds/ui/popup_open.mp3";
import { useCachedSoundSrc } from "./usecachedSoundSrc";
async function fetchSighting(url: string | undefined, ref: number): Promise<SightingType> {
const res = await fetch(`${url}${ref}`, {
@@ -21,31 +25,19 @@ export function useSightingFeed(url: string | undefined) {
const [sessionStarted, setSessionStarted] = useState(false);
const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(null);
const mostRecent = sightings[0] ?? null;
const latestRef = mostRecent?.ref ?? null;
const { src: soundSrc } = useCachedSoundSrc(state?.sightingSound, state?.soundOptions, switchSound);
const { src: soundSrcHotlist } = useCachedSoundSrc(state?.hotlistSound, state?.soundOptions, notification);
const { src: soundSrcNped } = useCachedSoundSrc(state?.NPEDsound, state?.soundOptions, popup);
const { play: hotlistsound } = useSound(soundSrcHotlist, { volume: state.hotlistSoundVolume });
const { play: npedSound } = useSound(soundSrcNped, { volume: state.NPEDsoundVolume });
const { play: sightingSound } = useSound(soundSrc, { volume: state.sightingVolume });
const mostRecent = sightings[0] ?? null;
const first = useRef(true);
const lastSoundAt = useRef(0);
const COOLDOWN_MS = 1500;
const currentRef = useRef<number>(-1);
const lastValidTimestamp = useRef<number>(Date.now());
const trigger = useMemo(() => {
if (latestRef == null || !audioArmed) return null;
if (first.current) {
first.current = false;
return Symbol("skip");
}
const now = Date.now();
if (now - lastSoundAt.current < COOLDOWN_MS) return Symbol("skip");
lastSoundAt.current = now;
return latestRef;
}, [audioArmed, latestRef]);
const soundSrc = useMemo(() => {
return getSoundFileURL(state?.sightingSound) ?? switchSound;
}, [state.sightingSound]);
function refetchInterval(query: Query<SightingType, Error, SightingType, (string | undefined)[]>) {
if (!query) return;
const data = query.state.data as SightingType | undefined;
@@ -74,15 +66,36 @@ export function useSightingFeed(url: string | undefined) {
staleTime: 0,
});
//use latestref instead of trigger to revert back
useSoundOnChange(soundSrc, trigger, {
volume: 1,
initial: false,
});
const playHotlistsound = useDebouncedCallback(() => {
hotlistsound();
}, 500);
const playNPEDHitSound = useDebouncedCallback(() => {
npedSound();
}, 500);
const playSightingHitSound = useDebouncedCallback(() => {
sightingSound();
}, 500);
useEffect(() => {
const data = query.data;
if (!data || data.ref === -1) return;
const isHotListHit = checkIsHotListHit(data);
const cat = getNPEDCategory(data);
const isNPEDHitA = cat === "A";
const isNPEDHitB = cat === "B";
const isNPEDHitC = cat === "C";
if ((isNPEDHitA && audioArmed) || (isNPEDHitB && audioArmed) || (isNPEDHitC && audioArmed)) {
playNPEDHitSound();
} else if (isHotListHit && audioArmed) {
playHotlistsound();
} else if (audioArmed) {
playSightingHitSound();
}
const now = Date.now();

View File

@@ -0,0 +1,56 @@
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";
export function useCachedSoundSrc(
selected: string | undefined,
soundOptions: SoundUploadValue[] | undefined,
fallbackUrl: string
) {
const isUploaded = !!selected && (selected.endsWith(".mp3") || selected.endsWith(".wav"));
const resolved = resolveSoundSource(selected, soundOptions);
const { query } = useFileUpload({
queryKey: resolved?.type === "uploaded" ? [resolved?.url] : undefined,
});
const [objectUrl, setObjectUrl] = useState<string>();
const objRef = useRef<string | null>(null);
useEffect(() => {
const blob = query?.data;
if (blob instanceof Blob) {
if (objRef.current) URL.revokeObjectURL(objRef.current);
const url = URL.createObjectURL(blob);
objRef.current = url;
setObjectUrl(url);
} else {
if (objRef.current) URL.revokeObjectURL(objRef.current);
objRef.current = null;
setObjectUrl(undefined);
}
}, [query?.data]);
useEffect(() => {
return () => {
if (objRef.current) URL.revokeObjectURL(objRef.current);
};
}, []);
const src = useMemo(() => {
if (isUploaded && objectUrl) return objectUrl;
if (!selected) return fallbackUrl;
return getSoundFileURL(selected) ?? fallbackUrl;
}, [isUploaded, objectUrl, selected, fallbackUrl]);
return {
src,
isUploaded,
isLoading: !!query?.isLoading,
error: (query?.error as Error) || undefined,
};
}

View File

@@ -47,7 +47,7 @@ const SystemSettings = () => {
</div>
</TabPanel>
<TabPanel>
<div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-4 px-2 sm:px-4 lg:px-0 w-full">
<div className="mx-auto grid grid-rows-2 sm:grid-cols-1 lg:grid-cols-8 gap-4 px-2 sm:px-4 lg:px-0 w-full">
<SoundSettingsCard />
<SoundUploadCard />
</div>

View File

@@ -43,17 +43,16 @@ export type CameraSettingValues = {
id: number | string;
};
export type CameraSettingErrorValues = Partial<
Record<keyof CameraSettingValues, string>
>;
export type CameraSettingErrorValues = Partial<Record<keyof CameraSettingValues, string>>;
export type BearerTypeFieldType = {
format: string;
enabled: boolean;
verbose: boolean;
verbose?: boolean;
};
export type InitialValuesForm = {
format: string;
backOfficeURL: string;
username: string;
password: string;
@@ -69,6 +68,13 @@ export type InitialValuesFormErrors = {
readTimeoutSeconds?: string;
};
export type OptionalBOF2Constants = {
FFID?: "";
SCID?: "";
timestampSource?: "";
GPSFormat?: "";
};
export type NPEDFieldType = {
frontId: string;
username: string | undefined;
@@ -287,18 +293,28 @@ export type FormValues = {
sightingSound: SoundValue;
NPEDsound: SoundValue;
hotlists: Hotlist[];
hotlistSound: SoundValue;
soundOptions?: SoundUploadValue[];
};
export type SoundUploadValue = {
name: string;
soundFile: File | null;
soundFileName?: string;
soundFile?: File | null;
soundUrl?: string;
uploadedAt?: number;
};
export type SoundState = {
sightingSound: SoundValue;
NPEDsound: SoundValue;
hotlists: Hotlist[];
hotlistSound: SoundValue;
soundOptions?: SoundUploadValue[];
sightingVolume: number;
NPEDsoundVolume: number;
hotlistSoundVolume: number;
uploadedSound?: Blob | null;
};
type UpdateAction = {
@@ -307,6 +323,11 @@ type UpdateAction = {
sightingSound: SoundValue;
NPEDsound: SoundValue;
hotlists: Hotlist[];
sightingVolume: number;
NPEDsoundVolume: number;
hotlistSoundVolume: number;
hotlistSound: SoundValue;
soundOptions?: SoundUploadValue[];
};
};
@@ -315,7 +336,17 @@ type AddAction = {
payload: SoundUploadValue;
};
export type SoundAction = UpdateAction | AddAction;
type VolumeAction = {
type: "SIGHTINGVOLUME" | "NPEDVOLUME" | "HOTLISTVOLUME";
payload: number;
};
type UploadedState = {
type: "UPLOADEDSOUND";
payload: Blob | undefined;
};
export type SoundAction = UpdateAction | AddAction | VolumeAction | UploadedState;
export type WifiSettingValues = {
ssid: string;
password: string;
@@ -355,3 +386,26 @@ export type ModemSettingsType = {
password: string;
authenticationType: string;
};
export type HitKind = "NPED" | "HOTLIST";
export type QueuedHit = {
id: number | string;
sighting: SightingType;
kind: HitKind;
};
export type DedupedSightings = ReducedSightingType[];
export type NPEDSTATE = {
sessionStarted: boolean;
sessionList: ReducedSightingType[];
sessionPaused: boolean;
savedSightings: DedupedSightings;
npedUser: NPEDUser;
};
export type NPEDACTION = {
type: string;
payload: any;
};

16
src/utils/cacheSound.ts Normal file
View File

@@ -0,0 +1,16 @@
export async function getOrCacheBlob(url: string) {
const cache = await caches.open("app-sounds-v1");
const hit = await cache.match(url);
if (hit) return await hit.blob();
const res = await fetch(url, { cache: "no-store" });
if (!res.ok) throw new Error(`Fetch failed: ${res.status}`);
await cache.put(url, res.clone());
return await res.blob();
}
export async function evictFromCache(url: string) {
const cache = await caches.open("app-sounds-v1");
await cache.delete(url);
}

View File

@@ -0,0 +1,24 @@
import { getSoundFileURL } from "./utils";
import { CAM_BASE } from "./config";
import type { SoundUploadValue } from "../types/types";
export function resolveSoundSource(
selected: string | undefined,
soundOptions: SoundUploadValue[] | undefined
): { type: "uploaded"; url: string } | { type: "builtin"; url: string } | undefined {
if (!selected) return undefined;
const isFile = selected.endsWith(".mp3") || selected.endsWith(".wav");
if (isFile) {
const match = soundOptions?.find((o) => o.soundFileName === selected);
const version = match?.uploadedAt ?? 0;
const url = `${CAM_BASE}/Mobile/${encodeURIComponent(selected)}?v=${version}`;
return { type: "uploaded", url };
}
const builtin = getSoundFileURL(selected);
if (builtin) return { type: "builtin", url: builtin };
return undefined;
}

View File

@@ -1,18 +1,31 @@
import switchSound from "../assets/sounds/ui/switch.mp3";
import popup from "../assets/sounds/ui/popup_open.mp3";
import notification from "../assets/sounds/ui/notification.mp3";
import beep from "../assets/sounds/ui/Beep.wav";
import warning from "../assets/sounds/ui/Warning.wav";
import ding from "../assets/sounds/ui/Ding.wav";
import shutter from "../assets/sounds/ui/shutter.mp3";
import attention from "../assets/sounds/ui/Attention.wav";
import type { HotlistMatches, SightingType } from "../types/types";
import { hasFlag } from "country-flag-icons";
export function getSoundFileURL(name: string) {
const sounds: Record<string, string> = {
switch: switchSound,
popup: popup,
notification: notification,
beep: beep,
warning: warning,
ding: ding,
shutter: shutter,
attention: attention,
};
return sounds[name] ?? null;
}
export const showSoundURL = (url: URL | string | undefined) => {
console.log(url);
};
const randomChars = () => {
const uppercaseAsciiStart = 65;
const letterIndex = Math.floor(Math.random() * 26);
@@ -79,12 +92,6 @@ export const formatNumberPlate = (plate: string) => {
const formattedPlate = splittedPlate?.join("");
return formattedPlate;
};
export const formatNumberPlateEU = (plate: string) => {
const splittedPlate = plate?.split("");
splittedPlate?.splice(3, 0, " ");
const formattedPlate = splittedPlate?.join("");
return formattedPlate;
};
export const BLANK_IMG = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
@@ -141,16 +148,13 @@ export const checkIsHotListHit = (sigthing: SightingType | null) => {
};
export function getHotlistName(obj: HotlistMatches | undefined) {
if (!obj || Object.values(obj).includes(false)) return;
if (!obj) return;
const keys = Object.keys(obj);
return keys;
const hotlistNames = Object.entries(obj)
.filter(([, value]) => value === true)
.map(([key]) => key);
return hotlistNames;
}
export const getNPEDCategory = (r?: SightingType | null) =>
r?.metadata?.npedJSON?.["NPED CATEGORY"] as "A" | "B" | "C" | undefined;
export const numberPlateFlag = (countryCode: string) => {
const result = hasFlag(countryCode) === true;
console.log(result);
};
r?.metadata?.npedJSON?.["NPED CATEGORY"] as "A" | "B" | "C" | "D" | undefined;

View File

@@ -138,7 +138,7 @@
dependencies:
"@babel/helper-plugin-utils" "^7.27.1"
"@babel/runtime@^7.1.2":
"@babel/runtime@^7.1.2", "@babel/runtime@^7.10.1", "@babel/runtime@^7.18.3":
version "7.28.4"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.28.4.tgz#a70226016fabe25c5783b2f22d3e1c9bc5ca3326"
integrity sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==
@@ -1044,6 +1044,11 @@ chownr@^3.0.0:
resolved "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz"
integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==
classnames@^2.2.5:
version "2.5.1"
resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.5.1.tgz#ba774c614be0f016da105c858e7159eae8e7687b"
integrity sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==
clsx@^2.0.0, clsx@^2.1.1:
version "2.1.1"
resolved "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz"
@@ -1875,6 +1880,23 @@ queue-microtask@^1.2.2:
resolved "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz"
integrity sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==
rc-slider@^11.1.9:
version "11.1.9"
resolved "https://registry.yarnpkg.com/rc-slider/-/rc-slider-11.1.9.tgz#d872130fbf4ec51f28543d62e90451091d6f5208"
integrity sha512-h8IknhzSh3FEM9u8ivkskh+Ef4Yo4JRIY2nj7MrH6GQmrwV6mcpJf5/4KgH5JaVI1H3E52yCdpOlVyGZIeph5A==
dependencies:
"@babel/runtime" "^7.10.1"
classnames "^2.2.5"
rc-util "^5.36.0"
rc-util@^5.36.0:
version "5.44.4"
resolved "https://registry.yarnpkg.com/rc-util/-/rc-util-5.44.4.tgz#89ee9037683cca01cd60f1a6bbda761457dd6ba5"
integrity sha512-resueRJzmHG9Q6rI/DfK6Kdv9/Lfls05vzMs1Sk3M2P+3cJa+MakaZyWY8IPfehVuhPJFKrIY1IK4GqbiaiY5w==
dependencies:
"@babel/runtime" "^7.18.3"
react-is "^18.2.0"
react-dom@^19.1.1:
version "19.1.1"
resolved "https://registry.npmjs.org/react-dom/-/react-dom-19.1.1.tgz"
@@ -1892,6 +1914,11 @@ react-is@^16.13.1, react-is@^16.7.0:
resolved "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz"
integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==
react-is@^18.2.0:
version "18.3.1"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.3.1.tgz#e83557dc12eae63a99e003a46388b1dcbb44db7e"
integrity sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==
react-lifecycles-compat@^3.0.0:
version "3.0.4"
resolved "https://registry.npmjs.org/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz"
@@ -2240,6 +2267,11 @@ uri-js@^4.2.2:
dependencies:
punycode "^2.1.0"
use-debounce@^10.0.6:
version "10.0.6"
resolved "https://registry.yarnpkg.com/use-debounce/-/use-debounce-10.0.6.tgz#e05060a5e561432ec740c653698f3eb162bd28ec"
integrity sha512-C5OtPyhAZgVoteO9heXMTdW7v/IbFI+8bSVKYCJrSmiWWCLsbUxiBSp4t9v0hNBTGY97bT72ydDIDyGSFWfwXg==
vite@^7.1.0:
version "7.1.2"
resolved "https://registry.npmjs.org/vite/-/vite-7.1.2.tgz"