1 Commits

Author SHA1 Message Date
d40a86bb6b - finland version release 2025-10-17 09:07:32 +01:00
79 changed files with 1146 additions and 2515 deletions

163
README.md
View File

@@ -1,116 +1,69 @@
# Mav Mobile UI # React + TypeScript + Vite
This is a React-based web application built with Vite (react and typescript). This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
## Getting started Currently, two official plugins are available:
### Prerequisites - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
- Node.js (v18 or higher recommended) ## Expanding the ESLint configuration
- Yarn (v1.22+) (https://yarnpkg.com/)
### Installation If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```bash
git clone https://mavportal.com/TobaOjo/Mav-Mobile-UI.git
cd Mav-Mobile-UI
yarn install
```
### Running Locally
```bash
yarn dev
```
The app will be available at `http://localhost:5173`.
To run on locally on other devices
```bash
yarn dev --host
```
The app will be available at the exposed addresses to access e.g. http://1xx.xxx.x.xxx:<PORT>/Mobile
## Tech Stack
- **React** UI library
- **Vite** Build tool
- **Yarn** Package manager
## Configuration
Create a `.env` file to access the Mav Mobile box in unit 5 for or for any environment-specific settings:
```env
VITE_AGX_BOX_URL=http://1xx.xxx.xxx.xxx:<PORT>
```
## Development
### Linting & Formatting
```bash
yarn lint
yarn format
```
### Testing
(Currently not implemented consider adding Jest or Vitest)
## Deployment
To build for production:
Navigate to the Mav-Mobile-UI folder
```bash
cd Mav-Mobile-UI
```
**Delete** the local .env (Production will use its own domain)
run
```bash
yarn build
```
- Navigate to your Mav-Mobile-UI folder
- Select the Dist folder
- Compress to (ZIP)
- Log into box on Moba using Session > SSH and putting IP in Remote Host.
- Creds are mav:mav
- Drag and drop dist.zip into file explorer menu on left hand side (has to be named dist.zip exactly).
- Run command
```bash
sudo ./integrate-web-ui.sh
```
Run
```bash
sudo nano web-static/index.html
```
- add the following between the lines </body> & </html>
```js ```js
<foot> export default tseslint.config([
<script> globalIgnores(['dist']),
if (window.location.pathname !== "/Mobile") { {
window.location.replace(window.location.origin + "/Mobile"); files: ['**/*.{ts,tsx}'],
} extends: [
</script> // Other configs...
</foot>
// Remove tseslint.configs.recommended and replace with this
...tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
...tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
...tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
``` ```
- Run You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```bash ```js
sudo reboot // eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
``` ```
It should come back up all working

View File

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

View File

@@ -5,7 +5,7 @@ import FrontCamera from "./pages/FrontCamera";
import RearCamera from "./pages/RearCamera"; import RearCamera from "./pages/RearCamera";
import SystemSettings from "./pages/SystemSettings"; import SystemSettings from "./pages/SystemSettings";
import Session from "./pages/Session"; import Session from "./pages/Session";
import { IntegrationsProvider } from "./context/providers/IntegrationsContextProvider"; import { NPEDUserProvider } from "./context/providers/NPEDUserContextProvider";
import { AlertHitProvider } from "./context/providers/AlertHitProvider"; import { AlertHitProvider } from "./context/providers/AlertHitProvider";
import { SoundProvider } from "react-sounds"; import { SoundProvider } from "react-sounds";
import SoundContextProvider from "./context/providers/SoundContextProvider"; import SoundContextProvider from "./context/providers/SoundContextProvider";
@@ -14,20 +14,20 @@ function App() {
return ( return (
<SoundContextProvider> <SoundContextProvider>
<SoundProvider initialEnabled={true}> <SoundProvider initialEnabled={true}>
<IntegrationsProvider> <NPEDUserProvider>
<AlertHitProvider> <AlertHitProvider>
<Routes> <Routes>
<Route path="/" element={<Container />}> <Route path="/" element={<Container />}>
<Route index element={<Dashboard />} /> <Route index element={<Dashboard />} />
<Route path="a-camera-settings" element={<FrontCamera />} /> <Route path="camera-settings" element={<FrontCamera />} />
<Route path="b-camera-settings" element={<RearCamera />} /> <Route path="rear-camera-settings" element={<RearCamera />} />
<Route path="system-settings" element={<SystemSettings />} /> <Route path="system-settings" element={<SystemSettings />} />
<Route path="session-settings" element={<Session />} /> <Route path="session-settings" element={<Session />} />
<Route path="*" element={<Navigate to="/" replace />} /> <Route path="*" element={<Navigate to="/" replace />} />
</Route> </Route>
</Routes> </Routes>
</AlertHitProvider> </AlertHitProvider>
</IntegrationsProvider> </NPEDUserProvider>
</SoundProvider> </SoundProvider>
</SoundContextProvider> </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,8 +1,11 @@
import { useGetOverviewSnapshot } from "../../hooks/useGetOverviewSnapshot"; import { useGetOverviewSnapshot } from "../../hooks/useGetOverviewSnapshot";
import type { ZoomInOptions } from "../../types/types";
import NavigationArrow from "../UI/NavigationArrow"; import NavigationArrow from "../UI/NavigationArrow";
import { useCameraZoom } from "../../hooks/useCameraZoom";
import { useEffect } from "react";
import Loading from "../UI/Loading"; import Loading from "../UI/Loading";
import ErrorState from "../UI/ErrorState"; import ErrorState from "../UI/ErrorState";
type SnapshotContainerProps = { type SnapshotContainerProps = {
side: string; side: string;
settingsPage?: boolean; settingsPage?: boolean;
@@ -10,20 +13,52 @@ type SnapshotContainerProps = {
onZoomLevelChange?: (level: number) => void; onZoomLevelChange?: (level: number) => void;
}; };
export const SnapshotContainer = ({ side, settingsPage }: SnapshotContainerProps) => { export const SnapshotContainer = ({
side,
settingsPage,
zoomLevel,
onZoomLevelChange,
}: SnapshotContainerProps) => {
const { canvasRef, isError, isPending } = useGetOverviewSnapshot(side); const { canvasRef, isError, isPending } = useGetOverviewSnapshot(side);
const cameraControllerSide =
side === "CameraA" ? "CameraControllerA" : "CameraControllerB";
const { mutation } = useCameraZoom({ camera: cameraControllerSide });
const handleZoomClick = () => {
const baseLevel = zoomLevel ?? 1;
const newLevel = baseLevel >= 8 ? 1 : baseLevel * 2;
if (onZoomLevelChange) onZoomLevelChange(newLevel);
if (!zoomLevel) return;
};
useEffect(() => {
if (zoomLevel) {
const zoomInOptions: ZoomInOptions = {
camera: cameraControllerSide,
multiplier: zoomLevel,
};
mutation.mutate(zoomInOptions);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [zoomLevel]);
return ( return (
<div className="flex flex-col md:flex-row"> <div className="flex flex-col md:flex-row">
<NavigationArrow side={side} settingsPage={settingsPage} /> <NavigationArrow side={side} settingsPage={settingsPage} />
<div className="w-full bg-[#253445] rounded-md overflow-hidden md:h-[500px] lg:h-[70vh]"> <div className="w-full">
{isError && <ErrorState />} {isError && <ErrorState />}
{isPending && ( {isPending && (
<div className="absolute inset-0 grid place-items-center"> <div className="my-50 h-[50%]">
<Loading message="Camera Preview" /> <Loading message="Camera Preview" />
</div> </div>
)} )}
<canvas ref={canvasRef} className="absolute w-full h-full z-20" /> <canvas
onClick={handleZoomClick}
ref={canvasRef}
className="absolute inset-0 object-contain min-h-[100%] z-20"
/>
</div> </div>
</div> </div>
); );

View File

@@ -4,14 +4,14 @@ import { useEffect, useMemo, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEye, faEyeSlash } from "@fortawesome/free-regular-svg-icons"; import { faEye, faEyeSlash } from "@fortawesome/free-regular-svg-icons";
import CardHeader from "../UI/CardHeader"; import CardHeader from "../UI/CardHeader";
import { useCameraMode, useCameraZoom } from "../../hooks/useCameraZoom"; import { useCameraZoom } from "../../hooks/useCameraZoom";
import { parseRTSPUrl, reverseZoomMapping, zoomMapping } from "../../utils/utils"; import { parseRTSPUrl } from "../../utils/utils";
type CameraSettingsProps = { type CameraSettingsProps = {
initialData: CameraConfig; initialData: CameraConfig;
updateCameraConfig: (values: CameraSettingValues) => Promise<void> | void; updateCameraConfig: (values: CameraSettingValues) => Promise<void> | void;
zoomLevel?: number; zoomLevel?: number;
onZoomLevelChange?: (level: number | undefined) => void; onZoomLevelChange?: (level: number) => void;
updateCameraConfigError: null | Error; updateCameraConfigError: null | Error;
}; };
@@ -20,22 +20,38 @@ const CameraSettingFields = ({
updateCameraConfig, updateCameraConfig,
zoomLevel, zoomLevel,
onZoomLevelChange, onZoomLevelChange,
updateCameraConfigError,
}: CameraSettingsProps) => { }: CameraSettingsProps) => {
const [showPwd, setShowPwd] = useState(false); const [showPwd, setShowPwd] = useState(false);
const cameraControllerSide = initialData?.id === "CameraA" ? "CameraControllerA" : "CameraControllerB"; const cameraControllerSide = initialData?.id === "CameraA" ? "CameraControllerA" : "CameraControllerB";
const { mutation, query } = useCameraZoom({ camera: cameraControllerSide }); const { mutation, query } = useCameraZoom({ camera: cameraControllerSide });
const { cameraModeQuery, cameraModeMutation } = useCameraMode({ camera: cameraControllerSide }); const zoomOptions = [1, 2, 4, 8];
const zoomOptions = [1, 2, 4];
const magnification = query?.data?.propMagnification?.value;
const apiZoom = reverseZoomMapping(magnification);
const parsed = parseRTSPUrl(initialData?.propURI?.value); const parsed = parseRTSPUrl(initialData?.propURI?.value);
const cameraMode = cameraModeQuery?.data?.propDayNightMode?.value;
useEffect(() => { useEffect(() => {
if (!query?.data) return; if (!query?.data) return;
const apiZoom = getZoomLevel(query.data);
onZoomLevelChange?.(apiZoom); onZoomLevelChange?.(apiZoom);
}, [query?.data, onZoomLevelChange, apiZoom]); }, [query?.data, onZoomLevelChange]);
const getZoomLevel = (levelstring: string | undefined) => {
switch (levelstring) {
case "1x":
return 1;
case "2x":
return 2;
case "4x":
return 4;
case "8x":
return 8;
default:
return 1;
}
};
const initialValues = useMemo<CameraSettingValues>( const initialValues = useMemo<CameraSettingValues>(
() => ({ () => ({
@@ -44,11 +60,11 @@ const CameraSettingFields = ({
userName: parsed?.username ?? "", userName: parsed?.username ?? "",
password: parsed?.password ?? "", password: parsed?.password ?? "",
id: initialData?.id, id: initialData?.id,
mode: cameraMode ?? "day",
zoom: apiZoom,
}),
[initialData?.id, initialData?.propURI?.value, parsed?.username, parsed?.password, cameraMode, apiZoom] zoom: zoomLevel,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[initialData?.id, initialData?.propURI?.value, zoomLevel]
); );
const validateValues = (values: CameraSettingValues) => { const validateValues = (values: CameraSettingValues) => {
@@ -64,18 +80,15 @@ const CameraSettingFields = ({
const handleRadioButtonChange = async (levelNumber: number) => { const handleRadioButtonChange = async (levelNumber: number) => {
if (!onZoomLevelChange || !zoomLevel) return; if (!onZoomLevelChange || !zoomLevel) return;
const text = zoomMapping(levelNumber);
onZoomLevelChange(levelNumber); onZoomLevelChange(levelNumber);
const zoomInOptions: ZoomInOptions = { const zoomInOptions: ZoomInOptions = {
camera: cameraControllerSide, camera: cameraControllerSide,
multiplier: levelNumber, multiplier: levelNumber,
multiplierText: text,
}; };
mutation.mutate(zoomInOptions); mutation.mutate(zoomInOptions);
}; };
const selectedZoom = zoomLevel ?? 1; const selectedZoom = zoomLevel ?? 1;
return ( return (
<Formik <Formik
@@ -85,8 +98,8 @@ const CameraSettingFields = ({
validateOnChange={false} validateOnChange={false}
enableReinitialize enableReinitialize
> >
{({ errors, touched, values, setFieldValue, isSubmitting }) => ( {({ errors, touched }) => (
<Form className="flex flex-col space-y-6 p-2 overflow-x-hidden"> <Form className="flex flex-col space-y-6 p-2">
<div className="flex flex-col space-y-2 relative"> <div className="flex flex-col space-y-2 relative">
<label htmlFor="friendlyName">Name</label> <label htmlFor="friendlyName">Name</label>
{touched.friendlyName && errors.friendlyName && ( {touched.friendlyName && errors.friendlyName && (
@@ -98,6 +111,7 @@ const CameraSettingFields = ({
type="text" type="text"
className="p-2 border border-gray-400 rounded-lg" className="p-2 border border-gray-400 rounded-lg"
placeholder="Enter camera name" placeholder="Enter camera name"
disabled
/> />
</div> </div>
@@ -112,6 +126,7 @@ const CameraSettingFields = ({
type="text" type="text"
className="p-2 border border-gray-400 rounded-lg" className="p-2 border border-gray-400 rounded-lg"
placeholder="RTSP://..." placeholder="RTSP://..."
disabled
/> />
</div> </div>
@@ -127,6 +142,7 @@ const CameraSettingFields = ({
className="p-2 border border-gray-400 rounded-lg" className="p-2 border border-gray-400 rounded-lg"
placeholder="Enter user name" placeholder="Enter user name"
autoComplete="username" autoComplete="username"
disabled
/> />
</div> </div>
@@ -142,6 +158,7 @@ const CameraSettingFields = ({
type={showPwd ? "text" : "password"} type={showPwd ? "text" : "password"}
className="p-2 border border-gray-400 rounded-lg w-full " className="p-2 border border-gray-400 rounded-lg w-full "
placeholder="Enter password" placeholder="Enter password"
disabled
/> />
<FontAwesomeIcon <FontAwesomeIcon
type="button" type="button"
@@ -152,7 +169,7 @@ const CameraSettingFields = ({
</div> </div>
<div className="my-3"> <div className="my-3">
<CardHeader title="Zoom settings" /> <CardHeader title="Zoom settings" />
<div className="mx-auto grid grid-cols-3 place-items-center"> <div className="mx-auto grid grid-cols-4 items-center">
{zoomOptions.map((zoom) => ( {zoomOptions.map((zoom) => (
<div key={zoom} className="my-3"> <div key={zoom} className="my-3">
<Field <Field
@@ -170,53 +187,27 @@ const CameraSettingFields = ({
peer-checked:border-2 peer-checked:border-blue-900 peer-checked:border-2 peer-checked:border-blue-900
peer-checked:text-blue-600 peer-checked:bg-gray-100" peer-checked:text-blue-600 peer-checked:bg-gray-100"
> >
{zoomMapping(zoom)} x{zoom}
</label>
</div>
))}
</div>
</div>
<div>
<CardHeader title="Mode" />
<div
role="radiogroup"
aria-label="Camera mode"
className="mx-auto grid grid-cols-2 place-items-center gap-3"
>
{["day", "night"].map((el) => (
<div key={el} className="my-3">
<Field
type="radio"
name="mode"
value={el}
checked={values.mode === el}
id={`mode-${el}`}
className="peer hidden"
disabled={cameraModeMutation.isPending}
onChange={async () => {
setFieldValue("mode", el);
await cameraModeMutation.mutateAsync({ camera: cameraControllerSide, mode: el });
}}
/>
<label
htmlFor={`mode-${el}`}
className={`px-8 py-2 rounded-md border border-gray-300
peer-checked:border-2 peer-checked:border-blue-900
peer-checked:text-blue-600 peer-checked:bg-gray-100
${cameraModeMutation.isPending ? "opacity-60 cursor-not-allowed" : "cursor-pointer"}`}
>
{el === "day" ? "Day" : "Night"}
</label> </label>
</div> </div>
))} ))}
</div> </div>
</div> </div>
<div className="mt-3"> <div className="mt-3">
{ {updateCameraConfigError ? (
<button type="submit" className="bg-green-700 text-white rounded-lg p-2 mx-auto w-full"> <button className="bg-red-500 text-white rounded-lg p-2 mx-auto h-[100%] w-full" disabled>
{isSubmitting ? "Saving" : "Save settings"} Retry
</button> </button>
} ) : (
<button
type="submit"
className="bg-blue-700 text-white rounded-lg p-2 mx-auto h-[100%] w-full"
disabled
>
{/* {isSubmitting ? "Saving" : "Save settings"} bg-[#26B170] */}
{"Disabled: Coming soon"}
</button>
)}
</div> </div>
</div> </div>
</Form> </Form>

View File

@@ -13,14 +13,15 @@ const CameraSettings = ({
title: string; title: string;
side: string; side: string;
zoomLevel?: number; zoomLevel?: number;
onZoomLevelChange?: (level: number | undefined) => void; onZoomLevelChange?: (level: number) => void;
}) => { }) => {
const { data, updateCameraConfig, updateCameraConfigError } = useFetchCameraConfig(side); const { data, updateCameraConfig, updateCameraConfigError } = useFetchCameraConfig(side);
return ( return (
<Card className="overflow-x-visible min-h-[40vh] md:min-h-[60vh] lg:w-[40%] p-4"> <Card className="overflow-hidden min-h-[40vh] md:min-h-[60vh] max-h-[80vh] lg:w-[40%] p-4">
<div className="relative flex flex-col space-y-3"> <div className="relative flex flex-col space-y-3">
<CardHeader title={title} icon={faWrench} /> <CardHeader title={title} icon={faWrench} />
{ {
<CameraSettingFields <CameraSettingFields
initialData={data} initialData={data}

View File

@@ -8,8 +8,8 @@ import SightingOverview from "../SightingOverview/SightingOverview";
const FrontCameraOverviewCard = () => { const FrontCameraOverviewCard = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const handlers = useSwipeable({ const handlers = useSwipeable({
onSwipedRight: () => navigate("/a-camera-settings"), onSwipedRight: () => navigate("/camera-settings"),
onSwipedLeft: () => navigate("/b-camera-settings"), onSwipedLeft: () => navigate("/rear-camera-settings"),
trackMouse: true, trackMouse: true,
}); });

View File

@@ -20,17 +20,17 @@ const OverviewVideoContainer = ({
const location = useLocation(); const location = useLocation();
const handlers = useSwipeable({ const handlers = useSwipeable({
onSwipedLeft: () => { onSwipedLeft: () => {
if (location.pathname === "/b-camera-settings") return; if (location.pathname === "/rear-camera-settings") return;
navigate("/"); navigate("/");
}, },
onSwipedRight: () => { onSwipedRight: () => {
if (location.pathname === "/a-camera-settings") return; if (location.pathname === "/camera-settings") return;
navigate("/"); navigate("/");
}, },
trackMouse: true, trackMouse: true,
}); });
return ( return (
<Card className={clsx("relative min-h-[40vh] md:min-h-[40vh] max-h-[70vh] lg:w-[70%] overflow-y-hidden")}> <Card className={clsx("relative min-h-[40vh] md:min-h-[60vh] max-h-[80vh] lg:w-[70%] overflow-y-hidden")}>
<div className="w-full" {...handlers}> <div className="w-full" {...handlers}>
<SnapshotContainer <SnapshotContainer
side={side} side={side}

View File

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

View File

@@ -13,7 +13,7 @@ type CardProps = React.HTMLAttributes<HTMLDivElement>;
const RearCameraOverviewCard = ({ className }: CardProps) => { const RearCameraOverviewCard = ({ className }: CardProps) => {
const navigate = useNavigate(); const navigate = useNavigate();
const handlers = useSwipeable({ const handlers = useSwipeable({
onSwipedLeft: () => navigate("/b-camera-settings"), onSwipedLeft: () => navigate("/rear-camera-settings"),
trackMouse: true, trackMouse: true,
}); });
const { mostRecent } = useSightingFeedContext(); const { mostRecent } = useSightingFeedContext();

View File

@@ -1,36 +1,30 @@
import Card from "../UI/Card"; import Card from "../UI/Card";
import CardHeader from "../UI/CardHeader"; import CardHeader from "../UI/CardHeader";
import { useIntegrationsContext } from "../../context/IntegrationsContext"; import { useNPEDContext } from "../../context/NPEDUserContext";
import type { ReducedSightingType } from "../../types/types"; import type { ReducedSightingType } from "../../types/types";
import { toast } from "sonner"; 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 SessionCard = () => {
const { state, dispatch } = useIntegrationsContext(); const { sessionStarted, setSessionStarted, sessionList } = useNPEDContext();
const { mutation } = useCameraBlackboard();
const sessionStarted = state.sessionStarted; const handleStartClick = () => {
const sessionPaused = state.sessionPaused; setSessionStarted(!sessionStarted);
const sessionList = state.sessionList; toast(`${sessionStarted ? "Vehicle tracking session Ended" : "Vehicle tracking session Started"}`);
};
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 dedupedSightings = sightings.map((sighting) => sighting[1]);
const vehicles = dedupedSightings.reduce<Record<string, ReducedSightingType[]>>( const vehicles = dedupedSightings.reduce<Record<string, ReducedSightingType[]>>(
(acc, item) => { (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"] === "A") acc.npedCatA.push(item);
if (item.metadata?.npedJSON["NPED CATEGORY"] === "B") acc.npedCatB.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"] === "C") acc.npedCatC.push(item);
if (item.metadata?.npedJSON["NPED CATEGORY"] === "D") acc.npedCatD.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["TAX STATUS"] === false) acc.notTaxed.push(item);
if (item.metadata?.npedJSON["MOT STATUS"] === false) acc.notMOT.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; return acc;
}, },
{ {
@@ -40,32 +34,9 @@ const SessionCard = () => {
npedCatD: [], npedCatD: [],
notTaxed: [], notTaxed: [],
notMOT: [], 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 ( return (
<Card className="p-4 col-span-3"> <Card className="p-4 col-span-3">
<CardHeader title="Session" /> <CardHeader title="Session" />
@@ -76,72 +47,34 @@ const SessionCard = () => {
} transition w-full`} } transition w-full`}
onClick={handleStartClick} onClick={handleStartClick}
> >
<div className="flex flex-row gap-3 items-center justify-self-center"> {sessionStarted ? "End Session" : "Start Session"}
<FontAwesomeIcon icon={sessionStarted ? faStop : faPlay} />
<p>{sessionStarted ? "End Session" : "Start Session"}</p>
</div>
</button> </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"> <ul className="text-white space-y-2">
<VehicleSessionItem <li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
sessionNumber={vehicles.vehicles.length} <p>Number of Vehicles:</p>
textColour="text-green-400" <span className="font-bold text-green-600 text-xl">{dedupedSightings.length}</span>
vehicleTag={"Number of Vehicles sightings:"} </li>
/> <li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
<VehicleSessionItem <p>Vehicles without Tax:</p>
sessionNumber={vehicles.notTaxed.length} <span className="font-bold text-amber-600 text-xl">{vehicles.notTaxed.length}</span>
textColour="text-amber-400" </li>
vehicleTag={"Vehicles without Tax:"} <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>{" "}
<VehicleSessionItem <span className="font-bold text-red-500 text-xl">{vehicles.notMOT.length}</span>
sessionNumber={vehicles.notMOT.length} </li>
textColour="text-red-500" <li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
vehicleTag={"Vehicles without MOT:"} <p>Vehicles with NPED Cat A:</p>
/> <span className="font-bold text-gray-300 text-xl">{vehicles.npedCatA.length}</span>
<VehicleSessionItem </li>
sessionNumber={vehicles.hotlistHit.length} <li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
textColour="text-blue-400" <p>Vehicles with NPED Cat B:</p>{" "}
vehicleTag={"Vehicles on Hotlists:"} <span className="font-bold text-gray-300text-xl">{vehicles.npedCatB.length}</span>
/> </li>
<VehicleSessionItem <li className="rounded-xl border border-slate-800 bg-slate-800/60 p-3 shadow-sm flex flex-row justify-between">
sessionNumber={vehicles.npedCatA.length} Vehicles with NPED Cat C:{" "}
textColour="text-gray-300" <span className="font-bold text-gray-300 text-xl">{vehicles.npedCatC.length}</span>
vehicleTag={"Vehicles with NPED Cat A:"} </li>
/>
<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> </ul>
</div> </div>
</Card> </Card>

View File

@@ -4,7 +4,7 @@ import BearerTypeFields from "./BearerTypeFields";
const BearerTypeCard = () => { const BearerTypeCard = () => {
return ( return (
<Card className="p-4 h-60"> <Card className="p-4">
<CardHeader title="Bearer Type" /> <CardHeader title="Bearer Type" />
<BearerTypeFields /> <BearerTypeFields />
</Card> </Card>

View File

@@ -1,12 +1,41 @@
import { Field, useFormikContext } from "formik"; import { Field, Form, Formik } from "formik";
import FormToggle from "../components/FormToggle"; import FormToggle from "../components/FormToggle";
import { useCameraOutput } from "../../../hooks/useCameraOutput";
import { cleanArray } from "../../../utils/utils";
import FormGroup from "../components/FormGroup"; import FormGroup from "../components/FormGroup";
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types"; import type { BearerTypeFieldType } from "../../../types/types";
export const ValuesComponent = () => {
return null;
};
const BearerTypeFields = () => { const BearerTypeFields = () => {
useFormikContext<BearerTypeFieldType & InitialValuesForm>(); 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);
};
return ( return (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize
>
{({ isSubmitting }) => (
<Form>
<div className="flex flex-col space-y-4 px-2"> <div className="flex flex-col space-y-4 px-2">
<FormGroup> <FormGroup>
<label htmlFor="format">Format</label> <label htmlFor="format">Format</label>
@@ -16,20 +45,31 @@ const BearerTypeFields = () => {
id="format" id="format"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60" className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
> >
<option key={"JSON"} value={"JSON"}> {options?.map((option: string) => (
JSON <option key={option} value={option}>
</option> {option}
<option key={"BOF2"} value={"BOF2"}>
BOF2
</option> </option>
))}
</Field> </Field>
</FormGroup> </FormGroup>
<FormGroup> <FormGroup>
<div className="flex flex-col space-y-4"> <div className="flex flex-col space-y-4">
<FormToggle name="enabled" label="Enabled" /> <FormToggle name="enabled" label="Enabled" />
<FormToggle name="verbose" label="Verbose" />
</div> </div>
</FormGroup> </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> </div>
</Form>
)}
</Formik>
); );
}; };

View File

@@ -1,54 +1,12 @@
import { useFormikContext, type FormikTouched } from "formik";
import Card from "../../UI/Card"; import Card from "../../UI/Card";
import CardHeader from "../../UI/CardHeader"; import CardHeader from "../../UI/CardHeader";
import ChannelFields from "./ChannelFields"; 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;
isBof2ConstantsLoading: boolean;
isDispatcherLoading: boolean;
};
const ChannelCard = ({ touched, isSubmitting, isBof2ConstantsLoading, isDispatcherLoading }: ChannelCardProps) => {
const { values, setFieldValue } = useFormikContext<BearerTypeFieldType & InitialValuesForm>();
const { backOfficeQuery } = useCameraBackOfficeOutput(values?.format);
const isBackOfficeQueryLoading = backOfficeQuery?.isFetching;
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 ( return (
<Card className="p-4 overflow-y-auto "> <Card className="p-4">
<CardHeader title={`Channel (${values?.format})`} /> <CardHeader title="Channel 1 (JSON)" />
{!isBof2ConstantsLoading && !isDispatcherLoading && !isBackOfficeQueryLoading ? ( <ChannelFields />
<ChannelFields
touched={touched}
isSubmitting={isSubmitting}
backOfficeData={backOfficeQuery}
format={values?.format}
/>
) : (
<>Loading...</>
)}
</Card> </Card>
); );
}; };

View File

@@ -1,52 +1,91 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Field, Form, Formik, useFormikContext } from "formik";
import { Field, useFormikContext, type FormikTouched } from "formik";
import FormGroup from "../components/FormGroup"; import FormGroup from "../components/FormGroup";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons"; import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types"; import { useCameraOutput } from "../../../hooks/useCameraOutput";
import type {
InitialValuesForm,
InitialValuesFormErrors,
} from "../../../types/types";
import { toast } from "sonner"; import { toast } from "sonner";
import type { UseQueryResult } from "@tanstack/react-query";
type ChannelFieldsProps = { const ChannelFields = () => {
touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>; const [showPwd, setShowPwd] = useState(false);
isSubmitting: boolean; const { backOfficeQuery, backOfficeMutation } = useCameraOutput();
backOfficeData: UseQueryResult<any, Error>; const backOfficeURL = backOfficeQuery?.data?.propBackofficeURL?.value;
format?: string; 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 ChannelFields = ({ touched, isSubmitting, format }: ChannelFieldsProps) => { const handleSubmit = async (values: InitialValuesForm) => {
const [showPwd, setShowPwd] = useState(false); await backOfficeMutation.mutateAsync(values);
const { submitCount, isValid, values, errors } = useFormikContext<BearerTypeFieldType & InitialValuesForm>(); };
const ValidationToastOnce = () => { const ValidationToastOnce = () => {
const { submitCount, isValid } = useFormikContext();
useEffect(() => { useEffect(() => {
if (submitCount > 0 && !isValid) { if (submitCount > 0 && !isValid) {
toast.error("Check fields are filled in"); toast.error("Check fields are filled in");
} }
}, []); }, [submitCount, isValid]);
return null; return null;
}; };
return ( const validateValues = (
<> values: InitialValuesForm
{format?.toLowerCase() !== "bof2" && format?.toLowerCase() !== "json" ? ( ): InitialValuesFormErrors => {
<> const errors: InitialValuesFormErrors = {};
<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"> const url = values.backOfficeURL?.trim();
Output configuration currently supports <span className="font-bold text-blue-400">JSON</span> or{" "} const username = values.username?.trim();
<span className="font-bold text-emerald-400">BOF2</span>. <br /> More formats will be added in future const password = values.password?.trim();
updates.
</p> if (!url) {
</div> 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>
<div className="flex flex-col space-y-2 px-2"> <div className="flex flex-col space-y-2 px-2">
<FormGroup> <FormGroup>
<label htmlFor="backoffice" className="m-0"> <label htmlFor="backoffice" className="m-0">
@@ -58,7 +97,11 @@ const ChannelFields = ({ touched, isSubmitting, format }: ChannelFieldsProps) =>
type="text" type="text"
id="backoffice" id="backoffice"
placeholder="https://www.backoffice.com" placeholder="https://www.backoffice.com"
className={`p-1.5 border border-gray-400 rounded-lg w-full md:w-60`} className={`p-1.5 border ${
errors.backOfficeURL && touched.backOfficeURL
? "border-red-500"
: "border-gray-400 "
} rounded-lg w-full md:w-60`}
/> />
</FormGroup> </FormGroup>
<FormGroup> <FormGroup>
@@ -68,7 +111,11 @@ const ChannelFields = ({ touched, isSubmitting, format }: ChannelFieldsProps) =>
type="text" type="text"
id="username" id="username"
placeholder="Back office username" placeholder="Back office username"
className={`p-1.5 border border-gray-400 rounded-lg w-full md:w-60`} className={`p-1.5 border ${
errors.username && touched.username
? "border-red-500"
: "border-gray-400 "
} rounded-lg w-full md:w-60`}
/> />
</FormGroup> </FormGroup>
<FormGroup> <FormGroup>
@@ -80,7 +127,9 @@ const ChannelFields = ({ touched, isSubmitting, format }: ChannelFieldsProps) =>
id="password" id="password"
placeholder="Back office password" placeholder="Back office password"
className={`p-1.5 border ${ 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`} } rounded-lg w-full md:w-60`}
/> />
<FontAwesomeIcon <FontAwesomeIcon
@@ -93,13 +142,17 @@ const ChannelFields = ({ touched, isSubmitting, format }: ChannelFieldsProps) =>
</FormGroup> </FormGroup>
<FormGroup> <FormGroup>
<label htmlFor="connectTimeoutSeconds">Connect Timeout Seconds</label> <label htmlFor="connectTimeoutSeconds">
Connect Timeout Seconds
</label>
<Field <Field
name={"connectTimeoutSeconds"} name={"connectTimeoutSeconds"}
type="number" type="number"
id="connectTimeoutSeconds" id="connectTimeoutSeconds"
className={`p-1.5 border ${ 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`} } rounded-lg w-full md:w-60`}
/> />
</FormGroup> </FormGroup>
@@ -111,137 +164,25 @@ const ChannelFields = ({ touched, isSubmitting, format }: ChannelFieldsProps) =>
id="readTimeoutSeconds" id="readTimeoutSeconds"
placeholder="https://example.com" placeholder="https://example.com"
className={`p-1.5 border ${ className={`p-1.5 border ${
errors.readTimeoutSeconds && touched.readTimeoutSeconds ? "border-red-500" : "border-gray-400 " errors.readTimeoutSeconds && touched.readTimeoutSeconds
} rounded-lg w-full md:w-60`} ? "border-red-500"
/> : "border-gray-400 "
</FormGroup>
{/* Overview quality and scale */}
<FormGroup>
<label htmlFor="overviewQuality">Overview quality and scale</label>
<Field
name={"overviewQuality"}
as="select"
id="overviewQuality"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
<option value={"HIGH"}>High</option>
<option value={"MEDIUM"}>Medium</option>
<option value={"LOW"}>Low</option>
</Field>
</FormGroup>
{/* propOverviewImageScaleFactor cropSizeFactor */}
<FormGroup>
<label htmlFor="cropSizeFactor">Crop Size Factor</label>
<Field
name={"cropSizeFactor"}
as="select"
id="cropSizeFactor"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
<option value={"FULL"}>Full</option>
<option value={"3/4"}>3/4</option>
<option value={"1/2"}>1/2</option>
<option value={"1/4"}>1/4</option>
</Field>
</FormGroup>
{format?.toLowerCase() === "bof2" && (
<>
<div className="space-y-3">
<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={"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={"Minutes"}>Minutes</option>
<option value={"Decimal Degrees"}>Decimal degrees</option>
</Field>
</FormGroup>
</div>
<div className="space-y-3">
<div className="border-b border-gray-500 my-3">
<h2 className="font-bold">{values.format} Lane ID Config</h2>
</div>
<FormGroup>
<label htmlFor="LID1">Lane ID 1 (Camera A)</label>
<Field
name={"LID1"}
type="text"
id="LID1"
placeholder="10"
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="LID2">Lane ID 2 (Camera B)</label>
<Field
name={"LID2"}
type="text"
id="LID2"
placeholder="20"
className={`p-1.5 border ${
errors.readTimeoutSeconds && touched.readTimeoutSeconds ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`} } rounded-lg w-full md:w-60`}
/> />
</FormGroup> </FormGroup>
</div> </div>
</>
)}
</div>
<button <button
type="submit" 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="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full md:w-[50%]"
> >
{isSubmitting ? "Saving..." : "Save Changes"} {isSubmitting || backOfficeMutation.isPending
? "Saving..."
: "Save Changes"}
</button> </button>
<ValidationToastOnce /> <ValidationToastOnce />
</> </Form>
)} )}
</> </Formik>
); );
}; };

View File

@@ -6,18 +6,16 @@ import { toast } from "sonner";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons"; import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useState } from "react"; import { useState } from "react";
import { useIntegrationsContext } from "../../../context/IntegrationsContext";
const NPEDFields = () => { const NPEDFields = () => {
const { state } = useIntegrationsContext();
const [showPwd, setShowPwd] = useState(false); const [showPwd, setShowPwd] = useState(false);
const { signIn, signOut } = useNPEDAuth(); const { signIn, user, signOut } = useNPEDAuth();
const initialValues = state.npedUser const initialValues = user
? { ? {
username: state.npedUser?.propUsername?.value, username: user?.propUsername?.value,
password: state.npedUser?.propPassword?.value, password: user?.propPassword?.value,
clientId: state.npedUser?.propClientID?.value, clientId: user?.propClientID?.value,
frontId: "NPED", frontId: "NPED",
rearId: "NPED", rearId: "NPED",
} }
@@ -50,13 +48,20 @@ const NPEDFields = () => {
}; };
return ( return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} validate={validateValues} enableReinitialize> <Formik
initialValues={initialValues}
onSubmit={handleSubmit}
validate={validateValues}
enableReinitialize
>
{({ errors, touched, isSubmitting }) => ( {({ errors, touched, isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2"> <Form className="flex flex-col space-y-5 px-2">
<FormGroup> <FormGroup>
<label htmlFor="username">Username</label> <label htmlFor="username">Username</label>
{touched.username && errors.username && ( {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 <Field
name="username" name="username"
@@ -77,7 +82,9 @@ const NPEDFields = () => {
className="p-2 border border-gray-400 rounded-lg w-full" className="p-2 border border-gray-400 rounded-lg w-full"
/> />
{touched.password && errors.password && ( {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 <FontAwesomeIcon
type="button" type="button"
@@ -90,7 +97,9 @@ const NPEDFields = () => {
<FormGroup> <FormGroup>
<label htmlFor="clientId">Client ID</label> <label htmlFor="clientId">Client ID</label>
{touched.clientId && errors.clientId && ( {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 <Field
name="clientId" name="clientId"
@@ -100,7 +109,7 @@ const NPEDFields = () => {
className="p-1.5 border border-gray-400 rounded-lg" className="p-1.5 border border-gray-400 rounded-lg"
/> />
</FormGroup> </FormGroup>
{!state.npedUser?.propClientID?.value ? ( {!user?.propClientID?.value ? (
<button <button
type="submit" 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" 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" type="file"
name="file" name="file"
id="file" id="file"
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="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) { if (e.target.files) {
if (e.target.files[0].type !== "text/csv") { if (e.target.files[0].type !== "text/csv") {

View File

@@ -1,151 +1,12 @@
import { Form, Formik } from "formik";
import BearerTypeCard from "../BearerType/BearerTypeCard"; import BearerTypeCard from "../BearerType/BearerTypeCard";
import ChannelCard from "../Channel1-JSON/ChannelCard"; import ChannelCard from "../Channel1-JSON/ChannelCard";
import { useCameraOutput, useGetDispatcherConfig } from "../../../hooks/useCameraOutput";
import type {
BearerTypeFieldType,
InitialValuesForm,
InitialValuesFormErrors,
OptionalBOF2Constants,
OptionalBOF2LaneIDs,
} from "../../../types/types";
import { useQueryClient } from "@tanstack/react-query";
import { useUpdateBackOfficeConfig } from "../../../hooks/useBackOfficeConfig";
import { useFormVaidate } from "../../../hooks/useFormValidate";
import { useSightingAmend } from "../../../hooks/useSightingAmend";
import StoreCard from "../Store/StoreCard";
const SettingForms = () => { const SettingForms = () => {
const qc = useQueryClient();
const { dispatcherQuery, dispatcherMutation, backOfficeDispatcherMutation, bof2LandMutation, laneIdQuery } =
useCameraOutput();
const { backOfficeMutation } = useUpdateBackOfficeConfig();
const { bof2ConstantsQuery } = useGetDispatcherConfig();
const { validateMutation } = useFormVaidate();
const { sightingAmendQuery, sightingAmendMutation } = useSightingAmend();
const format = dispatcherQuery?.data?.propFormat?.value;
const enabled = dispatcherQuery?.data?.propEnabled?.value;
const sightingQuality = sightingAmendQuery?.data?.propOverviewQuality?.value;
const cropSizeFactor = sightingAmendQuery?.data?.propOverviewImageScaleFactor?.value;
const laneID = laneIdQuery?.data?.id;
const LID1 = laneIdQuery?.data?.propLaneID1?.value;
const LID2 = laneIdQuery?.data?.propLaneID2?.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 isDispatcherLoading = dispatcherQuery?.isFetching;
const isBof2ConstantsLoading = bof2ConstantsQuery?.isFetching;
const initialValues: BearerTypeFieldType & InitialValuesForm & OptionalBOF2Constants & OptionalBOF2LaneIDs = {
format: format ?? "JSON",
enabled: enabled === "true",
backOfficeURL: "",
username: "",
password: "",
connectTimeoutSeconds: Number(5),
readTimeoutSeconds: Number(15),
overviewQuality: sightingQuality ?? "HIGH",
cropSizeFactor: cropSizeFactor ?? "3/4",
// Bof2 - optional constants
FFID: FFID ?? "",
SCID: SCID ?? "",
timestampSource: timestampSource ?? "",
GPSFormat: GPSFormat ?? "",
//BOF2 - optional Lane IDs
laneId: laneID ?? "",
LID1: LID1 ?? "",
LID2: LID2 ?? "",
};
const validateValues = (values: InitialValuesForm): InitialValuesFormErrors => {
const errors: InitialValuesFormErrors = {};
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 & OptionalBOF2LaneIDs
) => {
const validResponse = await validateMutation.mutateAsync(values);
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] });
if (validResponse?.reason === "OK") {
await backOfficeMutation.mutateAsync(values);
await sightingAmendMutation.mutateAsync(values);
if (values.format.toLowerCase() === "bof2") {
const bof2ConstantsData: OptionalBOF2Constants = {
FFID: values.FFID,
SCID: values.SCID,
timestampSource: values.timestampSource,
GPSFormat: values.GPSFormat,
};
const bof2LaneData: OptionalBOF2LaneIDs = {
laneId: laneIdQuery?.data?.id,
LID1: values.LID1,
LID2: values.LID2,
};
await bof2LandMutation.mutateAsync(bof2LaneData);
await backOfficeDispatcherMutation.mutateAsync(bof2ConstantsData);
}
} else {
console.log("error");
return;
}
}
};
return ( 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"> <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">
<div>
<BearerTypeCard /> <BearerTypeCard />
<StoreCard /> <ChannelCard />
</div> </div>
<ChannelCard
touched={touched}
isSubmitting={isSubmitting}
isDispatcherLoading={isDispatcherLoading}
isBof2ConstantsLoading={isBof2ConstantsLoading}
/>
</div>
</Form>
)}
</Formik>
); );
}; };

View File

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

View File

@@ -1,10 +1,9 @@
import { Field, Form, Formik } from "formik"; import { Field, FieldArray, 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";
import { useCameraBlackboard } from "../../../hooks/useCameraBlackboard"; import { useCameraBlackboard } from "../../../hooks/useCameraBlackboard";
import { toast } from "sonner"; import { toast } from "sonner";
import SliderComponent from "../../UI/Slider";
const SoundSettingsFields = () => { const SoundSettingsFields = () => {
const { state, dispatch } = useSoundContext(); const { state, dispatch } = useSoundContext();
@@ -13,31 +12,22 @@ 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?.soundFileName, value: soundOption?.name,
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,
}; };
const handleSubmit = async (values: FormValues) => { const handleSubmit = async (values: FormValues) => {
const updatedValues = { dispatch({ type: "UPDATE", payload: values });
...values,
sightingVolume: state.sightingVolume,
NPEDsoundVolume: state.NPEDsoundVolume,
hotlistSoundVolume: state.hotlistSoundVolume,
soundOptions: [...(state.soundOptions ?? [])],
};
dispatch({ type: "UPDATE", payload: updatedValues });
const result = await mutation.mutateAsync({ const result = await mutation.mutateAsync({
operation: "INSERT", operation: "INSERT",
path: "soundSettings", path: "soundSettings",
value: updatedValues, value: values,
}); });
if (result.reason !== "OK") { if (result.reason !== "OK") {
toast.error("Cannot update sound settings"); toast.error("Cannot update sound settings");
@@ -47,10 +37,9 @@ 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">
<label htmlFor="sightingSound">Sighting Sound</label> <label htmlFor="sightingSound">Sighting Sound</label>
<Field <Field
as="select" as="select"
@@ -59,17 +48,14 @@ const SoundSettingsFields = () => {
> >
{soundOptions?.map(({ value, label }) => { {soundOptions?.map(({ value, label }) => {
return ( return (
<option key={label} value={value}> <option key={value} value={value}>
{label} {label}
</option> </option>
); );
})} })}
</Field> </Field>
<SliderComponent soundCategory="SIGHTINGVOLUME" />
</div>
</FormGroup> </FormGroup>
<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> <label htmlFor="NPEDsound">NPED notification Sound</label>
<Field <Field
as="select" as="select"
@@ -82,37 +68,24 @@ const SoundSettingsFields = () => {
</option> </option>
))} ))}
</Field> </Field>
<SliderComponent soundCategory="NPEDVOLUME" />
</div>
</FormGroup> </FormGroup>
<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={() => (
<div className="w-full m-2"> <div className="w-full m-2">
{values?.hotlists?.length > 0 ? ( {values?.hotlists?.length > 0 ? (
values?.hotlists?.map((hotlist, index) => ( values?.hotlists?.map((hotlist, index) => (
<div key={hotlist.name} className="flex items-center m-2 w-full justify-between"> <div
<label htmlFor={`hotlists.${index}.sound`} className="w-32 shrink-0"> 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} {hotlist.name}
</label> </label>
<Field <Field
@@ -135,7 +108,7 @@ const SoundSettingsFields = () => {
</div> </div>
)} )}
/> />
</FormGroup> */} </FormGroup>
</div> </div>
<button <button
type="submit" type="submit"

View File

@@ -3,80 +3,45 @@ 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";
import { useFileUpload } from "../../../hooks/useFileUpload";
const SoundUpload = () => { const SoundUpload = () => {
const { state, dispatch } = useSoundContext(); const { dispatch } = useSoundContext();
const { mutation } = useCameraBlackboard();
const { mutation: fileMutation } = useFileUpload({
queryKey: state.sightingSound ? [state.sightingSound] : undefined,
});
const initialValues: SoundUploadValue = { const initialValues: SoundUploadValue = {
name: "", name: "",
soundFile: null, soundFile: null,
soundFileName: "",
soundUrl: "",
uploadedAt: Date.now(),
}; };
const handleSubmit = async (values: SoundUploadValue) => { const handleSubmit = (values: SoundUploadValue) => {
if (!values.soundFile) { if (!values.soundFile) {
toast.warning("Please select an audio file"); toast.warning("Please select an audio file");
return; } else {
}
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 }); dispatch({ type: "ADD", payload: values });
toast.success("Sound file upload successfully");
}
}; };
return ( return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize> <Formik
initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize
>
{({ setFieldValue, errors, setFieldError }) => ( {({ setFieldValue, errors, setFieldError }) => (
<Form> <Form>
<label htmlFor="soundFile" className="">
Sound File
</label>
<FormGroup> <FormGroup>
<label htmlFor="soundFile">Sound File</label>
<input <input
type="file" type="file"
name="soundFile" name="soundFile"
id="sightingSoundinput" id="sightingSoundinput"
accept="audio/mpeg" 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) => { onChange={(e) => {
if (e.target?.files && e.target?.files[0]?.type === "audio/mpeg") { if (
const url = URL.createObjectURL(e.target.files[0]); e.target?.files &&
setFieldValue("soundUrl", url); e.target?.files[0]?.type === "audio/mpeg"
) {
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]);
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 { } else {
setFieldError("soundFile", "Not an mp3 file"); setFieldError("soundFile", "Not an mp3 file");
toast.error("Not an mp3 file"); toast.error("Not an mp3 file");
@@ -84,19 +49,12 @@ const SoundUpload = () => {
}} }}
/> />
</FormGroup> </FormGroup>
{errors.soundFile && (
<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="text-red-500 text-sm mt-1">Not an mp3 file</p>
<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 <button
type="submit" 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 mt-[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"
disabled={errors.soundFile ? true : false} disabled={errors.soundFile ? true : false}
> >
Upload Upload

View File

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

View File

@@ -1,14 +0,0 @@
import Card from "../../UI/Card";
import CardHeader from "../../UI/CardHeader";
import StoreFields from "./StoreFields";
const StoreCard = () => {
return (
<Card className="p-4">
<CardHeader title="Store" />
<StoreFields />
</Card>
);
};
export default StoreCard;

View File

@@ -1,29 +0,0 @@
import { useStoreDispatch } from "../../../hooks/useStoreDispatch";
import VehicleSessionItem from "../../UI/VehicleSessionItem";
const StoreFields = () => {
const { storeQuery } = useStoreDispatch();
const totalPending = storeQuery?.data?.totalPending;
const totalActive = storeQuery?.data?.totalActive;
const totalSent = storeQuery?.data?.totalSent;
const totalReceived = storeQuery?.data?.totalReceived;
const totalLost = storeQuery?.data?.totalLost;
if (storeQuery.isLoading) return <div className="p-4">Loading store data...</div>;
if (storeQuery.error) return <div className="p-4">Error: {storeQuery.error.message}</div>;
return (
<div className="p-4">
<ul className="text-white space-y-3">
<VehicleSessionItem sessionNumber={totalActive} textColour="text-gray-400" vehicleTag={"Total Active:"} />
<VehicleSessionItem sessionNumber={totalSent} textColour="text-blue-400" vehicleTag={"Total Sent:"} />
<VehicleSessionItem sessionNumber={totalReceived} textColour="text-green-400" vehicleTag={"Total Received:"} />
<VehicleSessionItem sessionNumber={totalPending} textColour="text-amber-400" vehicleTag={"Total Pending:"} />
<VehicleSessionItem sessionNumber={totalLost} textColour="text-red-400" vehicleTag={"Total Lost:"} />
</ul>
</div>
);
};
export default StoreFields;

View File

@@ -2,8 +2,6 @@ import { toast } from "sonner";
import type { SystemValues } from "../../../types/types"; import type { SystemValues } from "../../../types/types";
import { CAM_BASE } from "../../../utils/config"; import { CAM_BASE } from "../../../utils/config";
const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : "";
export async function handleSystemSave(values: SystemValues) { export async function handleSystemSave(values: SystemValues) {
const payload = { const payload = {
// Build JSON // Build JSON
@@ -20,7 +18,7 @@ export async function handleSystemSave(values: SystemValues) {
}; };
try { try {
const response = await fetch(`${camBase}/api/update-config`, { const response = await fetch(`${CAM_BASE}/api/update-config`, {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -31,7 +29,11 @@ export async function handleSystemSave(values: SystemValues) {
if (!response.ok) { if (!response.ok) {
const text = await response.text().catch(() => ""); const text = await response.text().catch(() => "");
throw new Error(`HTTP ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`); throw new Error(
`HTTP ${response.status} ${response.statusText}${
text ? ` - ${text}` : ""
}`
);
} }
} catch (err) { } catch (err) {
if (err instanceof Error) { if (err instanceof Error) {
@@ -45,10 +47,10 @@ export async function handleSystemSave(values: SystemValues) {
} }
export async function handleSystemRecall() { export async function handleSystemRecall() {
const url = `${camBase}/api/fetch-config?id=GLOBAL--Device`; const url = `${CAM_BASE}/api/fetch-config?id=GLOBAL--Device`;
const controller = new AbortController(); const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 70000); const timeoutId = setTimeout(() => controller.abort(), 7000);
try { try {
const response = await fetch(url, { const response = await fetch(url, {
@@ -59,7 +61,11 @@ export async function handleSystemRecall() {
if (!response.ok) { if (!response.ok) {
const text = await response.text().catch(() => ""); const text = await response.text().catch(() => "");
throw new Error(`HTTP ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`); throw new Error(
`HTTP ${response.status} ${response.statusText}${
text ? ` - ${text}` : ""
}`
);
} }
const data = await response.json(); const data = await response.json();
@@ -70,7 +76,9 @@ export async function handleSystemRecall() {
const sntpIntervalRaw = data?.propSNTPIntervalMinutes?.value; const sntpIntervalRaw = data?.propSNTPIntervalMinutes?.value;
let sntpInterval = let sntpInterval =
typeof sntpIntervalRaw === "number" ? sntpIntervalRaw : Number.parseInt(String(sntpIntervalRaw).trim(), 10); typeof sntpIntervalRaw === "number"
? sntpIntervalRaw
: Number.parseInt(String(sntpIntervalRaw).trim(), 10);
if (!Number.isFinite(sntpInterval)) { if (!Number.isFinite(sntpInterval)) {
sntpInterval = 60; sntpInterval = 60;

View File

@@ -4,53 +4,37 @@ import { useReboots } from "../../../hooks/useReboots";
import { timezones } from "./timezones"; import { timezones } from "./timezones";
import SystemFileUpload from "./SystemFileUpload"; import SystemFileUpload from "./SystemFileUpload";
import type { SystemValues, SystemValuesErrors } from "../../../types/types"; import type { SystemValues, SystemValuesErrors } from "../../../types/types";
import { useDNSSettings, useSystemConfig } from "../../../hooks/useSystemConfig"; import { useSystemConfig } from "../../../hooks/useSystemConfig";
import { ValidateIPaddress } from "../../../utils/utils";
import { toast } from "sonner";
const SystemConfigFields = () => { const SystemConfigFields = () => {
const { saveSystemSettings, systemSettingsData, saveSystemSettingsLoading } = useSystemConfig(); const { saveSystemSettings, systemSettingsData, saveSystemSettingsLoading } =
const { hardRebootMutation } = useReboots(); useSystemConfig();
const { dnsQuery, dnsMutation } = useDNSSettings(); const { softRebootMutation, hardRebootMutation } = useReboots();
const dnsPrimary = dnsQuery?.data?.propNameServerPrimary?.value;
const dnsSecondary = dnsQuery?.data?.propNameServerSecondary?.value;
const initialvalues: SystemValues = { const initialvalues: SystemValues = {
deviceName: systemSettingsData?.deviceName ?? "", deviceName: systemSettingsData?.deviceName ?? "",
timeZone: systemSettingsData?.timeZone ?? "", timeZone: systemSettingsData?.timeZone ?? "",
sntpServer: systemSettingsData?.sntpServer ?? "", sntpServer: systemSettingsData?.sntpServer ?? "",
sntpInterval: systemSettingsData?.sntpInterval ?? 60, sntpInterval: systemSettingsData?.sntpInterval ?? 60,
serverPrimary: dnsPrimary ?? "",
serverSecondary: dnsSecondary ?? "",
softwareUpdate: null, softwareUpdate: null,
}; };
const handleSubmit = async (values: SystemValues) => { const handleSubmit = (values: SystemValues) => saveSystemSettings(values);
saveSystemSettings(values);
await dnsMutation.mutateAsync(values);
};
const validateValues = (values: SystemValues) => { const validateValues = (values: SystemValues) => {
const errors: SystemValuesErrors = {}; const errors: SystemValuesErrors = {};
const interval = Number(values.sntpInterval); const interval = Number(values.sntpInterval);
if (!values.deviceName) errors.deviceName = "Required"; if (!values.deviceName) errors.deviceName = "Required";
if (!values.timeZone) errors.timeZone = "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"; if (!values.sntpServer) errors.sntpServer = "Required";
const invalidPrimary = ValidateIPaddress(values.serverPrimary);
const invalidSecondary = ValidateIPaddress(values.serverSecondary);
if (invalidPrimary || invalidSecondary) {
toast.error(invalidPrimary || invalidSecondary, {
id: "invalid-ip",
});
}
return errors; return errors;
}; };
// const handleSoftReboot = async () => { const handleSoftReboot = async () => {
// await softRebootMutation.mutate(); await softRebootMutation.mutate();
// }; };
const handleHardReboot = async () => { const handleHardReboot = async () => {
await hardRebootMutation.mutate(); await hardRebootMutation.mutate();
@@ -62,17 +46,22 @@ const SystemConfigFields = () => {
onSubmit={handleSubmit} onSubmit={handleSubmit}
validate={validateValues} validate={validateValues}
enableReinitialize enableReinitialize
validateOnChange={false} validateOnChange
validateOnBlur validateOnBlur
> >
{({ values, errors, touched, isSubmitting }) => ( {({ values, errors, touched, isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2"> <Form className="flex flex-col space-y-5 px-2">
<FormGroup> <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 Device Name
</label> </label>
{touched.deviceName && errors.deviceName && ( {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 <Field
id="deviceName" id="deviceName"
@@ -84,11 +73,16 @@ const SystemConfigFields = () => {
/> />
</FormGroup> </FormGroup>
<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 Local Time Zone
</label> </label>
{touched.timeZone && errors.timeZone && ( {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 <Field
id="timeZone" id="timeZone"
@@ -105,11 +99,16 @@ const SystemConfigFields = () => {
</Field> </Field>
</FormGroup> </FormGroup>
<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 SNTP Server
</label> </label>
{touched.sntpServer && errors.sntpServer && ( {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 <Field
id="sntpServer" id="sntpServer"
@@ -120,13 +119,17 @@ const SystemConfigFields = () => {
autoComplete="off" autoComplete="off"
/> />
</FormGroup> </FormGroup>
<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 SNTP Interval minutes
</label> </label>
{touched.sntpInterval && errors.sntpInterval && ( {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 <Field
id="sntpInterval" id="sntpInterval"
@@ -137,59 +140,38 @@ const SystemConfigFields = () => {
className="p-2 border border-gray-400 rounded-lg w-full max-w-xs" className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
/> />
</FormGroup> </FormGroup>
<FormGroup>
<label htmlFor="serverPrimary" className="font-medium whitespace-nowrap md:w-1/2 text-left">
Primary DNS Server
</label>
<Field
id="serverPrimary"
name="serverPrimary"
type="text"
className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
placeholder="Enter DNS primary address"
autoComplete="off"
/>
</FormGroup>
<FormGroup>
<label htmlFor="serverSecondary" className="font-medium whitespace-nowrap md:w-1/2 text-left">
Secondary DNS Server
</label>
<Field
id="serverSecondary"
name="serverSecondary"
type="text"
className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
placeholder="Enter DNS secondary address"
autoComplete="off"
/>
</FormGroup>
<button <button
type="submit" 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="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full md:w-[50%]"
disabled={isSubmitting} disabled={isSubmitting}
> >
{saveSystemSettingsLoading ? "Saving..." : "Save System Settings"} {saveSystemSettingsLoading ? "Saving..." : "Save System Settings"}
</button> </button>
<SystemFileUpload name={"softwareUpdate"} selectedFile={values.softwareUpdate} /> <SystemFileUpload
name={"softwareUpdate"}
selectedFile={values.softwareUpdate}
/>
<div className="border-b border-gray-600"> <div className="border-b border-gray-600">
<p>Reboot</p> <p>Reboot</p>
</div> </div>
{/* <button <button
type="button" type="button"
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full md:w-[50%]" className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full md:w-[50%]"
onClick={handleSoftReboot} onClick={handleSoftReboot}
> >
{softRebootMutation.isPending || isSubmitting ? "Rebooting..." : "Software Reboot"} {softRebootMutation.isPending || isSubmitting
</button> */} ? "Rebooting..."
: "Software Reboot"}
</button>
<button <button
type="button" type="button"
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full md:w-[50%]" className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full md:w-[50%]"
onClick={handleHardReboot} onClick={handleHardReboot}
> >
{hardRebootMutation.isPending || isSubmitting ? "Rebooting" : "Hardware Reboot"} {hardRebootMutation.isPending || isSubmitting
? "Rebooting"
: "Hardware Reboot"}
</button> </button>
</Form> </Form>
)} )}

View File

@@ -36,7 +36,7 @@ const SystemFileUpload = ({ name, selectedFile }: SystemFileUploadProps) => {
type="file" type="file"
name="softwareUpdate" name="softwareUpdate"
id="softwareUpdate" id="softwareUpdate"
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="file:px-10 file:border file:border-gray-500 file:rounded-lg file:bg-blue-800 file:mr-5 w-full max-w-xs"
onChange={(event) => { onChange={(event) => {
const file = event.currentTarget.files?.[0]; const file = event.currentTarget.files?.[0];
if (!file) { if (!file) {
@@ -44,7 +44,8 @@ const SystemFileUpload = ({ name, selectedFile }: SystemFileUploadProps) => {
return; 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); setFieldValue(name, file);
}} }}
/> />
@@ -52,7 +53,7 @@ const SystemFileUpload = ({ name, selectedFile }: SystemFileUploadProps) => {
</FormGroup> </FormGroup>
<button <button
type="button" type="button"
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" 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"
disabled={!selectedFile} disabled={!selectedFile}
onClick={handleFileUploadClick} onClick={handleFileUploadClick}
> >

View File

@@ -10,10 +10,16 @@ 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 (!file) throw new Error("No file supplied");
if (!opts?.uploadUrl) throw new Error("No URL supplied"); if (!opts?.uploadUrl) throw new Error("No URL supplied");
if (file?.type !== "text/csv") {
throw new Error("This file is not supported, please upload a CSV file.");
}
const timeoutMs = opts?.timeoutMs ?? 30000; const timeoutMs = opts?.timeoutMs ?? 30000;
const fieldName = opts?.fieldName ?? "upload"; const fieldName = opts?.fieldName ?? "upload";
const fileName = opts?.overrideFileName ?? file?.name; const fileName = opts?.overrideFileName ?? file?.name;
@@ -36,7 +42,9 @@ export async function sendBlobFileUpload({ file, opts }: BlobFileUpload): Promis
const bodyText = await resp.text(); const bodyText = await resp.text();
if (!resp.ok) { 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; return bodyText;
@@ -46,7 +54,9 @@ export async function sendBlobFileUpload({ file, opts }: BlobFileUpload): Promis
} }
// In browsers, fetch throws TypeError on network-level failures // In browsers, fetch throws TypeError on network-level failures
if (err instanceof TypeError) { 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 // Todo: fix error message response
return `Hotlist Load OK`; return `Hotlist Load OK`;

View File

@@ -6,6 +6,7 @@ const ModemCard = () => {
return ( return (
<Card className="p-4"> <Card className="p-4">
<CardHeader title={"Modem"} /> <CardHeader title={"Modem"} />
<ModemSettings /> <ModemSettings />
</Card> </Card>
); );

View File

@@ -6,8 +6,6 @@ import { useEffect, useState } from "react";
import ModemToggle from "./ModemToggle"; import ModemToggle from "./ModemToggle";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons"; import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { ValidateIPaddress } from "../../../utils/utils";
import { toast, Toaster } from "sonner";
const ModemSettings = () => { const ModemSettings = () => {
const [showSettings, setShowSettings] = useState(false); const [showSettings, setShowSettings] = useState(false);
@@ -18,8 +16,6 @@ const ModemSettings = () => {
const username = modemQuery?.data?.propUsername.value; const username = modemQuery?.data?.propUsername.value;
const password = modemQuery?.data?.propPassword?.value; const password = modemQuery?.data?.propPassword?.value;
const mode = modemQuery?.data?.propMode?.value; const mode = modemQuery?.data?.propMode?.value;
const serverPrimary = modemQuery?.data?.propNameServerPrimary?.value;
const serverSecondary = modemQuery?.data?.propNameServerSecondary?.value;
useEffect(() => { useEffect(() => {
setShowSettings(mode === "AUTO"); setShowSettings(mode === "AUTO");
@@ -30,19 +26,9 @@ const ModemSettings = () => {
username: username ?? "", username: username ?? "",
password: password ?? "", password: password ?? "",
authenticationType: "PAP", authenticationType: "PAP",
serverPrimary: serverPrimary ?? "",
serverSecondary: serverSecondary ?? "",
}; };
const handleSubmit = async (values: ModemSettingsType) => { const handleSubmit = async (values: ModemSettingsType) => {
const invalidPrimary = ValidateIPaddress(values.serverPrimary);
const invalidSecondary = ValidateIPaddress(values.serverSecondary);
if (invalidPrimary || invalidSecondary) {
toast.error(invalidPrimary || invalidSecondary, {
id: "invalid-ip",
});
return;
}
const modemConfig = { const modemConfig = {
id: "ModemAndWifiManager-modem", id: "ModemAndWifiManager-modem",
fields: [ fields: [
@@ -63,37 +49,30 @@ const ModemSettings = () => {
property: "propMode", property: "propMode",
value: showSettings ? "AUTO" : "MANUAL", value: showSettings ? "AUTO" : "MANUAL",
}, },
{
property: "propNameServerPrimary",
value: values.serverPrimary,
},
{
property: "propNameServerSecondary",
value: values.serverSecondary,
},
], ],
}; };
await modemMutation.mutateAsync(modemConfig);
const response = await modemMutation.mutateAsync(modemConfig);
if (!response?.id) {
toast.success("Modem settings updated successfully", {
id: "modemSettings",
});
}
}; };
return ( return (
<> <>
<ModemToggle showSettings={showSettings} onShowSettings={setShowSettings} /> <ModemToggle
showSettings={showSettings}
<Formik initialValues={inititalValues} onSubmit={handleSubmit} enableReinitialize> onShowSettings={setShowSettings}
/>
{!showSettings && (
<Formik
initialValues={inititalValues}
onSubmit={handleSubmit}
enableReinitialize
>
{({ isSubmitting }) => ( {({ isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2"> <Form className="flex flex-col space-y-5 px-2">
{!showSettings && (
<>
<FormGroup> <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 APN
</label> </label>
<Field <Field
@@ -105,7 +84,10 @@ const ModemSettings = () => {
/> />
</FormGroup> </FormGroup>
<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 Username
</label> </label>
<Field <Field
@@ -117,7 +99,10 @@ const ModemSettings = () => {
/> />
</FormGroup> </FormGroup>
<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 Password
</label> </label>
<div className="flex gap-2 items-center relative mb-4"> <div className="flex gap-2 items-center relative mb-4">
@@ -137,32 +122,11 @@ const ModemSettings = () => {
</div> </div>
</FormGroup> </FormGroup>
<FormGroup> <FormGroup>
<label htmlFor="serverPrimary" className="font-medium whitespace-nowrap md:w-2/3"> <label
Name server primary htmlFor="password"
</label> className="font-medium whitespace-nowrap md:w-2/3"
<Field >
placeholder="Enter Server primary" Password
name="serverPrimary"
id="serverPrimary"
type="text"
className="p-1.5 border border-gray-400 rounded-lg"
/>
</FormGroup>
<FormGroup>
<label htmlFor="serverSecondary" className="font-medium whitespace-nowrap md:w-2/3">
Name server secondary
</label>
<Field
placeholder="Enter Server secondary"
name="serverSecondary"
id="serverSecondary"
type="text"
className="p-1.5 border border-gray-400 rounded-lg"
/>
</FormGroup>
<FormGroup>
<label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">
Authentication Type
</label> </label>
<Field <Field
name="authenticationType" name="authenticationType"
@@ -174,18 +138,18 @@ const ModemSettings = () => {
<option value="none">None</option> <option value="none">None</option>
</Field> </Field>
</FormGroup> </FormGroup>
</>
)}
<button <button
type="submit" 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="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full md:w-[50%]"
> >
{isSubmitting || modemMutation.isPending ? "Saving..." : "Save Modem settings"} {isSubmitting || modemMutation.isPending
? "Saving..."
: "Save Modem settings"}
</button> </button>
</Form> </Form>
)} )}
</Formik> </Formik>
<Toaster /> )}
</> </>
); );
}; };

View File

@@ -5,7 +5,6 @@ import { useWifiAndModem } from "../../../hooks/useCameraWifiandModem";
import { useState } from "react"; import { useState } from "react";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons"; import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { toast, Toaster } from "sonner";
const WiFiSettingsForm = () => { const WiFiSettingsForm = () => {
const [showPwd, setShowPwd] = useState(false); const [showPwd, setShowPwd] = useState(false);
@@ -20,13 +19,6 @@ const WiFiSettingsForm = () => {
encryption: "WPA2", encryption: "WPA2",
}; };
const validatePassword = (password: string) => {
if (password.length < 8) {
toast.error("Password must be at least 8 characters long", { id: "password" });
return "Password must be at least 8 characters long";
}
};
const handleSubmit = async (values: WifiSettingValues) => { const handleSubmit = async (values: WifiSettingValues) => {
const wifiConfig = { const wifiConfig = {
id: "ModemAndWifiManager-wifi", id: "ModemAndWifiManager-wifi",
@@ -45,12 +37,18 @@ const WiFiSettingsForm = () => {
await wifiMutation.mutateAsync(wifiConfig); await wifiMutation.mutateAsync(wifiConfig);
}; };
return ( return (
<> <Formik
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize> initialValues={initialValues}
onSubmit={handleSubmit}
enableReinitialize
>
{({ isSubmitting }) => ( {({ isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2"> <Form className="flex flex-col space-y-5 px-2">
<FormGroup> <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 SSID
</label> </label>
<Field <Field
@@ -62,7 +60,10 @@ const WiFiSettingsForm = () => {
/> />
</FormGroup> </FormGroup>
<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 Password
</label> </label>
<div className="flex gap-2 items-center relative mb-4"> <div className="flex gap-2 items-center relative mb-4">
@@ -72,9 +73,7 @@ const WiFiSettingsForm = () => {
type={showPwd ? "text" : "password"} type={showPwd ? "text" : "password"}
className="p-2 border border-gray-400 rounded-lg w-full" className="p-2 border border-gray-400 rounded-lg w-full"
placeholder="Enter Password" placeholder="Enter Password"
validate={validatePassword}
/> />
<FontAwesomeIcon <FontAwesomeIcon
type="button" type="button"
className="absolute right-5 end-0" className="absolute right-5 end-0"
@@ -84,7 +83,10 @@ const WiFiSettingsForm = () => {
</div> </div>
</FormGroup> </FormGroup>
<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 WPA/Encryption Type
</label> </label>
<Field <Field
@@ -101,15 +103,15 @@ const WiFiSettingsForm = () => {
</FormGroup> </FormGroup>
<button <button
type="submit" 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="bg-[#26B170] text-white px-4 py-2 rounded hover:bg-green-700 transition w-full md:w-[50%]"
> >
{isSubmitting || wifiMutation.isPending ? "Saving..." : " Save WiFi settings"} {isSubmitting || wifiMutation.isPending
? "Saving..."
: " Save WiFi settings"}
</button> </button>
</Form> </Form>
)} )}
</Formik> </Formik>
<Toaster />
</>
); );
}; };

View File

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

View File

@@ -23,7 +23,8 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
const { dispatch } = useAlertHitContext(); const { dispatch } = useAlertHitContext();
const { query, mutation } = useCameraBlackboard(); const { query, mutation } = useCameraBlackboard();
const hotlistNames = getHotlistName(sighting?.metadata?.hotlistMatches); const hotlistName = getHotlistName(sighting?.metadata?.hotlistMatches);
const handleAcknowledgeButton = () => { const handleAcknowledgeButton = () => {
try { try {
if (!sighting) { if (!sighting) {
@@ -108,7 +109,7 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
onClick={handleAcknowledgeButton} onClick={handleAcknowledgeButton}
> >
<FontAwesomeIcon icon={faCheck} /> <FontAwesomeIcon icon={faCheck} />
Acknowledge Accept
</button> </button>
)} )}
</div> </div>
@@ -116,6 +117,16 @@ 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] : "-"}
</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" />}
@@ -123,20 +134,6 @@ 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, 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"> <div className="flex flex-col lg:flex-row items-center gap-3">
<img <img
src={sighting?.overviewUrl} src={sighting?.overviewUrl}
@@ -160,28 +157,18 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
<dd className="font-medium text-2xl">{sighting?.seenCount ?? "-"}</dd> <dd className="font-medium text-2xl">{sighting?.seenCount ?? "-"}</dd>
</div> </div>
{sighting?.make ||
(sighting?.make.trim() && (
<div> <div>
<dt className="text-gray-300">Make</dt> <dt className="text-gray-300">Make</dt>
<dd className="font-medium text-2xl">{sighting?.make ?? "-"}</dd> <dd className="font-medium text-2xl">{sighting?.make ?? "-"}</dd>
</div> </div>
))}
{sighting?.model ||
(!sighting?.model.trim() && (
<div> <div>
<dt className="text-gray-300">Model</dt> <dt className="text-gray-300">Model</dt>
<dd className="font-medium text-2xl">{sighting?.model ?? "-"}</dd> <dd className="font-medium text-2xl">{sighting?.model ?? "-"}</dd>
</div> </div>
))}
{sighting?.color ||
(!sighting?.color.trim() && (
<div className="sm:col-span-2"> <div className="sm:col-span-2">
<dt className="text-gray-300">Colour</dt> <dt className="text-gray-300">Colour</dt>
<dd className="font-medium text-2xl">{sighting?.color ?? "-"}</dd> <dd className="font-medium text-2xl">{sighting?.color ?? "-"}</dd>
</div> </div>
))}
<div> <div>
<dt className="text-gray-300">Time</dt> <dt className="text-gray-300">Time</dt>
<dd className="font-medium text-xl">{sighting?.timeStamp ?? "-"}</dd> <dd className="font-medium text-xl">{sighting?.timeStamp ?? "-"}</dd>
@@ -205,7 +192,7 @@ const SightingModal = ({ isSightingModalOpen, handleClose, sighting, onDelete }:
onClick={handleAcknowledgeButton} onClick={handleAcknowledgeButton}
> >
<FontAwesomeIcon icon={faCheck} /> <FontAwesomeIcon icon={faCheck} />
Acknowledge Accept
</button> </button>
)} )}
{onDelete ? ( {onDelete ? (

View File

@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { HitKind, QueuedHit, ReducedSightingType, SightingType } from "../../types/types"; import type { ReducedSightingType, SightingType } from "../../types/types";
import { BLANK_IMG } 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";
import CardHeader from "../UI/CardHeader"; import CardHeader from "../UI/CardHeader";
@@ -15,11 +15,10 @@ import NPED_CAT_C from "/NPED_Cat_C.svg";
import popup from "../../assets/sounds/ui/popup_open.mp3"; import popup from "../../assets/sounds/ui/popup_open.mp3";
import notification from "../../assets/sounds/ui/notification.mp3"; import notification from "../../assets/sounds/ui/notification.mp3";
import { useSound } from "react-sounds"; import { useSound } from "react-sounds";
import { useIntegrationsContext } from "../../context/IntegrationsContext"; import { useNPEDContext } from "../../context/NPEDUserContext";
import { useSoundContext } from "../../context/SoundContext"; import { useSoundContext } from "../../context/SoundContext";
import Loading from "../UI/Loading"; import Loading from "../UI/Loading";
import { checkIsHotListHit, getNPEDCategory } from "../../utils/utils"; import { checkIsHotListHit, getNPEDCategory } from "../../utils/utils";
import { useCachedSoundSrc } from "../../hooks/usecachedSoundSrc";
function useNow(tickMs = 1000) { function useNow(tickMs = 1000) {
const [, setNow] = useState(() => Date.now()); const [, setNow] = useState(() => Date.now());
@@ -39,16 +38,23 @@ type SightingHistoryProps = {
className?: string; className?: string;
}; };
export default function SightingHistoryWidget({ className, title }: SightingHistoryProps) { export default function SightingHistoryWidget({
const [modalQueue, setModalQueue] = useState<QueuedHit[]>([]); className,
title,
}: SightingHistoryProps) {
useNow(1000); useNow(1000);
const { state } = useSoundContext(); const { state } = useSoundContext();
const { src: soundSrcHotlist } = useCachedSoundSrc(state?.hotlistSound, state?.soundOptions, notification); const soundSrcNped = useMemo(() => {
const { src: soundSrcNped } = useCachedSoundSrc(state?.NPEDsound, state?.soundOptions, popup); return getSoundFileURL(state.NPEDsound) ?? popup;
}, [state.NPEDsound]);
const { play: npedSound } = useSound(soundSrcNped, { volume: state.NPEDsoundVolume }); const soundSrcHotlist = useMemo(() => {
const { play: hotlistsound } = useSound(soundSrcHotlist, { volume: state.hotlistSoundVolume }); return getSoundFileURL(state?.hotlists?.[0]?.sound) ?? notification;
}, [state.hotlists]);
const { play: npedSound } = useSound(soundSrcNped);
const { play: hotlistsound } = useSound(soundSrcHotlist);
const { const {
sightings, sightings,
setSelectedSighting, setSelectedSighting,
@@ -59,28 +65,14 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
isLoading, isLoading,
} = useSightingFeedContext(); } = useSightingFeedContext();
const { dispatch, state: alertState } = useAlertHitContext(); const { dispatch } = useAlertHitContext();
const { state: integrationState, dispatch: integrationDispatch } = useIntegrationsContext(); const { sessionStarted, setSessionList, sessionList } = useNPEDContext();
const sessionStarted = integrationState.sessionStarted;
const sessionPaused = integrationState.sessionPaused;
const processedRefs = useRef<Set<number | string>>(new Set()); const processedRefs = useRef<Set<number | string>>(new Set());
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;
const inList = alertState?.alertList?.find((sighting) => sighting.vrm === id);
if (inList) {
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,
@@ -91,12 +83,11 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
useEffect(() => { useEffect(() => {
if (sessionStarted) { if (sessionStarted) {
if (!mostRecent) return; if (!mostRecent) return;
if (sessionPaused) return;
const reducedMostRecent = reduceObject(mostRecent); const reducedMostRecent = reduceObject(mostRecent);
integrationDispatch({ type: "ADD", payload: reducedMostRecent }); setSessionList([...sessionList, reducedMostRecent]);
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [mostRecent, sessionStarted]); }, [mostRecent, sessionStarted, setSessionList]);
const onRowClick = useCallback( const onRowClick = useCallback(
(sighting: SightingType) => { (sighting: SightingType) => {
@@ -107,7 +98,10 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
[setSelectedSighting, setSightingModalOpen] [setSelectedSighting, setSightingModalOpen]
); );
const rows = useMemo(() => sightings?.filter(Boolean) as SightingType[], [sightings]); const rows = useMemo(
() => sightings?.filter(Boolean) as SightingType[],
[sightings]
);
useEffect(() => { useEffect(() => {
if (!rows?.length) return; if (!rows?.length) return;
@@ -116,15 +110,32 @@ 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 isHotlistHit = checkIsHotListHit(sighting); const isHot = checkIsHotListHit(sighting);
const npedcategory = sighting?.metadata?.npedJSON?.["NPED CATEGORY"]; const cat = sighting?.metadata?.npedJSON?.["NPED CATEGORY"];
const isNPED = npedcategory === "A" || npedcategory === "B" || npedcategory === "C";
if (isNPED || isHotlistHit) { if (cat === "A" || cat === "B" || cat === "C") {
enqueue(sighting, isNPED ? "NPED" : "HOTLIST"); // enqueue ONLY 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;
} }
} }
}, [rows, enqueue]); }, [
rows,
hotlistsound,
npedSound,
setSightingModalOpen,
setSelectedSighting,
]);
useEffect(() => { useEffect(() => {
rows?.forEach((obj) => { rows?.forEach((obj) => {
@@ -157,37 +168,31 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
}); });
if (firstNPED) { if (firstNPED) {
enqueue(firstNPED, "NPED"); setSelectedSighting(firstNPED);
npedSound();
setSightingModalOpen(true);
npedRef.current = true; npedRef.current = true;
} }
if (firstHot) { if (firstHot) {
enqueue(firstHot, "HOTLIST"); setSelectedSighting(firstHot);
hotlistsound();
setSightingModalOpen(true);
hasAutoOpenedRef.current = true; hasAutoOpenedRef.current = true;
} }
}, [enqueue, hotlistsound, npedSound, rows, setSelectedSighting, setSightingModalOpen]); }, [hotlistsound, npedSound, setSelectedSighting]);
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 (
<> <>
<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} /> <CardHeader title={title} />
<div className="flex flex-col gap-3 "> <div className="flex flex-col gap-3 ">
{isLoading && ( {isLoading && (
@@ -210,16 +215,45 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
className={`border border-gray-700 rounded-md mb-2 p-2 cursor-pointer `} className={`border border-gray-700 rounded-md mb-2 p-2 cursor-pointer `}
onClick={() => onRowClick(obj)} 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 `}> <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> </div>
{isHotListHit && ( {isHotListHit && (
<img src={HotListImg} 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"
/>
)} )}
{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} /> <NumberPlate motion={motionAway} vrm={obj?.vrm} />
</div> </div>
</div> </div>
@@ -228,7 +262,11 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
</div> </div>
</div> </div>
</Card> </Card>
<SightingModal isSightingModalOpen={isSightingModalOpen} handleClose={handleClose} sighting={selectedSighting} /> <SightingModal
isSightingModalOpen={isSightingModalOpen}
handleClose={handleClose}
sighting={selectedSighting}
/>
</> </>
); );
} }

View File

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

View File

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

View File

@@ -7,12 +7,16 @@ type ModalComponentProps = {
close: () => void; close: () => void;
}; };
const ModalComponent = ({ isModalOpen, children, close }: ModalComponentProps) => { const ModalComponent = ({
isModalOpen,
children,
close,
}: ModalComponentProps) => {
return ( return (
<Modal <Modal
isOpen={isModalOpen} isOpen={isModalOpen}
onRequestClose={close} onRequestClose={close}
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" 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"
overlayClassName="fixed inset-0 bg-[#1e2a38]/70 flex justify-center items-start z-100" overlayClassName="fixed inset-0 bg-[#1e2a38]/70 flex justify-center items-start z-100"
> >
{children} {children}

View File

@@ -11,15 +11,16 @@ const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => {
const navigate = useNavigate(); const navigate = useNavigate();
const navigationDest = (side: string | undefined) => { const navigationDest = (side: string | undefined) => {
console.log(side);
if (settingsPage) { if (settingsPage) {
navigate("/"); navigate("/");
return; return;
} }
if (side === "Front") { if (side === "Front") {
navigate("/a-camera-settings"); navigate("/camera-settings");
} else if (side === "Rear") { } else if (side === "Rear") {
navigate("/b-Camera-settings"); navigate("/Rear-Camera-settings");
} }
}; };
@@ -30,15 +31,15 @@ const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => {
<FontAwesomeIcon <FontAwesomeIcon
size="2xl" size="2xl"
icon={faArrowRight} icon={faArrowRight}
className="absolute top-[50%] right-[2%] backdrop-blur-lg hover:cursor-pointer animate-bounce z-30 rounded-md arrow-outline" className="absolute top-[50%] right-[2%] backdrop-blur-lg hover:cursor-pointer animate-bounce z-30"
onClick={() => navigationDest("a")} onClick={() => navigationDest("Front")}
/> />
) : ( ) : (
<FontAwesomeIcon <FontAwesomeIcon
icon={faArrowLeft} icon={faArrowLeft}
size="2xl" size="2xl"
className="absolute top-[50%] left-[2%] backdrop-blur-md hover:cursor-pointer animate-bounce z-30 rounded-md arrow-outline" className="absolute top-[50%] left-[2%] backdrop-blur-md hover:cursor-pointer animate-bounce z-30"
onClick={() => navigationDest("b")} onClick={() => navigationDest(side)}
/> />
)} )}
</> </>
@@ -49,14 +50,14 @@ const NavigationArrow = ({ side, settingsPage }: NavigationArrowProps) => {
<FontAwesomeIcon <FontAwesomeIcon
icon={faArrowLeft} icon={faArrowLeft}
size="2xl" size="2xl"
className="absolute top-[50%] left-[2%] backdrop-blur-md hover:cursor-pointer animate-bounce z-100 arrow-outline rounded-md" className="absolute top-[50%] left-[2%] backdrop-blur-md hover:cursor-pointer animate-bounce z-100 "
onClick={() => navigationDest("Front")} onClick={() => navigationDest("Front")}
/> />
<FontAwesomeIcon <FontAwesomeIcon
icon={faArrowRight} icon={faArrowRight}
size="2xl" size="2xl"
className="absolute top-[50%] right-[2%] backdrop-blur-md hover:cursor-pointer animate-bounce z-100 arrow-outline rounded-md" className="absolute top-[50%] right-[2%] backdrop-blur-md hover:cursor-pointer animate-bounce z-100"
onClick={() => navigationDest("Rear")} onClick={() => navigationDest("Rear")}
/> />
</> </>

View File

@@ -1,60 +0,0 @@
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

@@ -1,18 +0,0 @@
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

@@ -1,14 +0,0 @@
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

@@ -0,0 +1,21 @@
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,10 +7,13 @@ type SoundContextType = {
audioArmed: boolean; audioArmed: boolean;
}; };
export const SoundContext = createContext<SoundContextType | undefined>(undefined); export const SoundContext = createContext<SoundContextType | undefined>(
undefined
);
export const useSoundContext = () => { export const useSoundContext = () => {
const ctx = useContext(SoundContext); 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; return ctx;
}; };

View File

@@ -1,36 +0,0 @@
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

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

View File

@@ -1,46 +0,0 @@
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,22 +3,12 @@ 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)", soundFileName: "switch" }, { name: "switch (Default)", soundFile: null },
{ name: "Popup", soundFileName: "popup" }, { name: "popup", soundFile: null },
{ name: "Notification", soundFileName: "notification" }, { name: "notification", soundFile: null },
{ 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 { export function reducer(state: SoundState, action: SoundAction): SoundState {
@@ -28,15 +18,10 @@ 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,
sightingVolume: action.payload.sightingVolume,
hotlistSoundVolume: action.payload.hotlistSoundVolume,
soundOptions: action.payload.soundOptions,
}; };
} }
@@ -46,29 +31,7 @@ export function reducer(state: SoundState, action: SoundAction): SoundState {
soundOptions: [...(state.soundOptions ?? []), action.payload], 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: default:
return state; return state;
} }

View File

@@ -1,75 +0,0 @@
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`, {
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

@@ -8,7 +8,7 @@ const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : "";
const getAllBlackboardData = async () => { const getAllBlackboardData = async () => {
const response = await fetch(`${camBase}/api/blackboard`, { const response = await fetch(`${camBase}/api/blackboard`, {
signal: AbortSignal.timeout(300000), signal: AbortSignal.timeout(500),
}); });
if (!response.ok) { if (!response.ok) {
throw new Error("Failed to fetch blackboard data"); throw new Error("Failed to fetch blackboard data");
@@ -17,7 +17,7 @@ const getAllBlackboardData = async () => {
}; };
const viewBlackboardData = async (options: CameraBlackBoardOptions) => { const viewBlackboardData = async (options: CameraBlackBoardOptions) => {
const response = await fetch(`${camBase}/api/blackboard`, { const response = await fetch(`/${camBase}api/blackboard`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(options), body: JSON.stringify(options),

View File

@@ -8,7 +8,7 @@ const fetchCameraSideConfig = async ({ queryKey }: { queryKey: string[] }) => {
const [, cameraSide] = queryKey; const [, cameraSide] = queryKey;
const fetchUrl = `${base_url}/fetch-config?id=${cameraSide}`; const fetchUrl = `${base_url}/fetch-config?id=${cameraSide}`;
const response = await fetch(fetchUrl, { const response = await fetch(fetchUrl, {
signal: AbortSignal.timeout(300000), signal: AbortSignal.timeout(500),
}); });
if (!response.ok) throw new Error("cannot react cameraSide "); if (!response.ok) throw new Error("cannot react cameraSide ");
return response.json(); return response.json();
@@ -31,7 +31,7 @@ const updateCamerasideConfig = async (data: { id: string | number; friendlyName:
method: "POST", method: "POST",
body: JSON.stringify(updateConfigPayload), body: JSON.stringify(updateConfigPayload),
}); });
if (!response.ok) throw new Error("Please make sure fields are filled in correctly"); if (!response.ok) throw new Error("Feature unavailable: Coming soon");
}; };
export const useFetchCameraConfig = (cameraSide: string) => { export const useFetchCameraConfig = (cameraSide: string) => {

View File

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

View File

@@ -3,11 +3,10 @@ import { CAM_BASE } from "../utils/config";
import type { ModemConfig, WifiConfig } from "../types/types"; import type { ModemConfig, WifiConfig } from "../types/types";
import { useEffect } from "react"; import { useEffect } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : "";
const getWiFiSettings = async () => { const getWiFiSettings = async () => {
const response = await fetch(`${camBase}/api/fetch-config?id=ModemAndWifiManager-wifi`, { const response = await fetch(`${CAM_BASE}/api/fetch-config?id=ModemAndWifiManager-wifi`, {
signal: AbortSignal.timeout(600000), signal: AbortSignal.timeout(500),
}); });
if (!response.ok) { if (!response.ok) {
throw new Error("Cannot fetch Wifi settings"); throw new Error("Cannot fetch Wifi settings");
@@ -16,7 +15,7 @@ const getWiFiSettings = async () => {
}; };
const updateWifiSettings = async (wifiConfig: WifiConfig) => { const updateWifiSettings = async (wifiConfig: WifiConfig) => {
const response = await fetch(`${camBase}/api/update-config`, { const response = await fetch(`${CAM_BASE}/api/update-config?id=ModemAndWifiManager-wifi`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(wifiConfig), body: JSON.stringify(wifiConfig),
@@ -28,8 +27,8 @@ const updateWifiSettings = async (wifiConfig: WifiConfig) => {
}; };
const getModemSettings = async () => { const getModemSettings = async () => {
const response = await fetch(`${camBase}/api/fetch-config?id=ModemAndWifiManager-modem`, { const response = await fetch(`${CAM_BASE}/api/fetch-config?id=ModemAndWifiManager-modem`, {
signal: AbortSignal.timeout(600000), signal: AbortSignal.timeout(500),
}); });
if (!response.ok) { if (!response.ok) {
throw new Error("Cannot fetch modem settings"); throw new Error("Cannot fetch modem settings");
@@ -38,7 +37,7 @@ const getModemSettings = async () => {
}; };
const updateModemSettings = async (modemConfig: ModemConfig) => { const updateModemSettings = async (modemConfig: ModemConfig) => {
const response = await fetch(`${camBase}/api/update-config`, { const response = await fetch(`${CAM_BASE}/api/update-config?id=ModemAndWifiManager-modem`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(modemConfig), body: JSON.stringify(modemConfig),

View File

@@ -1,38 +1,18 @@
import { useMutation, useQuery, type QueryFunctionContext } from "@tanstack/react-query"; import {
useMutation,
useQuery,
type QueryFunctionContext,
} from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config"; import { CAM_BASE } from "../utils/config";
import type { zoomConfig, ZoomInOptions } from "../types/types"; import type { zoomConfig, ZoomInOptions } from "../types/types";
import { toast } from "sonner"; import { toast } from "sonner";
import { useEffect } from "react"; import { useEffect } from "react";
const getCameraMode = async (options: { camera: string }) => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Ip${options.camera}`);
if (!response.ok) throw new Error("Cannot get camera mode");
return response.json();
};
const updateCameraMode = async (options: { camera: string; mode: string }) => {
const dayNightPayload = {
id: options.camera,
fields: [
{
property: "propDayNightMode",
value: options.mode,
},
],
};
const response = await fetch(`${CAM_BASE}/Ip${options.camera}-command?dayNightMode=${options.mode}`, {
method: "post",
body: JSON.stringify(dayNightPayload),
});
if (!response.ok) throw new Error("cannot update camera mode");
return response.json();
};
async function zoomIn(options: ZoomInOptions) { async function zoomIn(options: ZoomInOptions) {
const response = await fetch( const response = await fetch(
`${CAM_BASE}/Ip${options.camera}-command?magnification=${options.multiplierText?.toLowerCase()}`, `${CAM_BASE}/Ip${options.camera}-command?magnification=${options.multiplier}x`,
{ {
signal: AbortSignal.timeout(300000), signal: AbortSignal.timeout(500),
} }
); );
if (!response.ok) { if (!response.ok) {
@@ -42,21 +22,28 @@ async function zoomIn(options: ZoomInOptions) {
return response.json(); return response.json();
} }
async function fetchZoomInConfig({ queryKey }: QueryFunctionContext<[string, zoomConfig]>) { async function fetchZoomInConfig({
queryKey,
}: QueryFunctionContext<[string, zoomConfig]>) {
const [, { camera }] = queryKey; const [, { camera }] = queryKey;
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Ip${camera}`, { const response = await fetch(`${CAM_BASE}/Ip${camera}-inspect`, {
signal: AbortSignal.timeout(300000), signal: AbortSignal.timeout(500),
}); });
if (!response.ok) { if (!response.ok) {
throw new Error("Cannot get camera zoom settings"); throw new Error("Cannot get camera zoom settings");
} }
return response.json(); return response.text();
} }
//change to string //change to string
export const useCameraZoom = (options: zoomConfig) => { export const useCameraZoom = (options: zoomConfig) => {
const mutation = useMutation({ const mutation = useMutation({
mutationKey: ["zoomIn"], mutationKey: ["zoomIn"],
mutationFn: (options: ZoomInOptions) => zoomIn(options), mutationFn: (options: ZoomInOptions) => zoomIn(options),
onError: (err) => {
toast.error(`Failed to update zoom settings: ${err.message}`, {
id: "zoom",
});
},
}); });
const query = useQuery({ const query = useQuery({
@@ -65,25 +52,8 @@ export const useCameraZoom = (options: zoomConfig) => {
}); });
useEffect(() => { useEffect(() => {
if (query.isError) toast.error(query.error.message, { id: "zoom" }); if (query.isError) toast.error(query.error.message, { id: "hardReboot" });
}, [query?.error?.message, query.isError]); }, [query?.error?.message, query.isError]);
return { mutation, query }; return { mutation, query };
}; };
export const useCameraMode = (option: { camera: string }) => {
const cameraModeQuery = useQuery({
queryKey: ["getCameraMode"],
queryFn: () => getCameraMode(option),
});
const cameraModeMutation = useMutation({
mutationKey: ["updateCameraMode"],
mutationFn: updateCameraMode,
});
return {
cameraModeQuery,
cameraModeMutation,
};
};

View File

@@ -1,45 +0,0 @@
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

@@ -1,46 +0,0 @@
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,153 +0,0 @@
import { useRef, useCallback, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
const apiUrl = CAM_BASE;
async function fetchSnapshot(cameraSide: string): Promise<Blob> {
const response = await fetch(`${apiUrl}/${cameraSide}-preview`, {
signal: AbortSignal.timeout(300000),
cache: "no-store",
});
if (!response.ok) {
throw new Error(`Cannot reach endpoint (${response.status})`);
}
return response.blob();
}
/** Draw an ImageBitmap to canvas with aspect-fill (like object-fit: cover) */
function drawBitmapToCanvas(canvas: HTMLCanvasElement, bitmap: ImageBitmap) {
const ctx = canvas.getContext("2d");
if (!ctx) return;
const dpr = window.devicePixelRatio || 1;
const cssWidth = canvas.clientWidth;
const cssHeight = canvas.clientHeight;
const width = Math.floor(cssWidth * dpr);
const height = Math.floor(cssHeight * dpr);
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
ctx.clearRect(0, 0, width, height);
const srcW = bitmap.width;
const srcH = bitmap.height;
const srcAspect = srcW / srcH;
const dstAspect = width / height;
let drawWidth = width;
let drawHeight = height;
// aspect-fit calculation (no cropping)
if (srcAspect > dstAspect) {
// image is wider → fit to canvas width
drawWidth = width;
drawHeight = width / srcAspect;
} else {
// image is taller → fit to canvas height
drawHeight = height;
drawWidth = height * srcAspect;
}
// center image (adds black borders if aspect ratios differ)
const dx = (width - drawWidth) / 50;
const dy = (height - drawHeight) / 2;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
ctx.drawImage(bitmap, 0, 0, srcW, srcH, dx, dy, drawWidth, drawHeight);
}
export function useGetOverviewSnapshot(side: string) {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const latestBitmapRef = useRef<ImageBitmap | null>(null);
// Redraw helper; always draws the current bitmap if available
const draw = useCallback(() => {
const canvas = canvasRef.current;
const bmp = latestBitmapRef.current;
if (!canvas || !bmp) return;
drawBitmapToCanvas(canvas, bmp);
}, []);
const {
data: snapshotBlob,
isError,
error,
isPending,
} = useQuery({
queryKey: ["overviewSnapshot", side],
queryFn: () => fetchSnapshot(side),
// Poll ~4 fps when visible; pause when tab hidden
refetchInterval: () => (document.visibilityState === "visible" ? 250 : false),
refetchOnWindowFocus: false,
// Avoid keeping lots of blobs around in cache
gcTime: 0, // v5 name (cacheTime in v4)
staleTime: 0,
retry: false, // or a small number if you prefer retries
});
// Convert Blob -> ImageBitmap and draw
useEffect(() => {
let cancelled = false;
if (!snapshotBlob) return;
(async () => {
try {
const bitmap = await createImageBitmap(snapshotBlob);
if (cancelled) {
bitmap.close();
return;
}
// Dispose previous bitmap to free memory
if (latestBitmapRef.current) {
latestBitmapRef.current.close();
}
latestBitmapRef.current = bitmap;
// Draw now (and again on next resize)
draw();
} catch {
// noop — fetch handler surfaces the main error path
}
})();
return () => {
cancelled = true;
};
}, [snapshotBlob, draw]);
// Redraw on resize & DPR changes
useEffect(() => {
const onResize = () => draw();
const onDPR = () => draw();
window.addEventListener("resize", onResize);
// Listen for DPR changes (some browsers support this)
const mql = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
mql.addEventListener?.("change", onDPR);
return () => {
window.removeEventListener("resize", onResize);
mql.removeEventListener?.("change", onDPR);
};
}, [draw]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (latestBitmapRef.current) {
latestBitmapRef.current.close();
latestBitmapRef.current = null;
}
};
}, []);
// Optional: normalize error type
const typedError = error instanceof Error ? error : undefined;
return { canvasRef, isError, error: typedError, isPending };
}

View File

@@ -3,75 +3,34 @@ import { useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config"; import { CAM_BASE } from "../utils/config";
const apiUrl = CAM_BASE; const apiUrl = CAM_BASE;
// const fetch_url = `http://100.82.205.44/Colour-preview`;
async function fetchSnapshot(cameraSide: string): Promise<Blob> { async function fetchSnapshot(cameraSide: string) {
const response = await fetch(`${apiUrl}/${cameraSide}-preview`, { const response = await fetch(`${apiUrl}/${cameraSide}-preview`, {
signal: AbortSignal.timeout(300000), signal: AbortSignal.timeout(500),
cache: "no-store",
}); });
if (!response.ok) { if (!response.ok) {
throw new Error(`Cannot reach endpoint (${response.status})`); throw new Error("Cannot reach endpoint");
}
return response.blob();
} }
/** Draw an ImageBitmap to canvas with aspect-fill (like object-fit: cover) */ return await response.blob();
function drawBitmapToCanvas(canvas: HTMLCanvasElement, bitmap: ImageBitmap) {
const ctx = canvas.getContext("2d");
if (!ctx) return;
const dpr = window.devicePixelRatio || 1;
const cssWidth = canvas.clientWidth;
const cssHeight = canvas.clientHeight;
const width = Math.floor(cssWidth * dpr);
const height = Math.floor(cssHeight * dpr);
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
ctx.clearRect(0, 0, width, height);
const srcW = bitmap.width;
const srcH = bitmap.height;
const srcAspect = srcW / srcH;
const dstAspect = width / height;
let drawWidth = width;
let drawHeight = height;
// aspect-fit calculation (no cropping)
if (srcAspect > dstAspect) {
// image is wider → fit to canvas width
drawWidth = width;
drawHeight = width / srcAspect;
} else {
// image is taller → fit to canvas height
drawHeight = height;
drawWidth = height * srcAspect;
}
// center image (adds black borders if aspect ratios differ)
const dx = (width - drawWidth) / 50;
const dy = (height - drawHeight) / 2;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
ctx.drawImage(bitmap, 0, 0, srcW, srcH, dx, dy, drawWidth, drawHeight);
} }
export function useGetOverviewSnapshot(side: string) { export function useGetOverviewSnapshot(side: string) {
const latestUrlRef = useRef<string | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null); const canvasRef = useRef<HTMLCanvasElement | null>(null);
const latestBitmapRef = useRef<ImageBitmap | null>(null); const imageRef = useRef<HTMLImageElement | null>(null);
// Redraw helper; always draws the current bitmap if available const drawImage = useCallback(() => {
const draw = useCallback(() => {
const canvas = canvasRef.current; const canvas = canvasRef.current;
const bmp = latestBitmapRef.current; const ctx = canvas?.getContext("2d");
if (!canvas || !bmp) return; const img = imageRef.current;
drawBitmapToCanvas(canvas, bmp);
if (!canvas || !ctx || !img) return;
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}, []); }, []);
const { const {
@@ -80,82 +39,43 @@ export function useGetOverviewSnapshot(side: string) {
error, error,
isPending, isPending,
} = useQuery({ } = useQuery({
queryKey: ["overviewSnapshot", side], queryKey: ["overviewSnapshot"],
queryFn: () => fetchSnapshot(side), queryFn: () => fetchSnapshot(side),
// Poll ~4 fps when visible; pause when tab hidden
refetchInterval: () => (document.visibilityState === "visible" ? 250 : false),
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
// Avoid keeping lots of blobs around in cache refetchInterval: 250,
gcTime: 0, // v5 name (cacheTime in v4)
staleTime: 0,
retry: false, // or a small number if you prefer retries
}); });
// Convert Blob -> ImageBitmap and draw
useEffect(() => { useEffect(() => {
let cancelled = false;
if (!snapshotBlob) return; if (!snapshotBlob) return;
(async () => { const imgUrl = URL.createObjectURL(snapshotBlob);
try { const img = new Image();
const bitmap = await createImageBitmap(snapshotBlob); imageRef.current = img;
if (cancelled) {
bitmap.close();
return;
}
// Dispose previous bitmap to free memory img.onload = () => {
if (latestBitmapRef.current) { drawImage();
latestBitmapRef.current.close(); };
} img.src = imgUrl;
latestBitmapRef.current = bitmap;
// Draw now (and again on next resize) if (latestUrlRef.current) {
draw(); URL.revokeObjectURL(latestUrlRef.current);
} catch {
// noop — fetch handler surfaces the main error path
} }
})(); latestUrlRef.current = imgUrl;
return () => { return () => {
cancelled = true; if (latestUrlRef.current) {
}; URL.revokeObjectURL(latestUrlRef.current);
}, [snapshotBlob, draw]); latestUrlRef.current = null;
// Redraw on resize & DPR changes
useEffect(() => {
const onResize = () => draw();
const onDPR = () => draw();
window.addEventListener("resize", onResize);
// Listen for DPR changes (some browsers support this)
const mql = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
mql.addEventListener?.("change", onDPR);
return () => {
window.removeEventListener("resize", onResize);
mql.removeEventListener?.("change", onDPR);
};
}, [draw]);
useEffect(() => {
const el = canvasRef.current?.parentElement; // the box
if (!el) return;
const ro = new ResizeObserver(() => draw()); // your draw() calls aspect-fit logic
ro.observe(el);
return () => ro.disconnect();
}, [draw]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (latestBitmapRef.current) {
latestBitmapRef.current.close();
latestBitmapRef.current = null;
} }
}; };
}, []); }, [snapshotBlob, drawImage]);
// Optional: normalize error type useEffect(() => {
const typedError = error instanceof Error ? error : undefined; window.addEventListener("resize", drawImage);
return () => {
window.removeEventListener("resize", drawImage);
};
}, [drawImage]);
return { canvasRef, isError, error: typedError, isPending }; return { canvasRef, isError, error, isPending };
} }

View File

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

View File

@@ -1,48 +0,0 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import type { InitialValuesForm } from "../types/types";
const getSightingAmend = async () => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=SightingAmmendA`);
if (!response.ok) throw new Error("Cannot reach sighting amend endpoint");
return response.json();
};
const updateSightingAmend = async (data: InitialValuesForm) => {
const updateSightingAmendPayload = {
id: "SightingAmmendA",
fields: [
{
property: "propOverviewQuality",
value: data.overviewQuality,
},
{
property: "propOverviewImageScaleFactor",
value: data.cropSizeFactor,
},
],
};
const response = await fetch(`${CAM_BASE}/api/update-config`, {
method: "Post",
body: JSON.stringify(updateSightingAmendPayload),
});
if (!response.ok) throw new Error("cannot update camera control");
return response.json();
};
export const useSightingAmend = () => {
const sightingAmendQuery = useQuery({
queryKey: ["getSightingAmend"],
queryFn: getSightingAmend,
});
const sightingAmendMutation = useMutation({
mutationKey: ["updateSightingAmend"],
mutationFn: updateSightingAmend,
});
return {
sightingAmendQuery,
sightingAmendMutation,
};
};

View File

@@ -1,18 +1,14 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import { Query, useQuery } from "@tanstack/react-query"; import { Query, useQuery } from "@tanstack/react-query";
import type { SightingType } from "../types/types"; import type { SightingType } from "../types/types";
import { useSound } from "react-sounds"; import { useSoundOnChange } from "react-sounds";
import { useSoundContext } from "../context/SoundContext"; import { useSoundContext } from "../context/SoundContext";
import { checkIsHotListHit, getNPEDCategory } from "../utils/utils"; import { getSoundFileURL } from "../utils/utils";
import switchSound from "../assets/sounds/ui/switch.mp3"; 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> { async function fetchSighting(url: string | undefined, ref: number): Promise<SightingType> {
const res = await fetch(`${url}${ref}`, { const res = await fetch(`${url}${ref}`, {
signal: AbortSignal.timeout(300000), signal: AbortSignal.timeout(5000),
}); });
if (!res.ok) throw new Error(String(res.status)); if (!res.ok) throw new Error(String(res.status));
return res.json(); return res.json();
@@ -25,19 +21,31 @@ export function useSightingFeed(url: string | undefined) {
const [sessionStarted, setSessionStarted] = useState(false); const [sessionStarted, setSessionStarted] = useState(false);
const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(null); const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(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 mostRecent = sightings[0] ?? null;
const latestRef = mostRecent?.ref ?? null;
const first = useRef(true);
const lastSoundAt = useRef(0);
const COOLDOWN_MS = 1500;
const currentRef = useRef<number>(-1); const currentRef = useRef<number>(-1);
const lastValidTimestamp = useRef<number>(Date.now()); 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)[]>) { function refetchInterval(query: Query<SightingType, Error, SightingType, (string | undefined)[]>) {
if (!query) return; if (!query) return;
const data = query.state.data as SightingType | undefined; const data = query.state.data as SightingType | undefined;
@@ -48,7 +56,7 @@ export function useSightingFeed(url: string | undefined) {
return 100; return 100;
} }
if (now - lastValidTimestamp.current > 600_000) { if (now - lastValidTimestamp.current > 60_000) {
currentRef.current = -1; currentRef.current = -1;
lastValidTimestamp.current = now; lastValidTimestamp.current = now;
} }
@@ -66,36 +74,15 @@ export function useSightingFeed(url: string | undefined) {
staleTime: 0, staleTime: 0,
}); });
const playHotlistsound = useDebouncedCallback(() => { //use latestref instead of trigger to revert back
hotlistsound(); useSoundOnChange(soundSrc, trigger, {
}, 500); volume: 1,
initial: false,
const playNPEDHitSound = useDebouncedCallback(() => { });
npedSound();
}, 500);
const playSightingHitSound = useDebouncedCallback(() => {
sightingSound();
}, 500);
useEffect(() => { useEffect(() => {
const data = query.data; const data = query.data;
if (!data || data.ref === -1) return; 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(); const now = Date.now();

View File

@@ -1,19 +0,0 @@
import { useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
const getStoreData = async () => {
const response = await fetch(`${CAM_BASE}/Store/diagnostics-json`);
if (!response.ok) throw new Error("Cannot get store data");
return response.json();
};
export const useStoreDispatch = () => {
const storeQuery = useQuery({
queryKey: ["getStoreData"],
queryFn: getStoreData,
refetchInterval: 1000,
refetchOnWindowFocus: true,
});
return { storeQuery };
};

View File

@@ -1,41 +1,11 @@
import { useMutation, useQuery } from "@tanstack/react-query"; import { useMutation, useQuery } from "@tanstack/react-query";
import { sendBlobFileUpload } from "../components/SettingForms/System/Upload"; import { sendBlobFileUpload } from "../components/SettingForms/System/Upload";
import { toast } from "sonner"; import { toast } from "sonner";
import { handleSystemSave, handleSystemRecall } from "../components/SettingForms/System/SettingSaveRecall"; import {
handleSystemSave,
handleSystemRecall,
} from "../components/SettingForms/System/SettingSaveRecall";
import { useEffect } from "react"; import { useEffect } from "react";
import { CAM_BASE } from "../utils/config";
import type { DNSSettingsType } from "../types/types";
const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : "";
const getDNSSettings = async () => {
const response = await fetch(`${camBase}/api/fetch-config?id=GLOBAL--NetworkConfig`);
if (!response.ok) throw new Error("Cannot get DNS Settings");
return response.json();
};
const updateDNSSettings = async (data: DNSSettingsType) => {
const dnsSettingsPayload = {
id: "GLOBAL--NetworkConfig",
fields: [
{
property: "propNameServerPrimary",
value: data?.serverPrimary,
},
{
property: "propNameServerSecondary",
value: data?.serverSecondary,
},
],
};
const response = await fetch(`${camBase}/api/update-config`, {
method: "post",
body: JSON.stringify(dnsSettingsPayload),
});
if (!response.ok) throw new Error("cannot send to DNS endpoint");
return response.json();
};
export const useSystemConfig = () => { export const useSystemConfig = () => {
const uploadSettingsMutation = useMutation({ const uploadSettingsMutation = useMutation({
@@ -81,20 +51,3 @@ export const useSystemConfig = () => {
saveSystemSettingsLoading: saveSystemSettings.isPending, saveSystemSettingsLoading: saveSystemSettings.isPending,
}; };
}; };
export const useDNSSettings = () => {
const dnsQuery = useQuery({
queryKey: ["getDNSSettings"],
queryFn: getDNSSettings,
});
const dnsMutation = useMutation({
mutationKey: ["updateDNSSettings"],
mutationFn: updateDNSSettings,
});
return {
dnsQuery,
dnsMutation,
};
};

View File

@@ -1,56 +0,0 @@
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

@@ -31,9 +31,3 @@ body {
} }
} }
} }
.arrow-outline path {
stroke: black; /* outline color */
stroke-width: 20px; /* thickness of outline (tweak this) */
stroke-linejoin: round;
}

View File

@@ -4,7 +4,7 @@ import OverviewVideoContainer from "../components/FrontCameraSettings/OverviewVi
import { Toaster } from "sonner"; import { Toaster } from "sonner";
const FrontCamera = () => { const FrontCamera = () => {
const [zoomLevel, setZoomLevel] = useState<number | undefined>(1); const [zoomLevel, setZoomLevel] = useState<number>(1);
return ( return (
<div className="mx-auto flex flex-col lg:flex-row gap-2 px-1 sm:px-2 lg:px-0 w-full min-h-screen"> <div className="mx-auto flex flex-col lg:flex-row gap-2 px-1 sm:px-2 lg:px-0 w-full min-h-screen">
<OverviewVideoContainer <OverviewVideoContainer

View File

@@ -4,9 +4,9 @@ import { Toaster } from "sonner";
import { useState } from "react"; import { useState } from "react";
const RearCamera = () => { const RearCamera = () => {
const [zoomLevel, setZoomLevel] = useState<number | undefined>(1); const [zoomLevel, setZoomLevel] = useState<number>(1);
return ( return (
<div className="mx-auto flex flex-col-reverse lg:flex-row gap-2 px-1 sm:px-2 lg:px-0 w-full min-h-screen"> <div className="mx-auto flex flex-col lg:flex-row gap-2 px-1 sm:px-2 lg:px-0 w-full min-h-screen">
<CameraSettings <CameraSettings
title="Camera B Settings" title="Camera B Settings"
side={"CameraB"} side={"CameraB"}

View File

@@ -47,7 +47,7 @@ const SystemSettings = () => {
</div> </div>
</TabPanel> </TabPanel>
<TabPanel> <TabPanel>
<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"> <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">
<SoundSettingsCard /> <SoundSettingsCard />
<SoundUploadCard /> <SoundUploadCard />
</div> </div>

View File

@@ -41,26 +41,24 @@ export type CameraSettingValues = {
userName: string; userName: string;
password: string; password: string;
id: number | string; id: number | string;
mode: string;
}; };
export type CameraSettingErrorValues = Partial<Record<keyof CameraSettingValues, string>>; export type CameraSettingErrorValues = Partial<
Record<keyof CameraSettingValues, string>
>;
export type BearerTypeFieldType = { export type BearerTypeFieldType = {
format: string; format: string;
enabled: boolean; enabled: boolean;
verbose?: boolean; verbose: boolean;
}; };
export type InitialValuesForm = { export type InitialValuesForm = {
format: string;
backOfficeURL: string; backOfficeURL: string;
username: string; username: string;
password: string; password: string;
connectTimeoutSeconds: number; connectTimeoutSeconds: number;
readTimeoutSeconds: number; readTimeoutSeconds: number;
overviewQuality?: string;
cropSizeFactor?: string;
}; };
export type InitialValuesFormErrors = { export type InitialValuesFormErrors = {
@@ -71,20 +69,6 @@ export type InitialValuesFormErrors = {
readTimeoutSeconds?: string; readTimeoutSeconds?: string;
}; };
export type OptionalBOF2Constants = {
FFID?: string;
SCID?: string;
timestampSource?: string;
GPSFormat?: string;
};
export type OptionalBOF2LaneIDs = {
laneId?: string;
LID1?: string;
LID2?: string;
LID3?: string;
};
export type NPEDFieldType = { export type NPEDFieldType = {
frontId: string; frontId: string;
username: string | undefined; username: string | undefined;
@@ -167,13 +151,6 @@ export type SystemValues = {
sntpInterval: number; sntpInterval: number;
timeZone: string; timeZone: string;
softwareUpdate?: File | null; softwareUpdate?: File | null;
serverPrimary?: string;
serverSecondary?: string;
};
export type DNSSettingsType = {
serverPrimary?: string;
serverSecondary?: string;
}; };
export type SystemValuesErrors = { export type SystemValuesErrors = {
@@ -310,28 +287,18 @@ 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;
soundFileName?: string; soundFile: File | null;
soundFile?: File | null;
soundUrl?: string;
uploadedAt?: number;
}; };
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;
NPEDsoundVolume: number;
hotlistSoundVolume: number;
uploadedSound?: Blob | null;
}; };
type UpdateAction = { type UpdateAction = {
@@ -340,11 +307,6 @@ type UpdateAction = {
sightingSound: SoundValue; sightingSound: SoundValue;
NPEDsound: SoundValue; NPEDsound: SoundValue;
hotlists: Hotlist[]; hotlists: Hotlist[];
sightingVolume: number;
NPEDsoundVolume: number;
hotlistSoundVolume: number;
hotlistSound: SoundValue;
soundOptions?: SoundUploadValue[];
}; };
}; };
@@ -353,17 +315,7 @@ type AddAction = {
payload: SoundUploadValue; payload: SoundUploadValue;
}; };
type VolumeAction = { export type SoundAction = UpdateAction | AddAction;
type: "SIGHTINGVOLUME" | "NPEDVOLUME" | "HOTLISTVOLUME";
payload: number;
};
type UploadedState = {
type: "UPLOADEDSOUND";
payload: Blob | undefined;
};
export type SoundAction = UpdateAction | AddAction | VolumeAction | UploadedState;
export type WifiSettingValues = { export type WifiSettingValues = {
ssid: string; ssid: string;
password: string; password: string;
@@ -391,7 +343,6 @@ export type ModemConfig = {
export type ZoomInOptions = { export type ZoomInOptions = {
camera: string; camera: string;
multiplier: number; multiplier: number;
multiplierText?: string;
}; };
export type zoomConfig = { export type zoomConfig = {
@@ -403,30 +354,4 @@ export type ModemSettingsType = {
username: string; username: string;
password: string; password: string;
authenticationType: string; authenticationType: string;
serverPrimary: string;
serverSecondary: 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;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload: any;
}; };

View File

@@ -1,16 +0,0 @@
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

@@ -1,24 +0,0 @@
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,31 +1,18 @@
import switchSound from "../assets/sounds/ui/switch.mp3"; import switchSound from "../assets/sounds/ui/switch.mp3";
import popup from "../assets/sounds/ui/popup_open.mp3"; import popup from "../assets/sounds/ui/popup_open.mp3";
import notification from "../assets/sounds/ui/notification.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 type { HotlistMatches, SightingType } from "../types/types";
import { hasFlag } from "country-flag-icons";
export function getSoundFileURL(name: string) { export function getSoundFileURL(name: string) {
const sounds: Record<string, string> = { const sounds: Record<string, string> = {
switch: switchSound, switch: switchSound,
popup: popup, popup: popup,
notification: notification, notification: notification,
beep: beep,
warning: warning,
ding: ding,
shutter: shutter,
attention: attention,
}; };
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);
@@ -92,6 +79,12 @@ export const formatNumberPlate = (plate: string) => {
const formattedPlate = splittedPlate?.join(""); const formattedPlate = splittedPlate?.join("");
return formattedPlate; 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=="; export const BLANK_IMG = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
@@ -148,50 +141,16 @@ export const checkIsHotListHit = (sigthing: SightingType | null) => {
}; };
export function getHotlistName(obj: HotlistMatches | undefined) { export function getHotlistName(obj: HotlistMatches | undefined) {
if (!obj) return; if (!obj || Object.values(obj).includes(false)) return;
const hotlistNames = Object.entries(obj) const keys = Object.keys(obj);
.filter(([, value]) => value === true) return keys;
.map(([key]) => key);
return hotlistNames;
} }
export const getNPEDCategory = (r?: SightingType | null) => export const getNPEDCategory = (r?: SightingType | null) =>
r?.metadata?.npedJSON?.["NPED CATEGORY"] as "A" | "B" | "C" | "D" | undefined; r?.metadata?.npedJSON?.["NPED CATEGORY"] as "A" | "B" | "C" | undefined;
export const zoomMapping = (zoomLevel: number | undefined) => { export const numberPlateFlag = (countryCode: string) => {
switch (zoomLevel) { const result = hasFlag(countryCode) === true;
case 1: console.log(result);
return "Near";
case 2:
return "Mid";
case 4:
return "Far";
default:
break;
}
};
export const reverseZoomMapping = (magnification: string) => {
switch (magnification) {
case "near":
return 1;
case "mid":
return 2;
case "far":
return 4;
default:
break;
}
};
export const ValidateIPaddress = (value: string | undefined) => {
if (!value) return;
const regex =
/^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
if (!regex.test(value)) {
return "Invalid IP address format";
}
}; };

View File

@@ -138,7 +138,7 @@
dependencies: dependencies:
"@babel/helper-plugin-utils" "^7.27.1" "@babel/helper-plugin-utils" "^7.27.1"
"@babel/runtime@^7.1.2", "@babel/runtime@^7.10.1", "@babel/runtime@^7.18.3": "@babel/runtime@^7.1.2":
version "7.28.4" version "7.28.4"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.28.4.tgz#a70226016fabe25c5783b2f22d3e1c9bc5ca3326" resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.28.4.tgz#a70226016fabe25c5783b2f22d3e1c9bc5ca3326"
integrity sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ== integrity sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==
@@ -1044,11 +1044,6 @@ chownr@^3.0.0:
resolved "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz" resolved "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz"
integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== 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: clsx@^2.0.0, clsx@^2.1.1:
version "2.1.1" version "2.1.1"
resolved "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz" resolved "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz"
@@ -1880,23 +1875,6 @@ queue-microtask@^1.2.2:
resolved "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz" resolved "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz"
integrity sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A== 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: react-dom@^19.1.1:
version "19.1.1" version "19.1.1"
resolved "https://registry.npmjs.org/react-dom/-/react-dom-19.1.1.tgz" resolved "https://registry.npmjs.org/react-dom/-/react-dom-19.1.1.tgz"
@@ -1914,11 +1892,6 @@ react-is@^16.13.1, react-is@^16.7.0:
resolved "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz" resolved "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz"
integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== 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: react-lifecycles-compat@^3.0.0:
version "3.0.4" version "3.0.4"
resolved "https://registry.npmjs.org/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz" resolved "https://registry.npmjs.org/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz"
@@ -2267,11 +2240,6 @@ uri-js@^4.2.2:
dependencies: dependencies:
punycode "^2.1.0" 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: vite@^7.1.0:
version "7.1.2" version "7.1.2"
resolved "https://registry.npmjs.org/vite/-/vite-7.1.2.tgz" resolved "https://registry.npmjs.org/vite/-/vite-7.1.2.tgz"