13 Commits

10 changed files with 189 additions and 67 deletions

View File

@@ -1,4 +1,4 @@
import { Field, FieldArray, Form, Formik } from "formik"; import { Field, Form, Formik } from "formik";
import FormGroup from "../components/FormGroup"; import FormGroup from "../components/FormGroup";
import type { FormValues, Hotlist } from "../../../types/types"; import type { FormValues, Hotlist } from "../../../types/types";
import { useSoundContext } from "../../../context/SoundContext"; import { useSoundContext } from "../../../context/SoundContext";
@@ -13,13 +13,14 @@ const SoundSettingsFields = () => {
const hotlists: Hotlist[] = state.hotlists; const hotlists: Hotlist[] = state.hotlists;
const soundOptions = state?.soundOptions?.map((soundOption) => ({ const soundOptions = state?.soundOptions?.map((soundOption) => ({
value: soundOption?.soundFile, value: soundOption?.soundFileName,
label: soundOption?.name, label: soundOption?.name,
})); }));
const initialValues: FormValues = { const initialValues: FormValues = {
sightingSound: state.sightingSound ?? "switch", sightingSound: state.sightingSound ?? "switch",
NPEDsound: state.NPEDsound ?? "popup", NPEDsound: state.NPEDsound ?? "popup",
hotlistSound: state.hotlistSound ?? "notification",
hotlists, hotlists,
}; };
@@ -28,9 +29,12 @@ const SoundSettingsFields = () => {
...values, ...values,
sightingVolume: state.sightingVolume, sightingVolume: state.sightingVolume,
NPEDsoundVolume: state.NPEDsoundVolume, NPEDsoundVolume: state.NPEDsoundVolume,
hotlistSoundVolume: state.hotlistSoundVolume,
soundOptions: [...(state.soundOptions ?? [])],
}; };
dispatch({ type: "UPDATE", payload: updatedValues }); dispatch({ type: "UPDATE", payload: updatedValues });
const result = await mutation.mutateAsync({ const result = await mutation.mutateAsync({
operation: "INSERT", operation: "INSERT",
path: "soundSettings", path: "soundSettings",
@@ -44,7 +48,7 @@ const SoundSettingsFields = () => {
}; };
return ( return (
<Formik initialValues={initialValues} onSubmit={handleSubmit}> <Formik initialValues={initialValues} onSubmit={handleSubmit}>
{({ values }) => ( {() => (
<Form className="flex flex-col space-y-3"> <Form className="flex flex-col space-y-3">
<FormGroup> <FormGroup>
<div className="flex flex-col md:flex-row space-y-2 w-full justify-between gap-3"> <div className="flex flex-col md:flex-row space-y-2 w-full justify-between gap-3">
@@ -85,6 +89,23 @@ const SoundSettingsFields = () => {
<div> <div>
<h3 className="text-lg font-semibold mb-2">Hotlist Sounds</h3> <h3 className="text-lg font-semibold mb-2">Hotlist Sounds</h3>
<FormGroup> <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 <FieldArray
name="hotlists" name="hotlists"
render={() => ( render={() => (
@@ -115,7 +136,7 @@ const SoundSettingsFields = () => {
</div> </div>
)} )}
/> />
</FormGroup> </FormGroup> */}
</div> </div>
<button <button
type="submit" type="submit"

View File

@@ -3,21 +3,47 @@ import FormGroup from "../components/FormGroup";
import type { SoundUploadValue } from "../../../types/types"; import type { SoundUploadValue } from "../../../types/types";
import { useSoundContext } from "../../../context/SoundContext"; import { useSoundContext } from "../../../context/SoundContext";
import { toast } from "sonner"; import { toast } from "sonner";
import { useCameraBlackboard } from "../../../hooks/useCameraBlackboard";
const SoundUpload = () => { const SoundUpload = () => {
const { dispatch } = useSoundContext(); const { state, dispatch } = useSoundContext();
const { mutation } = useCameraBlackboard();
const initialValues: SoundUploadValue = { const initialValues: SoundUploadValue = {
name: "", name: "",
soundFile: null, soundFile: null,
soundFileName: "",
soundUrl: "",
}; };
const handleSubmit = (values: SoundUploadValue) => { const handleSubmit = async (values: SoundUploadValue) => {
if (!values.soundFile) { if (!values.soundFile) {
toast.warning("Please select an audio file"); toast.warning("Please select an audio file");
} else { return;
dispatch({ type: "ADD", payload: values });
toast.success("Sound file upload successfully");
} }
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,
});
if (result.reason !== "OK") {
toast.error("Cannot update sound settings");
} else {
toast.success(`${values.name} file added`);
}
dispatch({ type: "ADD", payload: values });
}; };
return ( return (
@@ -36,7 +62,10 @@ const SoundUpload = () => {
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" 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) => { 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("name", e.target.files[0].name);
setFieldValue("soundFileName", e.target.files[0].name);
setFieldValue("soundFile", e.target.files[0]); setFieldValue("soundFile", e.target.files[0]);
} else { } else {
setFieldError("soundFile", "Not an mp3 file"); setFieldError("soundFile", "Not an mp3 file");

View File

@@ -23,8 +23,7 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
const { dispatch } = useAlertHitContext(); const { dispatch } = useAlertHitContext();
const { query, mutation } = useCameraBlackboard(); const { query, mutation } = useCameraBlackboard();
const hotlistName = getHotlistName(sighting?.metadata?.hotlistMatches); const hotlistNames = getHotlistName(sighting?.metadata?.hotlistMatches);
const handleAcknowledgeButton = () => { const handleAcknowledgeButton = () => {
try { try {
if (!sighting) { if (!sighting) {
@@ -117,16 +116,6 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
<div className="flex flex-col md:flex-row gap-3 items-center"> <div className="flex flex-col md:flex-row gap-3 items-center">
<NumberPlate vrm={sighting?.vrm} motion={motionAway} /> <NumberPlate vrm={sighting?.vrm} motion={motionAway} />
<img src={sighting?.plateUrlColour} alt="plate patch" className="h-16 object-contain rounded-md" /> <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].replace(/\.csv$/i, "") : "-"}
</p>
</div>
</div>
)}
</div> </div>
{isHotListHit && <img src={HotListImg} alt="hotlistHit" className="h-20 object-contain rounded-md" />} {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" />} {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" />} {isNPEDHitC && <img src={NPED_CAT_C} alt="hotlistHit" className="h-20 object-contain rounded-md" />}
</div> </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) => (
<div className="items-center px-2.5 py-0.5 rounded-sm me-2 bg-amber-500 w-55 m-2">
<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"> <div className="flex flex-col lg:flex-row items-center gap-3">
<img <img
src={sighting?.overviewUrl} src={sighting?.overviewUrl}

View File

@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ReducedSightingType, SightingType } from "../../types/types"; import type { HitKind, QueuedHit, ReducedSightingType, SightingType } from "../../types/types";
import { BLANK_IMG, getSoundFileURL } from "../../utils/utils"; import { BLANK_IMG, getSoundFileURL } from "../../utils/utils";
import NumberPlate from "../PlateStack/NumberPlate"; import NumberPlate from "../PlateStack/NumberPlate";
import Card from "../UI/Card"; import Card from "../UI/Card";
@@ -39,19 +39,28 @@ type SightingHistoryProps = {
}; };
export default function SightingHistoryWidget({ className, title }: SightingHistoryProps) { export default function SightingHistoryWidget({ className, title }: SightingHistoryProps) {
const [modalQueue, setModalQueue] = useState<QueuedHit[]>([]);
useNow(1000); useNow(1000);
const { state } = useSoundContext(); const { state } = useSoundContext();
const soundSrcNped = useMemo(() => { const soundSrcNped = useMemo(() => {
if (state?.NPEDsound?.includes(".mp3") || state.NPEDsound?.includes(".wav")) {
const file = state.soundOptions?.find((item) => item.name === state.NPEDsound);
return file?.soundUrl ?? popup;
}
return getSoundFileURL(state.NPEDsound) ?? popup; return getSoundFileURL(state.NPEDsound) ?? popup;
}, [state.NPEDsound]); }, [state.NPEDsound, state.soundOptions]);
const soundSrcHotlist = useMemo(() => { const soundSrcHotlist = useMemo(() => {
return getSoundFileURL(state?.hotlists?.[0]?.sound) ?? notification; if (state?.hotlistSound?.includes(".mp3") || state.hotlistSound?.includes(".wav")) {
}, [state.hotlists]); const file = state.soundOptions?.find((item) => item.name === state.hotlistSound);
return file?.soundUrl ?? notification;
}
return getSoundFileURL(state?.hotlistSound) ?? notification;
}, [state.hotlistSound, state.soundOptions]);
const { play: npedSound } = useSound(soundSrcNped, { volume: state.NPEDsoundVolume }); const { play: npedSound } = useSound(soundSrcNped, { volume: state.NPEDsoundVolume });
const { play: hotlistsound } = useSound(soundSrcHotlist); const { play: hotlistsound } = useSound(soundSrcHotlist, { volume: state.hotlistSoundVolume });
const { const {
sightings, sightings,
setSelectedSighting, setSelectedSighting,
@@ -70,6 +79,14 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
const hasAutoOpenedRef = useRef(false); const hasAutoOpenedRef = useRef(false);
const npedRef = 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 => { const reduceObject = (obj: SightingType): ReducedSightingType => {
return { return {
vrm: obj.vrm, vrm: obj.vrm,
@@ -104,26 +121,15 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
const id = sighting.vrm; const id = sighting.vrm;
if (processedRefs.current.has(id)) continue; if (processedRefs.current.has(id)) continue;
const isHot = checkIsHotListHit(sighting); const isHotlistHit = checkIsHotListHit(sighting);
const cat = sighting?.metadata?.npedJSON?.["NPED CATEGORY"]; const npedcategory = sighting?.metadata?.npedJSON?.["NPED CATEGORY"];
const isNPED = npedcategory === "A" || npedcategory === "B" || npedcategory === "C";
if (cat === "A" || cat === "B" || cat === "C") { if (isNPED || isHotlistHit) {
npedSound(); enqueue(sighting, isNPED ? "NPED" : "HOTLIST"); // enqueue ONLY
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;
} }
} }
}, [rows, hotlistsound, npedSound, setSightingModalOpen, setSelectedSighting]); }, [rows, enqueue]);
useEffect(() => { useEffect(() => {
rows?.forEach((obj) => { rows?.forEach((obj) => {
@@ -156,22 +162,33 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
}); });
if (firstNPED) { if (firstNPED) {
setSelectedSighting(firstNPED); enqueue(firstNPED, "NPED");
npedSound();
setSightingModalOpen(true);
npedRef.current = true; npedRef.current = true;
} }
if (firstHot) { if (firstHot) {
setSelectedSighting(firstHot); enqueue(firstHot, "HOTLIST");
hotlistsound();
setSightingModalOpen(true);
hasAutoOpenedRef.current = true; 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 = () => { const handleClose = () => {
setSightingModalOpen(false); setSightingModalOpen(false);
setModalQueue((q) => q.slice(1));
}; };
return ( return (
<> <>

View File

@@ -4,7 +4,20 @@ import { useSoundContext } from "../../context/SoundContext";
const SliderComponent = ({ soundCategory }: { soundCategory: "SIGHTINGVOLUME" | "NPEDVOLUME" | "HOTLISTVOLUME" }) => { const SliderComponent = ({ soundCategory }: { soundCategory: "SIGHTINGVOLUME" | "NPEDVOLUME" | "HOTLISTVOLUME" }) => {
const { dispatch, state } = useSoundContext(); const { dispatch, state } = useSoundContext();
const volume = soundCategory === "SIGHTINGVOLUME" ? state.sightingVolume : state.NPEDsoundVolume;
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 handleChange = (value: number | number[]) => {
const number = typeof value === "number" ? value : value[0]; const number = typeof value === "number" ? value : value[0];
@@ -39,7 +52,7 @@ const SliderComponent = ({ soundCategory }: { soundCategory: "SIGHTINGVOLUME" |
}, },
}} }}
/> />
<span>{volume * 10}</span> <span>{volume ? volume * 10 : 1}</span>
</div> </div>
); );
}; };

View File

@@ -20,8 +20,12 @@ const SoundContextProvider = ({ children }: SoundContextProviderProps) => {
operation: "VIEW", operation: "VIEW",
path: "soundSettings", path: "soundSettings",
}); });
console.log(result.result);
dispatch({ type: "UPDATE", payload: result.result }); if (!result.result || typeof result.result !== "object") {
dispatch({ type: "UPDATE", payload: state });
} else {
dispatch({ type: "UPDATE", payload: result.result });
}
}; };
fetchSound(); fetchSound();
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps

View File

@@ -3,15 +3,16 @@ import type { SoundAction, SoundState } from "../../types/types";
export const initialState: SoundState = { export const initialState: SoundState = {
sightingSound: "switch", sightingSound: "switch",
NPEDsound: "popup", NPEDsound: "popup",
hotlistSound: "warning",
hotlists: [{ name: "hotlistName", sound: "notification" }], hotlists: [{ name: "hotlistName", sound: "notification" }],
soundOptions: [ soundOptions: [
{ name: "Switch (Default)", soundFile: "switch" }, { name: "Switch (Default)", soundFileName: "switch" },
{ name: "Popup", soundFile: "popup" }, { name: "Popup", soundFileName: "popup" },
{ name: "Notification", soundFile: "notification" }, { name: "Notification", soundFileName: "notification" },
{ name: "Beep", soundFile: "beep" }, { name: "Beep", soundFileName: "beep" },
{ name: "Ding", soundFile: "ding" }, { name: "Ding", soundFileName: "ding" },
{ name: "Shutter", soundFile: "shutter" }, { name: "Shutter", soundFileName: "shutter" },
{ name: "Warning (voice)", soundFile: "warning" }, { name: "Warning (voice)", soundFileName: "warning" },
], ],
sightingVolume: 1, sightingVolume: 1,
NPEDsoundVolume: 1, NPEDsoundVolume: 1,
@@ -25,12 +26,15 @@ export function reducer(state: SoundState, action: SoundAction): SoundState {
...state, ...state,
sightingSound: action.payload.sightingSound, sightingSound: action.payload.sightingSound,
NPEDsound: action.payload.NPEDsound, NPEDsound: action.payload.NPEDsound,
hotlistSound: action.payload.hotlistSound,
hotlists: action.payload.hotlists?.map((hotlist) => ({ hotlists: action.payload.hotlists?.map((hotlist) => ({
name: hotlist.name, name: hotlist.name,
sound: hotlist.sound, sound: hotlist.sound,
})), })),
NPEDsoundVolume: action.payload.NPEDsoundVolume, NPEDsoundVolume: action.payload.NPEDsoundVolume,
sightingVolume: action.payload.sightingVolume, sightingVolume: action.payload.sightingVolume,
hotlistSoundVolume: action.payload.hotlistSoundVolume,
soundOptions: action.payload.soundOptions,
}; };
} }
@@ -53,6 +57,12 @@ export function reducer(state: SoundState, action: SoundAction): SoundState {
NPEDsoundVolume: action.payload, NPEDsoundVolume: action.payload,
}; };
case "HOTLISTVOLUME":
return {
...state,
hotlistSoundVolume: action.payload,
};
default: default:
return state; return state;
} }

View File

@@ -43,8 +43,12 @@ export function useSightingFeed(url: string | undefined) {
}, [audioArmed, latestRef]); }, [audioArmed, latestRef]);
const soundSrc = useMemo(() => { const soundSrc = useMemo(() => {
if (state?.sightingSound?.includes(".mp3") || state.sightingSound?.includes(".wav")) {
const file = state.soundOptions?.find((item) => item.name === state.sightingSound);
return file?.soundUrl ?? switchSound;
}
return getSoundFileURL(state?.sightingSound) ?? switchSound; return getSoundFileURL(state?.sightingSound) ?? switchSound;
}, [state.sightingSound]); }, [state.sightingSound, state.soundOptions]);
function refetchInterval(query: Query<SightingType, Error, SightingType, (string | undefined)[]>) { function refetchInterval(query: Query<SightingType, Error, SightingType, (string | undefined)[]>) {
if (!query) return; if (!query) return;

View File

@@ -285,17 +285,22 @@ export type FormValues = {
sightingSound: SoundValue; sightingSound: SoundValue;
NPEDsound: SoundValue; NPEDsound: SoundValue;
hotlists: Hotlist[]; hotlists: Hotlist[];
hotlistSound: SoundValue;
soundOptions?: SoundUploadValue[];
}; };
export type SoundUploadValue = { export type SoundUploadValue = {
name: string; name: string;
soundFile: File | null; soundFileName?: string;
soundFile?: File | null;
soundUrl?: string;
}; };
export type SoundState = { export type SoundState = {
sightingSound: SoundValue; sightingSound: SoundValue;
NPEDsound: SoundValue; NPEDsound: SoundValue;
hotlists: Hotlist[]; hotlists: Hotlist[];
hotlistSound: SoundValue;
soundOptions?: SoundUploadValue[]; soundOptions?: SoundUploadValue[];
sightingVolume: number; sightingVolume: number;
NPEDsoundVolume: number; NPEDsoundVolume: number;
@@ -310,7 +315,9 @@ type UpdateAction = {
hotlists: Hotlist[]; hotlists: Hotlist[];
sightingVolume: number; sightingVolume: number;
NPEDsoundVolume: number; NPEDsoundVolume: number;
hotlistSoundVolume?: number; hotlistSoundVolume: number;
hotlistSound: SoundValue;
soundOptions?: SoundUploadValue[];
}; };
}; };
@@ -364,3 +371,11 @@ export type ModemSettingsType = {
password: string; password: string;
authenticationType: string; authenticationType: string;
}; };
export type HitKind = "NPED" | "HOTLIST";
export type QueuedHit = {
id: number | string;
sighting: SightingType;
kind: HitKind;
};

View File

@@ -21,6 +21,10 @@ export function getSoundFileURL(name: string) {
return sounds[name] ?? null; return sounds[name] ?? null;
} }
export const showSoundURL = (url: URL | string | undefined) => {
console.log(url);
};
const randomChars = () => { const randomChars = () => {
const uppercaseAsciiStart = 65; const uppercaseAsciiStart = 65;
const letterIndex = Math.floor(Math.random() * 26); const letterIndex = Math.floor(Math.random() * 26);
@@ -143,10 +147,12 @@ export const checkIsHotListHit = (sigthing: SightingType | null) => {
}; };
export function getHotlistName(obj: HotlistMatches | undefined) { export function getHotlistName(obj: HotlistMatches | undefined) {
if (!obj || Object.values(obj).includes(false)) return; if (!obj) return;
const keys = Object.keys(obj); const hotlistNames = Object.entries(obj)
return keys; .filter(([, value]) => value === true)
.map(([key]) => key);
return hotlistNames;
} }
export const getNPEDCategory = (r?: SightingType | null) => export const getNPEDCategory = (r?: SightingType | null) =>