67 Commits

Author SHA1 Message Date
f571ab80a2 Merge branch 'main' into develop 2025-11-11 14:27:50 +00:00
b2335d2d4d - removed dist and updated readme 2025-11-11 14:26:52 +00:00
a873da8ef5 Merge pull request 'develop' (#4) from develop into main
Reviewed-on: #4
2025-11-11 13:58:46 +00:00
5014c97b4d updated readme 2025-11-11 13:57:05 +00:00
e374456588 updated readme 2025-11-11 13:52:58 +00:00
ee3e111e9b Merge pull request 'Update README.md' (#3) from tobaojo-patch-1 into develop
Reviewed-on: #3
2025-11-11 13:50:02 +00:00
a8178269c2 Update README.md 2025-11-11 13:49:46 +00:00
c057ce5084 Merge pull request 'develop' (#2) from develop into main
Reviewed-on: #2
2025-11-11 12:52:29 +00:00
0c7d99f7ea minor bugfix: removed csv check for update files 2025-11-11 12:50:48 +00:00
f2e10f958d Merge pull request 'added wifi validation' (#1) from bugfix/wifi into develop
Reviewed-on: #1
2025-11-11 12:40:15 +00:00
903b856303 added wifi validation 2025-11-11 12:37:28 +00:00
672ff1d2f1 Merged main into develop 2025-11-11 10:49:06 +00:00
08a07b7ffb Merged in develop (pull request #38)
Develop
2025-11-11 10:46:53 +00:00
d60c546db1 Merged in bugfix/Matttesting (pull request #37)
Bugfix/Matttesting
2025-11-11 10:45:25 +00:00
f35e2f9fb5 - added store and forward
- amended sighting ammend endpoint
2025-11-11 10:43:14 +00:00
cac9a2167d - tweaked timeouts 2025-11-10 13:47:19 +00:00
feddaa1eb0 - addressed bugs flagged by BR 2025-11-10 13:44:29 +00:00
ddeedd2d72 - fixed cropped live feed and amended APIs for submission 2025-11-10 11:55:15 +00:00
a734de6261 - removed ids in api enpoints as they are in JSON objects being sent 2025-11-10 09:05:08 +00:00
d57ad1003a -address fixes and changes per feedback from Matt and Brad 2025-11-05 16:30:27 +00:00
861f2dd31d - added endpoints for dns and other 2025-11-04 17:04:19 +00:00
647fd201a3 - minor tweaks on zoom and navigation arrow 2025-11-04 16:09:24 +00:00
c127ce8a8c - more addition bugfixes 2025-11-04 15:29:48 +00:00
61894c0c42 - minor big fixes
- default settings toggled
-update camera zoom need to test
2025-11-04 13:38:06 +00:00
76643cc84c Merged main into develop 2025-11-04 12:00:04 +00:00
f6c1ea2b1c - fixed endpoint typo 2025-11-04 11:49:40 +00:00
18e4d1dcff - quick fix for bof2 2025-11-04 11:45:54 +00:00
010a9fb59d Merged in develop (pull request #36)
Develop
2025-11-04 11:41:47 +00:00
b1953dd965 Merged in bugfix/uploadsounds-2 (pull request #35)
Bugfix/uploadsounds 2
2025-11-04 11:40:16 +00:00
630261ac21 Merged develop into bugfix/uploadsounds-2 2025-11-04 11:37:59 +00:00
c948192f10 Merged in bugfix/bearertype (pull request #34)
Bugfix/bearertype
2025-11-04 11:37:05 +00:00
f47459d116 - added validation endpoint 2025-11-04 11:31:37 +00:00
705d7c7040 - removed other options 2025-11-04 11:17:04 +00:00
ca625673e9 - updated to retrieve and set BOF2 data 2025-11-04 11:05:40 +00:00
538b623ac6 - updated form to include bof2 constants
- refactored code to make more scalable and use one form
2025-11-04 10:24:06 +00:00
933c101cbc - refactored to fetch confis based on formats
- send configs based on formats
2025-11-03 15:01:13 +00:00
af1dabc8fc Merged main into bugfix/uploadsounds-2 2025-10-31 08:27:59 +00:00
a839502421 - added sound file size limit 2025-10-30 11:16:06 +00:00
39629897d4 - removed console.logs 2025-10-30 10:53:48 +00:00
cd26b3b68f Merged main into develop 2025-10-30 10:41:07 +00:00
a8abed2246 - added feature to cache sounds for cross devices - should work in theory 2025-10-29 15:04:40 +00:00
cf72a1e1d3 - fixed file size bug 2025-10-28 15:23:28 +00:00
c8eed55801 - uploaded files seems to work on desktop version 2025-10-28 13:53:11 +00:00
907555cb0d - storing changes for now 2025-10-28 09:54:29 +00:00
d6c39843c8 Merged in develop (pull request #33)
Develop
2025-10-28 08:52:54 +00:00
a64fa76ecb - saving current work before refactor 2025-10-28 08:50:55 +00:00
93dcde4459 Merge branch 'develop' into bugfix/uploadsounds-2 2025-10-27 14:28:56 +00:00
a5b07333da Merged in bugfix/minorchanges (pull request #32)
bugfix/minorChanges
2025-10-27 14:20:56 +00:00
ae0a6f9249 - added debouncing of sounds
- added new sound files
- moved soung hits to sighting list
2025-10-27 14:00:28 +00:00
350d7cf41c Merge branch 'bugfix/uploadsounds-2' of bitbucket.org:mavsystemsltd/mav-in-car-fe into bugfix/uploadsounds-2 2025-10-27 11:31:25 +00:00
78e5da45ca Merged develop into bugfix/uploadsounds-2 2025-10-27 11:29:07 +00:00
e46460f41d Merged in enhancement/sessionstats (pull request #31)
Enhancement/sessionstats
2025-10-27 11:23:29 +00:00
6c441a0a4b Merged in enhancement-refactor (pull request #30)
Enhancement refactor
2025-10-27 11:11:15 +00:00
2d5b264041 - refactored state for sessionlist, and session active and pause states 2025-10-27 11:04:53 +00:00
251a2f5e7b - refactored NPED Login & logout 2025-10-27 09:35:59 +00:00
18534ceb2c - added functionality to save sighting sessions to black board 2025-10-27 08:28:44 +00:00
9975e6a6ca Merged develop into enhancement/sessionstats 2025-10-24 11:12:51 +00:00
c83122cd52 - added session sighting component
- add new session paused state and stop adding to session when true
2025-10-24 12:10:10 +01:00
abc8007fc6 Merged in enhancement/sightingHits (pull request #29)
Enhancement/sightingHits
2025-10-24 09:56:25 +00:00
7903633809 - removed console.log 2025-10-24 10:55:05 +01:00
359f3781f2 - refactored to allow for stacking of special hits (NPED + Hotlist) 2025-10-24 10:49:04 +01:00
f264f4e808 - resolved coding error 2025-10-23 09:19:18 +01:00
0c6e4b57be - need to find better way to fetch file urls to use for sound 2025-10-22 16:12:49 +01:00
a958901bed - will pick up later 2025-10-22 12:20:15 +01:00
4519700561 - added new sound files
- new functionality to upload files
- need to get and locatate uploaded files
2025-10-22 11:51:37 +01:00
b58181e551 - started improvements on session page to include pause and save buttons 2025-10-22 08:54:42 +01:00
df6bf75184 Merged in bugfix/uploadsounds (pull request #28)
Bugfix/uploadsounds
2025-10-21 14:20:33 +00:00
65 changed files with 2103 additions and 866 deletions

163
README.md
View File

@@ -1,69 +1,116 @@
# React + TypeScript + Vite
# Mav Mobile UI
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
This is a React-based web application built with Vite (react and typescript).
Currently, two official plugins are available:
## Getting started
- [@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
### Prerequisites
## Expanding the ESLint configuration
- Node.js (v18 or higher recommended)
- Yarn (v1.22+) (https://yarnpkg.com/)
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
### Installation
```js
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// 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...
},
},
])
```bash
git clone https://mavportal.com/TobaOjo/Mav-Mobile-UI.git
cd Mav-Mobile-UI
yarn install
```
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:
### 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
// 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...
},
},
])
<foot>
<script>
if (window.location.pathname !== "/Mobile") {
window.location.replace(window.location.origin + "/Mobile");
}
</script>
</foot>
```
- Run
```bash
sudo reboot
```
It should come back up all working

View File

@@ -32,7 +32,8 @@
"react-tabs": "^6.1.0",
"react-use": "^17.6.0",
"sonner": "^2.0.7",
"tailwindcss": "^4.1.11"
"tailwindcss": "^4.1.11",
"use-debounce": "^10.0.6"
},
"devDependencies": {
"@eslint/js": "^9.32.0",

View File

@@ -5,7 +5,7 @@ import FrontCamera from "./pages/FrontCamera";
import RearCamera from "./pages/RearCamera";
import SystemSettings from "./pages/SystemSettings";
import Session from "./pages/Session";
import { NPEDUserProvider } from "./context/providers/NPEDUserContextProvider";
import { IntegrationsProvider } from "./context/providers/IntegrationsContextProvider";
import { AlertHitProvider } from "./context/providers/AlertHitProvider";
import { SoundProvider } from "react-sounds";
import SoundContextProvider from "./context/providers/SoundContextProvider";
@@ -14,20 +14,20 @@ function App() {
return (
<SoundContextProvider>
<SoundProvider initialEnabled={true}>
<NPEDUserProvider>
<IntegrationsProvider>
<AlertHitProvider>
<Routes>
<Route path="/" element={<Container />}>
<Route index element={<Dashboard />} />
<Route path="camera-settings" element={<FrontCamera />} />
<Route path="rear-camera-settings" element={<RearCamera />} />
<Route path="a-camera-settings" element={<FrontCamera />} />
<Route path="b-camera-settings" element={<RearCamera />} />
<Route path="system-settings" element={<SystemSettings />} />
<Route path="session-settings" element={<Session />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Route>
</Routes>
</AlertHitProvider>
</NPEDUserProvider>
</IntegrationsProvider>
</SoundProvider>
</SoundContextProvider>
);

Binary file not shown.

Binary file not shown.

View File

@@ -1,11 +1,8 @@
import { useGetOverviewSnapshot } from "../../hooks/useGetOverviewSnapshot";
import type { ZoomInOptions } from "../../types/types";
import NavigationArrow from "../UI/NavigationArrow";
import { useCameraZoom } from "../../hooks/useCameraZoom";
import { useEffect } from "react";
import Loading from "../UI/Loading";
import ErrorState from "../UI/ErrorState";
type SnapshotContainerProps = {
side: string;
settingsPage?: boolean;
@@ -13,52 +10,20 @@ type SnapshotContainerProps = {
onZoomLevelChange?: (level: number) => void;
};
export const SnapshotContainer = ({
side,
settingsPage,
zoomLevel,
onZoomLevelChange,
}: SnapshotContainerProps) => {
export const SnapshotContainer = ({ side, settingsPage }: SnapshotContainerProps) => {
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 (
<div className="flex flex-col md:flex-row">
<NavigationArrow side={side} settingsPage={settingsPage} />
<div className="w-full">
<div className="w-full bg-[#253445] rounded-md overflow-hidden md:h-[500px] lg:h-[70vh]">
{isError && <ErrorState />}
{isPending && (
<div className="my-50 h-[50%]">
<div className="absolute inset-0 grid place-items-center">
<Loading message="Camera Preview" />
</div>
)}
<canvas
onClick={handleZoomClick}
ref={canvasRef}
className="absolute inset-0 object-contain min-h-[100%] z-20"
/>
<canvas ref={canvasRef} className="absolute w-full h-full z-20" />
</div>
</div>
);

View File

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

View File

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

View File

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

View File

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

View File

@@ -40,9 +40,7 @@ const NumberPlate = ({ motion, vrm, size }: NumberPlateProps) => {
return (
<div
className={`relative ${options.plateWidth} ${
options.borderWidth
} border-black rounded-xl text-nowrap
className={`relative ${options.plateWidth} ${options.borderWidth} border-black rounded-xl text-nowrap
text-black px-6 py-2
${motion ? "bg-yellow-400" : "bg-white"}`}
>
@@ -50,9 +48,7 @@ const NumberPlate = ({ motion, vrm, size }: NumberPlateProps) => {
<div className="absolute inset-y-0 left-0 bg-blue-600 w-8 flex flex-col">
<GB />
</div>
<p className={`pl-4 font-extrabold ${options.textSize} text-right`}>
{vrm && formatNumberPlate(vrm)}
</p>
<p className={`pl-4 font-extrabold ${options.textSize} text-right`}>{vrm && formatNumberPlate(vrm)}</p>
</div>
</div>
);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,79 +1,52 @@
import { Field, Form, Formik, useFormikContext } from "formik";
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Field, useFormikContext, type FormikTouched } from "formik";
import FormGroup from "../components/FormGroup";
import { useEffect, useState } from "react";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useCameraOutput } from "../../../hooks/useCameraOutput";
import type { InitialValuesForm, InitialValuesFormErrors } from "../../../types/types";
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
import { toast } from "sonner";
import type { UseQueryResult } from "@tanstack/react-query";
const ChannelFields = () => {
type ChannelFieldsProps = {
touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>;
isSubmitting: boolean;
backOfficeData: UseQueryResult<any, Error>;
format?: string;
};
const ChannelFields = ({ touched, isSubmitting, format }: ChannelFieldsProps) => {
const [showPwd, setShowPwd] = useState(false);
const { backOfficeQuery, backOfficeMutation } = useCameraOutput();
const backOfficeURL = backOfficeQuery?.data?.propBackofficeURL?.value;
const username = backOfficeQuery?.data?.propUsername?.value;
const password = backOfficeQuery?.data?.propPassword?.value;
const connectTimeoutSeconds = backOfficeQuery?.data?.propConnectTimeoutSeconds?.value;
const readTimeoutSeconds = backOfficeQuery?.data?.propReadTimeoutSeconds?.value;
const initialValues: InitialValuesForm = {
backOfficeURL: backOfficeURL ?? "",
username: username ?? "",
password: password ?? "",
connectTimeoutSeconds: Number(connectTimeoutSeconds),
readTimeoutSeconds: Number(readTimeoutSeconds),
};
const handleSubmit = async (values: InitialValuesForm) => {
await backOfficeMutation.mutateAsync(values);
};
const { submitCount, isValid, values, errors } = useFormikContext<BearerTypeFieldType & InitialValuesForm>();
const ValidationToastOnce = () => {
const { submitCount, isValid } = useFormikContext();
useEffect(() => {
if (submitCount > 0 && !isValid) {
toast.error("Check fields are filled in");
}
}, [submitCount, isValid]);
}, []);
return null;
};
const validateValues = (values: InitialValuesForm): InitialValuesFormErrors => {
const errors: InitialValuesFormErrors = {};
const url = values.backOfficeURL?.trim();
const username = values.username?.trim();
const password = values.password?.trim();
if (!url) {
errors.backOfficeURL = "Required";
}
if (!username) errors.username = "Required";
if (!password) errors.password = "Required";
const read = Number(values.readTimeoutSeconds);
if (!Number.isFinite(read)) {
errors.readTimeoutSeconds = "Must be a number";
} else if (read < 0) {
errors.readTimeoutSeconds = "Must be ≥ 0";
}
const connect = Number(values.connectTimeoutSeconds);
if (!Number.isFinite(connect)) {
errors.connectTimeoutSeconds = "Must be a number";
} else if (connect < 0) {
errors.connectTimeoutSeconds = "Must be ≥ 0";
}
return errors;
};
return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize validate={validateValues}>
{({ errors, touched, isSubmitting }) => (
<Form>
<>
{format?.toLowerCase() !== "bof2" && format?.toLowerCase() !== "json" ? (
<>
<div className="mt-4 flex flex-col items-center justify-center rounded-2xl border border-slate-800 bg-slate-900/40 p-10 text-center">
<div className="mb-3 rounded-xl bg-slate-800 px-3 py-1 text-xs uppercase tracking-wider text-slate-400">
Format coming soon
</div>
<p className="max-w-md text-slate-300">
Output configuration currently supports <span className="font-bold text-blue-400">JSON</span> or{" "}
<span className="font-bold text-emerald-400">BOF2</span>. <br /> More formats will be added in future
updates.
</p>
</div>
</>
) : (
<>
<div className="flex flex-col space-y-2 px-2">
<FormGroup>
<label htmlFor="backoffice" className="m-0">
@@ -85,9 +58,7 @@ const ChannelFields = () => {
type="text"
id="backoffice"
placeholder="https://www.backoffice.com"
className={`p-1.5 border ${
errors.backOfficeURL && touched.backOfficeURL ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
className={`p-1.5 border border-gray-400 rounded-lg w-full md:w-60`}
/>
</FormGroup>
<FormGroup>
@@ -97,9 +68,7 @@ const ChannelFields = () => {
type="text"
id="username"
placeholder="Back office username"
className={`p-1.5 border ${
errors.username && touched.username ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
className={`p-1.5 border border-gray-400 rounded-lg w-full md:w-60`}
/>
</FormGroup>
<FormGroup>
@@ -146,17 +115,133 @@ const ChannelFields = () => {
} rounded-lg w-full md:w-60`}
/>
</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`}
/>
</FormGroup>
</div>
</>
)}
</div>
<button
type="submit"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
>
{isSubmitting || backOfficeMutation.isPending ? "Saving..." : "Save Changes"}
{isSubmitting ? "Saving..." : "Save Changes"}
</button>
<ValidationToastOnce />
</Form>
</>
)}
</Formik>
</>
);
};

View File

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

View File

@@ -1,12 +1,151 @@
import { Form, Formik } from "formik";
import BearerTypeCard from "../BearerType/BearerTypeCard";
import ChannelCard from "../Channel1-JSON/ChannelCard";
import { useCameraOutput, useGetDispatcherConfig } from "../../../hooks/useCameraOutput";
import type {
BearerTypeFieldType,
InitialValuesForm,
InitialValuesFormErrors,
OptionalBOF2Constants,
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 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 (
<div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-2 sm:px-4 lg:px-0 w-full">
<BearerTypeCard />
<ChannelCard />
</div>
<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>
<BearerTypeCard />
<StoreCard />
</div>
<ChannelCard
touched={touched}
isSubmitting={isSubmitting}
isDispatcherLoading={isDispatcherLoading}
isBof2ConstantsLoading={isBof2ConstantsLoading}
/>
</div>
</Form>
)}
</Formik>
);
};

View File

@@ -32,7 +32,6 @@ const SoundSettingsFields = () => {
hotlistSoundVolume: state.hotlistSoundVolume,
soundOptions: [...(state.soundOptions ?? [])],
};
dispatch({ type: "UPDATE", payload: updatedValues });
const result = await mutation.mutateAsync({

View File

@@ -4,16 +4,21 @@ import type { SoundUploadValue } from "../../../types/types";
import { useSoundContext } from "../../../context/SoundContext";
import { toast } from "sonner";
import { useCameraBlackboard } from "../../../hooks/useCameraBlackboard";
import { useFileUpload } from "../../../hooks/useFileUpload";
const SoundUpload = () => {
const { state, dispatch } = useSoundContext();
const { mutation } = useCameraBlackboard();
const { mutation: fileMutation } = useFileUpload({
queryKey: state.sightingSound ? [state.sightingSound] : undefined,
});
const initialValues: SoundUploadValue = {
name: "",
soundFile: null,
soundFileName: "",
soundUrl: "",
uploadedAt: Date.now(),
};
const handleSubmit = async (values: SoundUploadValue) => {
@@ -37,10 +42,9 @@ const SoundUpload = () => {
path: "soundSettings",
value: updatedValues,
});
await fileMutation.mutateAsync(values.soundFile);
if (result.reason !== "OK") {
toast.error("Cannot update sound settings");
} else {
toast.success(`${values.name} file added`);
}
dispatch({ type: "ADD", payload: values });
@@ -48,7 +52,7 @@ const SoundUpload = () => {
return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
{({ setFieldValue, errors, setFieldError, values }) => (
{({ setFieldValue, errors, setFieldError }) => (
<Form>
<label htmlFor="soundFile" className="">
Sound File
@@ -67,6 +71,12 @@ const SoundUpload = () => {
setFieldValue("name", e.target.files[0].name);
setFieldValue("soundFileName", e.target.files[0].name);
setFieldValue("soundFile", e.target.files[0]);
setFieldValue("uploadedAt", Date.now());
if (e?.target?.files[0]?.size >= 1 * 1024 * 1024) {
setFieldError("soundFile", "larger than 1mb");
toast.error("File larger than 1MB");
return;
}
} else {
setFieldError("soundFile", "Not an mp3 file");
toast.error("Not an mp3 file");
@@ -76,11 +86,6 @@ const SoundUpload = () => {
</FormGroup>
<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">
{!values.soundFile && (
<div className="mb-3 rounded-xl bg-slate-800 px-3 py-1 text-xs uppercase tracking-wider text-slate-400">
No uploaded sound files
</div>
)}
<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>{" "}

View File

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

View File

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

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

View File

@@ -4,21 +4,29 @@ import { useReboots } from "../../../hooks/useReboots";
import { timezones } from "./timezones";
import SystemFileUpload from "./SystemFileUpload";
import type { SystemValues, SystemValuesErrors } from "../../../types/types";
import { useSystemConfig } from "../../../hooks/useSystemConfig";
import { useDNSSettings, useSystemConfig } from "../../../hooks/useSystemConfig";
const SystemConfigFields = () => {
const { saveSystemSettings, systemSettingsData, saveSystemSettingsLoading } = useSystemConfig();
const { softRebootMutation, hardRebootMutation } = useReboots();
const { hardRebootMutation } = useReboots();
const { dnsQuery, dnsMutation } = useDNSSettings();
const dnsPrimary = dnsQuery?.data?.propNameServerPrimary?.value;
const dnsSecondary = dnsQuery?.data?.propNameServerSecondary?.value;
const initialvalues: SystemValues = {
deviceName: systemSettingsData?.deviceName ?? "",
timeZone: systemSettingsData?.timeZone ?? "",
sntpServer: systemSettingsData?.sntpServer ?? "",
sntpInterval: systemSettingsData?.sntpInterval ?? 60,
serverPrimary: dnsPrimary ?? "",
serverSecondary: dnsSecondary ?? "",
softwareUpdate: null,
};
const handleSubmit = (values: SystemValues) => saveSystemSettings(values);
const handleSubmit = async (values: SystemValues) => {
saveSystemSettings(values);
await dnsMutation.mutateAsync(values);
};
const validateValues = (values: SystemValues) => {
const errors: SystemValuesErrors = {};
@@ -30,9 +38,9 @@ const SystemConfigFields = () => {
return errors;
};
const handleSoftReboot = async () => {
await softRebootMutation.mutate();
};
// const handleSoftReboot = async () => {
// await softRebootMutation.mutate();
// };
const handleHardReboot = async () => {
await hardRebootMutation.mutate();
@@ -102,6 +110,7 @@ const SystemConfigFields = () => {
autoComplete="off"
/>
</FormGroup>
<FormGroup>
<label htmlFor="sntpInterval" className="font-medium whitespace-nowrap md:w-1/2 text-left">
SNTP Interval minutes
@@ -118,6 +127,34 @@ const SystemConfigFields = () => {
className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
/>
</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
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"
@@ -130,13 +167,13 @@ const SystemConfigFields = () => {
<p>Reboot</p>
</div>
<button
{/* <button
type="button"
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full md:w-[50%]"
onClick={handleSoftReboot}
>
{softRebootMutation.isPending || isSubmitting ? "Rebooting..." : "Software Reboot"}
</button>
</button> */}
<button
type="button"
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full md:w-[50%]"

View File

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

View File

@@ -57,78 +57,81 @@ const ModemSettings = () => {
return (
<>
<ModemToggle showSettings={showSettings} onShowSettings={setShowSettings} />
{!showSettings && (
<Formik initialValues={inititalValues} onSubmit={handleSubmit} enableReinitialize>
{({ isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2">
<FormGroup>
<label htmlFor="apn" className="font-medium whitespace-nowrap md:w-2/3">
APN
</label>
<Field
placeholder="Enter APN"
name="apn"
id="apn"
type="text"
className="p-1.5 border border-gray-400 rounded-lg"
/>
</FormGroup>
<FormGroup>
<label htmlFor="username" className="font-medium whitespace-nowrap md:w-2/3">
Username
</label>
<Field
placeholder="Enter Username"
name="username"
id="username"
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">
Password
</label>
<div className="flex gap-2 items-center relative mb-4">
<Formik initialValues={inititalValues} onSubmit={handleSubmit} enableReinitialize>
{({ isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2">
{!showSettings && (
<>
<FormGroup>
<label htmlFor="apn" className="font-medium whitespace-nowrap md:w-2/3">
APN
</label>
<Field
id="password"
name="password"
type={showPwd ? "text" : "password"}
className="p-2 border border-gray-400 rounded-lg w-full"
placeholder="Enter Password"
placeholder="Enter APN"
name="apn"
id="apn"
type="text"
className="p-1.5 border border-gray-400 rounded-lg"
/>
<FontAwesomeIcon
type="button"
className="absolute right-5 end-0"
onClick={() => setShowPwd((s) => !s)}
icon={showPwd ? faEyeSlash : faEye}
</FormGroup>
<FormGroup>
<label htmlFor="username" className="font-medium whitespace-nowrap md:w-2/3">
Username
</label>
<Field
placeholder="Enter Username"
name="username"
id="username"
type="text"
className="p-1.5 border border-gray-400 rounded-lg"
/>
</div>
</FormGroup>
<FormGroup>
<label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">
Password
</label>
<Field
name="authenticationType"
as="select"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] flex-1 w-2/3"
>
<option value="PAP">PAP</option>
<option value="CHAP">CHAP</option>
<option value="none">None</option>
</Field>
</FormGroup>
<button
type="submit"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
>
{isSubmitting || modemMutation.isPending ? "Saving..." : "Save Modem settings"}
</button>
</Form>
)}
</Formik>
)}
</FormGroup>
<FormGroup>
<label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">
Password
</label>
<div className="flex gap-2 items-center relative mb-4">
<Field
id="password"
name="password"
type={showPwd ? "text" : "password"}
className="p-2 border border-gray-400 rounded-lg w-full"
placeholder="Enter Password"
/>
<FontAwesomeIcon
type="button"
className="absolute right-5 end-0"
onClick={() => setShowPwd((s) => !s)}
icon={showPwd ? faEyeSlash : faEye}
/>
</div>
</FormGroup>
<FormGroup>
<label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">
Password
</label>
<Field
name="authenticationType"
as="select"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] flex-1 w-2/3"
>
<option value="PAP">PAP</option>
<option value="CHAP">CHAP</option>
<option value="none">None</option>
</Field>
</FormGroup>
</>
)}
<button
type="submit"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
>
{isSubmitting || modemMutation.isPending ? "Saving..." : "Save Modem settings"}
</button>
</Form>
)}
</Formik>
</>
);
};

View File

@@ -5,6 +5,7 @@ import { useWifiAndModem } from "../../../hooks/useCameraWifiandModem";
import { useState } from "react";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { toast, Toaster } from "sonner";
const WiFiSettingsForm = () => {
const [showPwd, setShowPwd] = useState(false);
@@ -19,6 +20,13 @@ const WiFiSettingsForm = () => {
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 wifiConfig = {
id: "ModemAndWifiManager-wifi",
@@ -37,66 +45,71 @@ const WiFiSettingsForm = () => {
await wifiMutation.mutateAsync(wifiConfig);
};
return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
{({ isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2">
<FormGroup>
<label htmlFor="ssid" className="font-medium whitespace-nowrap md:w-2/3">
SSID
</label>
<Field
id="ssid"
name="ssid"
type="text"
className="p-1.5 border border-gray-400 rounded-lg"
placeholder="Enter SSID"
/>
</FormGroup>
<FormGroup>
<label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">
Password
</label>
<div className="flex gap-2 items-center relative mb-4">
<>
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
{({ isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2">
<FormGroup>
<label htmlFor="ssid" className="font-medium whitespace-nowrap md:w-2/3">
SSID
</label>
<Field
id="password"
name="password"
type={showPwd ? "text" : "password"}
className="p-2 border border-gray-400 rounded-lg w-full"
placeholder="Enter Password"
id="ssid"
name="ssid"
type="text"
className="p-1.5 border border-gray-400 rounded-lg"
placeholder="Enter SSID"
/>
<FontAwesomeIcon
type="button"
className="absolute right-5 end-0"
onClick={() => setShowPwd((s) => !s)}
icon={showPwd ? faEyeSlash : faEye}
/>
</div>
</FormGroup>
<FormGroup>
<label htmlFor="encryption" className="font-medium whitespace-nowrap md:w-2/3">
WPA/Encryption Type
</label>
<Field
id="encryption"
name="encryption"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] flex-1 w-2/3"
as="select"
</FormGroup>
<FormGroup>
<label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">
Password
</label>
<div className="flex gap-2 items-center relative mb-4">
<Field
id="password"
name="password"
type={showPwd ? "text" : "password"}
className="p-2 border border-gray-400 rounded-lg w-full"
placeholder="Enter Password"
validate={validatePassword}
/>
<FontAwesomeIcon
type="button"
className="absolute right-5 end-0"
onClick={() => setShowPwd((s) => !s)}
icon={showPwd ? faEyeSlash : faEye}
/>
</div>
</FormGroup>
<FormGroup>
<label htmlFor="encryption" className="font-medium whitespace-nowrap md:w-2/3">
WPA/Encryption Type
</label>
<Field
id="encryption"
name="encryption"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] flex-1 w-2/3"
as="select"
>
<option value="WPA2">WPA2</option>
<option value="WPA3">WPA3</option>
<option value="WEP">WEP</option>
<option value="None">None</option>
</Field>
</FormGroup>
<button
type="submit"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
>
<option value="WPA2">WPA2</option>
<option value="WPA3">WPA3</option>
<option value="WEP">WEP</option>
<option value="None">None</option>
</Field>
</FormGroup>
<button
type="submit"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5"
>
{isSubmitting || wifiMutation.isPending ? "Saving..." : " Save WiFi settings"}
</button>
</Form>
)}
</Formik>
{isSubmitting || wifiMutation.isPending ? "Saving..." : " Save WiFi settings"}
</button>
</Form>
)}
</Formik>
<Toaster />
</>
);
};

View File

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

View File

@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ReducedSightingType, SightingType } from "../../types/types";
import { BLANK_IMG, getSoundFileURL } from "../../utils/utils";
import type { HitKind, QueuedHit, ReducedSightingType, SightingType } from "../../types/types";
import { BLANK_IMG } from "../../utils/utils";
import NumberPlate from "../PlateStack/NumberPlate";
import Card from "../UI/Card";
import CardHeader from "../UI/CardHeader";
@@ -15,10 +15,11 @@ import NPED_CAT_C from "/NPED_Cat_C.svg";
import popup from "../../assets/sounds/ui/popup_open.mp3";
import notification from "../../assets/sounds/ui/notification.mp3";
import { useSound } from "react-sounds";
import { useNPEDContext } from "../../context/NPEDUserContext";
import { useIntegrationsContext } from "../../context/IntegrationsContext";
import { useSoundContext } from "../../context/SoundContext";
import Loading from "../UI/Loading";
import { checkIsHotListHit, getNPEDCategory } from "../../utils/utils";
import { useCachedSoundSrc } from "../../hooks/usecachedSoundSrc";
function useNow(tickMs = 1000) {
const [, setNow] = useState(() => Date.now());
@@ -39,24 +40,12 @@ type SightingHistoryProps = {
};
export default function SightingHistoryWidget({ className, title }: SightingHistoryProps) {
const [modalQueue, setModalQueue] = useState<QueuedHit[]>([]);
useNow(1000);
const { state } = useSoundContext();
const soundSrcNped = useMemo(() => {
if (state?.NPEDsound?.includes(".mp3") || state.NPEDsound?.includes(".wav")) {
const file = state.soundOptions?.find((item) => item.name === state.NPEDsound);
return file?.soundUrl ?? popup;
}
return getSoundFileURL(state.NPEDsound) ?? popup;
}, [state.NPEDsound, state.soundOptions]);
const soundSrcHotlist = useMemo(() => {
if (state?.hotlistSound?.includes(".mp3") || state.hotlistSound?.includes(".wav")) {
const file = state.soundOptions?.find((item) => item.name === state.hotlistSound);
return file?.soundUrl ?? notification;
}
return getSoundFileURL(state?.hotlistSound) ?? notification;
}, [state.hotlistSound, state.soundOptions]);
const { src: soundSrcHotlist } = useCachedSoundSrc(state?.hotlistSound, state?.soundOptions, notification);
const { src: soundSrcNped } = useCachedSoundSrc(state?.NPEDsound, state?.soundOptions, popup);
const { play: npedSound } = useSound(soundSrcNped, { volume: state.NPEDsoundVolume });
const { play: hotlistsound } = useSound(soundSrcHotlist, { volume: state.hotlistSoundVolume });
@@ -70,14 +59,28 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
isLoading,
} = useSightingFeedContext();
const { dispatch } = useAlertHitContext();
const { sessionStarted, setSessionList, sessionList } = useNPEDContext();
const { dispatch, state: alertState } = useAlertHitContext();
const { state: integrationState, dispatch: integrationDispatch } = useIntegrationsContext();
const sessionStarted = integrationState.sessionStarted;
const sessionPaused = integrationState.sessionPaused;
const processedRefs = useRef<Set<number | string>>(new Set());
const hasAutoOpenedRef = useRef(false);
const npedRef = useRef(false);
const enqueue = useCallback((sighting: SightingType, kind: HitKind) => {
const id = sighting.vrm ?? sighting.ref;
if (processedRefs.current.has(id)) return;
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 => {
return {
vrm: obj.vrm,
@@ -88,11 +91,12 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
useEffect(() => {
if (sessionStarted) {
if (!mostRecent) return;
if (sessionPaused) return;
const reducedMostRecent = reduceObject(mostRecent);
setSessionList([...sessionList, reducedMostRecent]);
integrationDispatch({ type: "ADD", payload: reducedMostRecent });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [mostRecent, sessionStarted, setSessionList]);
}, [mostRecent, sessionStarted]);
const onRowClick = useCallback(
(sighting: SightingType) => {
@@ -112,26 +116,15 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
const id = sighting.vrm;
if (processedRefs.current.has(id)) continue;
const isHot = checkIsHotListHit(sighting);
const cat = sighting?.metadata?.npedJSON?.["NPED CATEGORY"];
const isHotlistHit = checkIsHotListHit(sighting);
const npedcategory = sighting?.metadata?.npedJSON?.["NPED CATEGORY"];
const isNPED = npedcategory === "A" || npedcategory === "B" || npedcategory === "C";
if (cat === "A" || cat === "B" || cat === "C") {
npedSound();
setSelectedSighting(sighting);
setSightingModalOpen(true);
processedRefs.current.add(id);
break; // stop after one new open per render cycle
}
if (isHot) {
hotlistsound();
setSelectedSighting(sighting);
setSightingModalOpen(true);
processedRefs.current.add(id);
break;
if (isNPED || isHotlistHit) {
enqueue(sighting, isNPED ? "NPED" : "HOTLIST"); // enqueue ONLY
}
}
}, [rows, hotlistsound, npedSound, setSightingModalOpen, setSelectedSighting]);
}, [rows, enqueue]);
useEffect(() => {
rows?.forEach((obj) => {
@@ -164,22 +157,33 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
});
if (firstNPED) {
setSelectedSighting(firstNPED);
npedSound();
setSightingModalOpen(true);
enqueue(firstNPED, "NPED");
npedRef.current = true;
}
if (firstHot) {
setSelectedSighting(firstHot);
hotlistsound();
setSightingModalOpen(true);
enqueue(firstHot, "HOTLIST");
hasAutoOpenedRef.current = true;
}
}, [hotlistsound, npedSound, setSelectedSighting]);
}, [enqueue, hotlistsound, npedSound, rows, setSelectedSighting, setSightingModalOpen]);
useEffect(() => {
if (!isSightingModalOpen && modalQueue.length > 0) {
const next = modalQueue[0];
if (next.kind === "NPED") npedSound();
else hotlistsound();
setSelectedSighting(next.sighting);
setSightingModalOpen(true);
}
}, [isSightingModalOpen, npedSound, hotlistsound, setSelectedSighting, setSightingModalOpen, modalQueue]);
const handleClose = () => {
setSightingModalOpen(false);
setModalQueue((q) => q.slice(1));
};
return (
<>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -13,10 +13,12 @@ export const initialState: SoundState = {
{ 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 {
@@ -62,7 +64,11 @@ export function reducer(state: SoundState, action: SoundAction): SoundState {
...state,
hotlistSoundVolume: action.payload,
};
case "UPLOADEDSOUND":
return {
...state,
uploadedSound: action.payload,
};
default:
return state;
}

View File

@@ -0,0 +1,75 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { useEffect } from "react";
import { toast } from "sonner";
import type { InitialValuesForm } from "../types/types";
import { CAM_BASE } from "../utils/config";
const getBackOfficeConfig = async (format: string) => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher-${format?.toLowerCase()}`);
if (!response.ok) throw new Error("Cannot get Back Office configuration");
return response.json();
};
const updateBackOfficeConfig = async (data: InitialValuesForm) => {
const updateConfigPayload = {
id: `Dispatcher-${data.format.toLowerCase()}`,
fields: [
{
property: "propBackofficeURL",
value: data.backOfficeURL,
},
{
property: "propConnectTimeoutSeconds",
value: data.connectTimeoutSeconds,
},
{
property: "propPassword",
value: data.password,
},
{
property: "propReadTimeoutSeconds",
value: data.readTimeoutSeconds,
},
{
property: "propUsername",
value: data.username,
},
],
};
const response = await fetch(`${CAM_BASE}/api/update-config`, {
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 response = await fetch(`${camBase}/api/blackboard`, {
signal: AbortSignal.timeout(500),
signal: AbortSignal.timeout(300000),
});
if (!response.ok) {
throw new Error("Failed to fetch blackboard data");
@@ -17,7 +17,7 @@ const getAllBlackboardData = async () => {
};
const viewBlackboardData = async (options: CameraBlackBoardOptions) => {
const response = await fetch(`/${camBase}api/blackboard`, {
const response = await fetch(`${camBase}/api/blackboard`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(options),

View File

@@ -8,7 +8,7 @@ const fetchCameraSideConfig = async ({ queryKey }: { queryKey: string[] }) => {
const [, cameraSide] = queryKey;
const fetchUrl = `${base_url}/fetch-config?id=${cameraSide}`;
const response = await fetch(fetchUrl, {
signal: AbortSignal.timeout(500),
signal: AbortSignal.timeout(300000),
});
if (!response.ok) throw new Error("cannot react cameraSide ");
return response.json();
@@ -31,7 +31,7 @@ const updateCamerasideConfig = async (data: { id: string | number; friendlyName:
method: "POST",
body: JSON.stringify(updateConfigPayload),
});
if (!response.ok) throw new Error("Feature unavailable: Coming soon");
if (!response.ok) throw new Error("Please make sure fields are filled in correctly");
};
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 { useEffect } from "react";
import { toast } from "sonner";
import type { BearerTypeFieldType, InitialValuesForm } from "../types/types";
import type { BearerTypeFieldType, OptionalBOF2Constants, OptionalBOF2LaneIDs } from "../types/types";
const getDispatcherConfig = async () => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher`);
@@ -18,14 +18,13 @@ const updateDispatcherConfig = async (data: BearerTypeFieldType) => {
property: "propEnabled",
value: data.enabled,
},
// Todo: figure out how to add verbose conditionally
{
property: "propFormat",
value: data.format,
},
],
};
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher`, {
const response = await fetch(`${CAM_BASE}/api/update-config`, {
method: "POST",
body: JSON.stringify(updateConfigPayload),
});
@@ -33,43 +32,68 @@ const updateDispatcherConfig = async (data: BearerTypeFieldType) => {
return response.json();
};
const getBackOfficeConfig = async () => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher-json`);
if (!response.ok) throw new Error("Cannot get Back Office configuration");
return response.json();
};
const updateBackOfficeConfig = async (data: InitialValuesForm) => {
const updateConfigPayload = {
id: "Dispatcher-json",
const updateBackOfficeDispatcher = async (data: OptionalBOF2Constants) => {
const bof2ContantsPayload = {
id: "Dispatcher-bof2-constants",
fields: [
{
property: "propBackofficeURL",
value: data.backOfficeURL,
property: "propFeedIdentifier",
value: data?.FFID,
},
{
property: "propConnectTimeoutSeconds",
value: data.connectTimeoutSeconds,
property: "propSourceIdentifier",
value: data?.SCID,
},
{
property: "propPassword",
value: data.password,
property: "propTimeZoneType",
value: data?.timestampSource,
},
{
property: "propReadTimeoutSeconds",
value: data.readTimeoutSeconds,
},
{
property: "propUsername",
value: data.username,
property: "propGpsFormat",
value: data?.GPSFormat,
},
],
};
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher-json`, {
const response = await fetch(`${CAM_BASE}/api/update-config`, {
method: "POST",
body: JSON.stringify(updateConfigPayload),
body: JSON.stringify(bof2ContantsPayload),
});
if (!response.ok) throw new Error("Cannot update Back Office configuration");
if (!response.ok) throw new Error("Cannot update dispatcher configuration");
return response.json();
};
const getBof2DispatcherData = async () => {
const response = await fetch(`${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();
};
@@ -79,45 +103,55 @@ export const useCameraOutput = () => {
queryFn: getDispatcherConfig,
});
const backOfficeQuery = useQuery({
queryKey: ["backoffice"],
queryFn: getBackOfficeConfig,
});
const dispatcherMutation = useMutation({
mutationFn: updateDispatcherConfig,
mutationKey: ["dispatcherUpdate"],
onError: (error) => toast.error(error.message),
onSuccess: (data) => {
if (data) {
toast.success("Settings successfully updated");
toast.success("Settings successfully updated", { id: "dispatchSettings" });
}
},
});
const backOfficeMutation = useMutation({
mutationKey: ["backOfficeUpdate"],
mutationFn: updateBackOfficeConfig,
onError: (error) => toast.error(error.message),
const backOfficeDispatcherMutation = useMutation({
mutationKey: ["backofficedDispatcher"],
mutationFn: updateBackOfficeDispatcher,
onSuccess: (data) => {
if (data) {
toast.success("Settings successfully updated");
toast.success("Settings successfully updated", { id: "dispatchSettings" });
}
},
});
const bof2LandMutation = useMutation({
mutationKey: ["updateBOF2LaneId"],
mutationFn: updateBOF2LaneId,
});
const laneIdQuery = useQuery({
queryKey: ["getBOF2LaneId"],
queryFn: getBOF2LaneId,
});
useEffect(() => {
if (dispatcherQuery.isError) toast.error(dispatcherQuery.error.message);
}, [dispatcherQuery?.error?.message, dispatcherQuery.isError]);
useEffect(() => {
if (backOfficeQuery.isError) toast.error(backOfficeQuery.error.message);
}, [backOfficeQuery?.error?.message, backOfficeQuery.isError]);
return {
dispatcherQuery,
dispatcherMutation,
backOfficeQuery,
backOfficeMutation,
backOfficeDispatcherMutation,
bof2LandMutation,
laneIdQuery,
};
};
export const useGetDispatcherConfig = () => {
const bof2ConstantsQuery = useQuery({
queryKey: ["getBof2DispatcherData"],
queryFn: getBof2DispatcherData,
});
return { bof2ConstantsQuery };
};

View File

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

View File

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

View File

@@ -0,0 +1,45 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import { toast } from "sonner";
import { getOrCacheBlob } from "../utils/cacheSound";
const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : CAM_BASE;
type UseFileUploadProps = {
queryKey?: string[];
};
const uploadFile = async (file: File) => {
const form = new FormData();
form.append("upload", file, file.name);
const response = await fetch(`${camBase}/upload/file-upload/3`, {
method: "POST",
body: form,
});
if (!response.ok) {
throw new Error("Cannot reach upload file endpoint");
}
return response.text();
};
const getUploadFiles = async ({ queryKey }: { queryKey: string[] }) => {
const [, fileName] = queryKey;
const url = fileName;
return getOrCacheBlob(url);
};
export const useFileUpload = ({ queryKey }: UseFileUploadProps) => {
const query = useQuery({
queryKey: ["getUploadFiles", ...(queryKey ?? [])],
queryFn: () => getUploadFiles({ queryKey: ["getUploadFiles", ...(queryKey ?? [])] }),
enabled: !!queryKey,
});
const mutation = useMutation({
mutationFn: (file: File) => uploadFile(file),
mutationKey: ["uploadFile"],
onError: (err) => toast.error(err ? err.message : ""),
onSuccess: async (msg) => toast.success(msg),
});
return { query: queryKey ? query : undefined, mutation };
};

View File

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

View File

@@ -0,0 +1,153 @@
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,34 +3,75 @@ import { useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
const apiUrl = CAM_BASE;
// const fetch_url = `http://100.82.205.44/Colour-preview`;
async function fetchSnapshot(cameraSide: string) {
async function fetchSnapshot(cameraSide: string): Promise<Blob> {
const response = await fetch(`${apiUrl}/${cameraSide}-preview`, {
signal: AbortSignal.timeout(500),
signal: AbortSignal.timeout(300000),
cache: "no-store",
});
if (!response.ok) {
throw new Error("Cannot reach endpoint");
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;
}
return await response.blob();
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 latestUrlRef = useRef<string | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const imageRef = useRef<HTMLImageElement | null>(null);
const latestBitmapRef = useRef<ImageBitmap | null>(null);
const drawImage = useCallback(() => {
// Redraw helper; always draws the current bitmap if available
const draw = useCallback(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d");
const img = imageRef.current;
if (!canvas || !ctx || !img) return;
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const bmp = latestBitmapRef.current;
if (!canvas || !bmp) return;
drawBitmapToCanvas(canvas, bmp);
}, []);
const {
@@ -39,43 +80,82 @@ export function useGetOverviewSnapshot(side: string) {
error,
isPending,
} = useQuery({
queryKey: ["overviewSnapshot"],
queryKey: ["overviewSnapshot", side],
queryFn: () => fetchSnapshot(side),
// Poll ~4 fps when visible; pause when tab hidden
refetchInterval: () => (document.visibilityState === "visible" ? 250 : false),
refetchOnWindowFocus: false,
refetchInterval: 250,
// 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;
const imgUrl = URL.createObjectURL(snapshotBlob);
const img = new Image();
imageRef.current = img;
(async () => {
try {
const bitmap = await createImageBitmap(snapshotBlob);
if (cancelled) {
bitmap.close();
return;
}
img.onload = () => {
drawImage();
};
img.src = imgUrl;
// Dispose previous bitmap to free memory
if (latestBitmapRef.current) {
latestBitmapRef.current.close();
}
latestBitmapRef.current = bitmap;
if (latestUrlRef.current) {
URL.revokeObjectURL(latestUrlRef.current);
}
latestUrlRef.current = imgUrl;
// Draw now (and again on next resize)
draw();
} catch {
// noop — fetch handler surfaces the main error path
}
})();
return () => {
if (latestUrlRef.current) {
URL.revokeObjectURL(latestUrlRef.current);
latestUrlRef.current = null;
}
cancelled = true;
};
}, [snapshotBlob, drawImage]);
}, [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]);
useEffect(() => {
window.addEventListener("resize", drawImage);
return () => {
window.removeEventListener("resize", drawImage);
};
}, [drawImage]);
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]);
return { canvasRef, isError, error, isPending };
// 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

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

View File

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

View File

@@ -0,0 +1,19 @@
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,11 +1,41 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { sendBlobFileUpload } from "../components/SettingForms/System/Upload";
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 { 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 = () => {
const uploadSettingsMutation = useMutation({
@@ -51,3 +81,20 @@ export const useSystemConfig = () => {
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

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

View File

@@ -31,3 +31,9 @@ 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";
const FrontCamera = () => {
const [zoomLevel, setZoomLevel] = useState<number>(1);
const [zoomLevel, setZoomLevel] = useState<number | undefined>(1);
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">
<OverviewVideoContainer

View File

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

View File

@@ -41,6 +41,7 @@ export type CameraSettingValues = {
userName: string;
password: string;
id: number | string;
mode: string;
};
export type CameraSettingErrorValues = Partial<Record<keyof CameraSettingValues, string>>;
@@ -48,15 +49,18 @@ export type CameraSettingErrorValues = Partial<Record<keyof CameraSettingValues,
export type BearerTypeFieldType = {
format: string;
enabled: boolean;
verbose: boolean;
verbose?: boolean;
};
export type InitialValuesForm = {
format: string;
backOfficeURL: string;
username: string;
password: string;
connectTimeoutSeconds: number;
readTimeoutSeconds: number;
overviewQuality?: string;
cropSizeFactor?: string;
};
export type InitialValuesFormErrors = {
@@ -67,6 +71,20 @@ export type InitialValuesFormErrors = {
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 = {
frontId: string;
username: string | undefined;
@@ -149,6 +167,13 @@ export type SystemValues = {
sntpInterval: number;
timeZone: string;
softwareUpdate?: File | null;
serverPrimary?: string;
serverSecondary?: string;
};
export type DNSSettingsType = {
serverPrimary?: string;
serverSecondary?: string;
};
export type SystemValuesErrors = {
@@ -294,6 +319,7 @@ export type SoundUploadValue = {
soundFileName?: string;
soundFile?: File | null;
soundUrl?: string;
uploadedAt?: number;
};
export type SoundState = {
@@ -305,6 +331,7 @@ export type SoundState = {
sightingVolume: number;
NPEDsoundVolume: number;
hotlistSoundVolume: number;
uploadedSound?: Blob | null;
};
type UpdateAction = {
@@ -331,7 +358,12 @@ type VolumeAction = {
payload: number;
};
export type SoundAction = UpdateAction | AddAction | VolumeAction;
type UploadedState = {
type: "UPLOADEDSOUND";
payload: Blob | undefined;
};
export type SoundAction = UpdateAction | AddAction | VolumeAction | UploadedState;
export type WifiSettingValues = {
ssid: string;
password: string;
@@ -359,6 +391,7 @@ export type ModemConfig = {
export type ZoomInOptions = {
camera: string;
multiplier: number;
multiplierText?: string;
};
export type zoomConfig = {
@@ -371,3 +404,27 @@ export type ModemSettingsType = {
password: string;
authenticationType: string;
};
export type HitKind = "NPED" | "HOTLIST";
export type QueuedHit = {
id: number | string;
sighting: SightingType;
kind: HitKind;
};
export type DedupedSightings = ReducedSightingType[];
export type NPEDSTATE = {
sessionStarted: boolean;
sessionList: ReducedSightingType[];
sessionPaused: boolean;
savedSightings: DedupedSightings;
npedUser: NPEDUser;
};
export type NPEDACTION = {
type: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload: any;
};

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

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

View File

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

View File

@@ -5,7 +5,7 @@ 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";
export function getSoundFileURL(name: string) {
@@ -17,6 +17,7 @@ export function getSoundFileURL(name: string) {
warning: warning,
ding: ding,
shutter: shutter,
attention: attention,
};
return sounds[name] ?? null;
}
@@ -147,11 +148,39 @@ export const checkIsHotListHit = (sigthing: SightingType | null) => {
};
export function getHotlistName(obj: HotlistMatches | undefined) {
if (!obj || Object.values(obj).includes(false)) return;
if (!obj) return;
const keys = Object.keys(obj);
return keys;
const hotlistNames = Object.entries(obj)
.filter(([, value]) => value === true)
.map(([key]) => key);
return hotlistNames;
}
export const getNPEDCategory = (r?: SightingType | null) =>
r?.metadata?.npedJSON?.["NPED CATEGORY"] as "A" | "B" | "C" | undefined;
r?.metadata?.npedJSON?.["NPED CATEGORY"] as "A" | "B" | "C" | "D" | undefined;
export const zoomMapping = (zoomLevel: number | undefined) => {
switch (zoomLevel) {
case 1:
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;
}
};

View File

@@ -2267,6 +2267,11 @@ uri-js@^4.2.2:
dependencies:
punycode "^2.1.0"
use-debounce@^10.0.6:
version "10.0.6"
resolved "https://registry.yarnpkg.com/use-debounce/-/use-debounce-10.0.6.tgz#e05060a5e561432ec740c653698f3eb162bd28ec"
integrity sha512-C5OtPyhAZgVoteO9heXMTdW7v/IbFI+8bSVKYCJrSmiWWCLsbUxiBSp4t9v0hNBTGY97bT72ydDIDyGSFWfwXg==
vite@^7.1.0:
version "7.1.2"
resolved "https://registry.npmjs.org/vite/-/vite-7.1.2.tgz"