Compare commits

...

25 Commits

Author SHA1 Message Date
dab49fd99c Refactored routing components for better organization and maintainability 2025-12-17 16:07:01 +00:00
775fce7900 Refactor camera feed handling to support dynamic camera IDs and improve context management 2025-12-17 14:19:23 +00:00
cc8b3a5691 Merge pull request 'more accurate system status' (#25) from bugfix/dashboard into develop
Reviewed-on: #25
2025-12-17 09:46:26 +00:00
71ce2a9f91 - removed console.log
- fixed issue for more extensive check into tags to be more accurate
2025-12-17 09:44:14 +00:00
3fbafbbcc7 - minor bugfixes
- added developer modal for viewing app data
2025-12-12 12:18:17 +00:00
b38fbe132b Merge pull request 'develop' (#24) from develop into main
Reviewed-on: #24
2025-12-12 08:33:36 +00:00
9489fe2d6a Merge branch 'main' into develop 2025-12-12 08:33:27 +00:00
3353ad6f8b - updated paths and code splitting config 2025-12-12 08:32:06 +00:00
d1995f0a9f - updated main endpoint end point and added flexibility for camera navigation 2025-12-11 10:52:13 +00:00
e395777ae9 - added modal for entry and exit sightings and plate patches 2025-12-10 22:32:30 +00:00
ba93753df7 Merge pull request 'feature/ws-Camera' (#23) from feature/ws-Camera into develop
Reviewed-on: #23
2025-12-10 14:09:24 +00:00
eb45eabde9 - improved magnification level text
- removed magnification level
2025-12-10 14:08:44 +00:00
10e2644666 - improved zoom while clicking on on image to zoom 2025-12-10 13:09:07 +00:00
0ff43d975d - added digital zoom functionality on fixed location via web sockets 2025-12-10 10:30:32 +00:00
f0f311f316 Merge pull request 'develop' (#22) from develop into main
Reviewed-on: #22
2025-12-09 15:54:52 +00:00
c73c5f4187 - adjusted button on settings 2025-12-09 15:53:20 +00:00
0378667fe3 Merge pull request '- Enhanced responsiveness and layout adjustments across various components' (#21) from enhancement/responsive into develop
Reviewed-on: #21
2025-12-09 14:09:06 +00:00
632962aeaf - Enhanced responsiveness and layout adjustments across various components 2025-12-09 14:07:51 +00:00
e6f4131c1e Merge pull request 'Add zoom mode functionality and refactor video feed hooks' (#20) from feature/digitalZoom into develop
Reviewed-on: #20
2025-12-09 13:04:10 +00:00
06fe99b550 Merge branch 'develop' into feature/digitalZoom 2025-12-09 13:04:03 +00:00
328c61cf98 Merge pull request '- implement camera zoom controls and state management' (#19) from feature/cameraControls-2 into develop
Reviewed-on: #19
2025-12-09 13:03:42 +00:00
a9f6c4a4ad Merge branch 'develop' into feature/cameraControls-2 2025-12-09 13:03:34 +00:00
59e09b7a8d Merge pull request '- need endpoint for include and exclude' (#18) from feature/includeoption into develop
Reviewed-on: #18
2025-12-09 13:03:08 +00:00
c6a336389b Add zoom mode functionality and refactor video feed hooks
- Implemented zoom mode in RegionSelector for digital zooming.
- Updated VideoFeedGridPainter to handle zoom interactions.
- Refactored useGetVideoFeed to support target detection and video feed queries based on mode.
- Enhanced useCreateVideoSnapshot to manage snapshots during zoom mode.
2025-12-09 12:39:03 +00:00
b93b446614 - implement camera zoom controls and state management 2025-12-09 08:47:21 +00:00
49 changed files with 1215 additions and 347 deletions

View File

@@ -1,7 +1,7 @@
{ {
"name": "bayiq-ui", "name": "bayiq-ui",
"private": true, "private": true,
"version": "0.0.0", "version": "1.0.1",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -21,13 +21,15 @@
"clsx": "^2.1.1", "clsx": "^2.1.1",
"formik": "^2.4.9", "formik": "^2.4.9",
"konva": "^10.0.11", "konva": "^10.0.11",
"rc-slider": "^11.1.9",
"react": "^19.2.0", "react": "^19.2.0",
"react-dom": "^19.2.0", "react-dom": "^19.2.0",
"react-konva": "^19.2.0", "react-konva": "^19.2.0",
"react-modal": "^3.16.3", "react-modal": "^3.16.3",
"react-tabs": "^6.1.0", "react-tabs": "^6.1.0",
"react-use-websocket": "3.0.0", "react-use-websocket": "3.0.0",
"sonner": "^2.0.7" "sonner": "^2.0.7",
"use-debounce": "^10.0.6"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.1", "@eslint/js": "^9.39.1",

View File

@@ -0,0 +1,12 @@
// Camera configuration - add more cameras here as needed
export const CAMERA_IDS = ["A", "B", "C"] as const;
export type CameraID = (typeof CAMERA_IDS)[number];
export const DEFAULT_REGIONS = [
{ name: "Bay 1", brushColour: "#ff0000" },
{ name: "Bay 2", brushColour: "#00ff00" },
{ name: "Bay 3", brushColour: "#0400ff" },
{ name: "Bay 4", brushColour: "#ffff00" },
{ name: "Bay 5", brushColour: "#fc35db" },
];

View File

@@ -1,5 +1,10 @@
import { CAMBASE_WS } from "../../utils/config";
export const wsConfig = { export const wsConfig = {
infoBar: "ws://100.115.125.56/websocket-infobar", infoBar: `${CAMBASE_WS}/websocket-infobar`,
cameraFeedA: `${CAMBASE_WS}/websocket-CameraA-live-video`,
cameraFeedB: `${CAMBASE_WS}/websocket-CameraB-live-video`,
cameraFeedC: `${CAMBASE_WS}/websocket-CameraC-live-video`,
}; };
export type SocketKey = keyof typeof wsConfig; export type SocketKey = keyof typeof wsConfig;

View File

@@ -1,15 +1,23 @@
import { createContext, useContext } from "react"; import { createContext, useContext } from "react";
import { ReadyState } from "react-use-websocket"; import { ReadyState } from "react-use-websocket";
import type { InfoBarData } from "../../types/types"; import type { CameraZoomData, InfoBarData } from "../../types/types";
type InfoSocketState = { type InfoSocketState = {
data: InfoBarData | null; data: InfoBarData | null;
readyState: ReadyState; readyState: ReadyState;
sendJson: (msg: unknown) => void; sendJson: (msg: unknown) => void;
send?: (msg: string) => void;
};
type CameraSocketState = {
data: CameraZoomData | null;
readyState: ReadyState;
send: (msg: string) => void;
}; };
export type WebSocketConextValue = { export type WebSocketConextValue = {
info: InfoSocketState; info: InfoSocketState;
cameraFeed: CameraSocketState;
}; };
export const WebsocketContext = createContext<WebSocketConextValue | null>(null); export const WebsocketContext = createContext<WebSocketConextValue | null>(null);
@@ -21,3 +29,4 @@ const useWebSocketContext = () => {
}; };
export const useInfoSocket = () => useWebSocketContext().info; export const useInfoSocket = () => useWebSocketContext().info;
export const useCameraFeedSocket = () => useWebSocketContext().cameraFeed;

View File

@@ -4,8 +4,12 @@ import { initialState, reducer } from "../reducers/cameraFeedReducer";
import { useBlackBoard } from "../../hooks/useBlackBoard"; import { useBlackBoard } from "../../hooks/useBlackBoard";
import type { CameraFeedState } from "../../types/types"; import type { CameraFeedState } from "../../types/types";
import { CAMERA_IDS } from "../config/cameraConfig";
import CameraZoomFetcher from "./CameraZoomFetcher";
export const CameraFeedProvider = ({ children }: { children: ReactNode }) => { export const CameraFeedProvider = ({ children }: { children: ReactNode }) => {
const { blackboardMutation } = useBlackBoard(); const { blackboardMutation } = useBlackBoard();
const [state, dispatch] = useReducer(reducer, initialState); const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => { useEffect(() => {
@@ -18,16 +22,25 @@ export const CameraFeedProvider = ({ children }: { children: ReactNode }) => {
const cameraFeedData: CameraFeedState = result.result; const cameraFeedData: CameraFeedState = result.result;
const recontructedState = { const recontructedState = {
...cameraFeedData, ...cameraFeedData,
paintedCells: { paintedCells: CAMERA_IDS.reduce(
A: new Map(cameraFeedData.paintedCells.A), (acc, id) => {
B: new Map(cameraFeedData.paintedCells.B), acc[id] = new Map(cameraFeedData.paintedCells[id]);
C: new Map(cameraFeedData.paintedCells.C), return acc;
}, },
{} as typeof cameraFeedData.paintedCells,
),
}; };
dispatch({ type: "SET_CAMERA_FEED_DATA", cameraState: recontructedState }); dispatch({ type: "SET_CAMERA_FEED_DATA", cameraState: recontructedState });
}; };
fetchBlackBoardData(); fetchBlackBoardData();
}, []); }, []);
return <CameraFeedContext.Provider value={{ state, dispatch }}>{children}</CameraFeedContext.Provider>; return (
<CameraFeedContext.Provider value={{ state, dispatch }}>
{CAMERA_IDS.map((cameraId) => (
<CameraZoomFetcher key={cameraId} cameraId={cameraId} dispatch={dispatch} />
))}
{children}
</CameraFeedContext.Provider>
);
}; };

View File

@@ -0,0 +1,31 @@
import { useEffect } from "react";
import { useCameraZoom } from "../../features/cameras/hooks/useCameraZoom";
import type { CameraFeedAction } from "../../types/types";
import type { CameraID } from "../config/cameraConfig";
type CameraZoomFetcherProps = {
cameraId: CameraID;
dispatch: (action: CameraFeedAction) => void;
};
const CameraZoomFetcher = ({ cameraId, dispatch }: CameraZoomFetcherProps) => {
const { cameraZoomQuery } = useCameraZoom(cameraId);
useEffect(() => {
const fetchZoomLevel = async () => {
const result = await cameraZoomQuery.refetch();
if (result.data && typeof result.data.zoomLevel === "number") {
dispatch({
type: "SET_ZOOM_LEVEL",
payload: { cameraFeedID: cameraId, zoomLevel: result.data.zoomLevel },
});
}
};
fetchZoomLevel();
}, [cameraId, cameraZoomQuery, dispatch]);
return null;
};
export default CameraZoomFetcher;

View File

@@ -2,15 +2,29 @@ import { useEffect, useMemo, useState, type ReactNode } from "react";
import { WebsocketContext, type WebSocketConextValue } from "../context/WebSocketContext"; import { WebsocketContext, type WebSocketConextValue } from "../context/WebSocketContext";
import useWebSocket from "react-use-websocket"; import useWebSocket from "react-use-websocket";
import { wsConfig } from "../config/wsconfig"; import { wsConfig } from "../config/wsconfig";
import type { InfoBarData } from "../../types/types"; import type { CameraZoomData, InfoBarData } from "../../types/types";
import { CAMERA_IDS } from "../config/cameraConfig";
import { CAMBASE_WS } from "../../utils/config";
import { useCameraFeedContext } from "../context/CameraFeedContext";
type WebSocketProviderProps = { type WebSocketProviderProps = {
children: ReactNode; children: ReactNode;
}; };
export const WebSocketProvider = ({ children }: WebSocketProviderProps) => { export const WebSocketProvider = ({ children }: WebSocketProviderProps) => {
const { state } = useCameraFeedContext();
const [systemData, setSystemData] = useState<InfoBarData | null>(null); const [systemData, setSystemData] = useState<InfoBarData | null>(null);
const [socketData, setSocketData] = useState<CameraZoomData | null>(null);
const infoSocket = useWebSocket(wsConfig.infoBar, { share: true, shouldReconnect: () => true }); const infoSocket = useWebSocket(wsConfig.infoBar, { share: true, shouldReconnect: () => true });
const sockets = CAMERA_IDS.reduce(
(acc, id) => {
acc[id] = `${CAMBASE_WS}/websocket-Camera${id}-live-video`;
return acc;
},
{} as Record<string, string>,
);
const cameraFeedID = state.cameraFeedID;
const cameraFeed = useWebSocket(sockets[cameraFeedID], { share: true, shouldReconnect: () => true });
useEffect(() => { useEffect(() => {
async function parseData() { async function parseData() {
@@ -19,9 +33,15 @@ export const WebSocketProvider = ({ children }: WebSocketProviderProps) => {
const data = JSON.parse(text); const data = JSON.parse(text);
setSystemData(data); setSystemData(data);
} }
if (cameraFeed.lastMessage) {
const message = cameraFeed.lastMessage;
const data = await message?.data.text();
const parsedData: CameraZoomData = JSON.parse(data || "");
setSocketData(parsedData);
}
} }
parseData(); parseData();
}, [infoSocket.lastMessage]); }, [cameraFeed.lastMessage, infoSocket.lastMessage]);
const value = useMemo<WebSocketConextValue>( const value = useMemo<WebSocketConextValue>(
() => ({ () => ({
@@ -30,8 +50,21 @@ export const WebSocketProvider = ({ children }: WebSocketProviderProps) => {
readyState: infoSocket.readyState, readyState: infoSocket.readyState,
sendJson: infoSocket.sendJsonMessage, sendJson: infoSocket.sendJsonMessage,
}, },
cameraFeed: {
data: socketData,
readyState: cameraFeed.readyState,
send: cameraFeed.sendMessage,
},
}), }),
[infoSocket.readyState, infoSocket.sendJsonMessage, systemData], [
cameraFeed.readyState,
cameraFeed.sendMessage,
infoSocket.readyState,
infoSocket.sendJsonMessage,
socketData,
systemData,
],
); );
return <WebsocketContext.Provider value={value}>{children}</WebsocketContext.Provider>; return <WebsocketContext.Provider value={value}>{children}</WebsocketContext.Provider>;

View File

@@ -1,42 +1,38 @@
import type { CameraFeedAction, CameraFeedState, PaintedCell } from "../../types/types"; import type { CameraFeedAction, CameraFeedState, PaintedCell } from "../../types/types";
import { CAMERA_IDS, DEFAULT_REGIONS, type CameraID } from "../config/cameraConfig";
export const initialState: CameraFeedState = { export const initialState: CameraFeedState = {
cameraFeedID: "A", cameraFeedID: CAMERA_IDS[0],
paintedCells: { paintedCells: CAMERA_IDS.reduce(
A: new Map<string, PaintedCell>(), (acc, id) => {
B: new Map<string, PaintedCell>(), acc[id] = new Map<string, PaintedCell>();
C: new Map<string, PaintedCell>(), return acc;
}, },
regionsByCamera: { {} as Record<string, Map<string, PaintedCell>>,
A: [ ),
{ name: "Bay 1", brushColour: "#ff0000" }, regionsByCamera: CAMERA_IDS.reduce(
{ name: "Bay 2", brushColour: "#00ff00" }, (acc, id) => {
{ name: "Bay 3", brushColour: "#0400ff" }, acc[id] = DEFAULT_REGIONS;
{ name: "Bay 4", brushColour: "#ffff00" }, return acc;
{ name: "Bay 5", brushColour: "#fc35db" }, },
], {} as Record<string, { name: string; brushColour: string }[]>,
B: [ ),
{ name: "Bay 1", brushColour: "#ff0000" },
{ name: "Bay 2", brushColour: "#00ff00" },
{ name: "Bay 3", brushColour: "#0400ff" },
{ name: "Bay 4", brushColour: "#ffff00" },
{ name: "Bay 5", brushColour: "#fc35db" },
],
C: [
{ name: "Bay 1", brushColour: "#ff0000" },
{ name: "Bay 2", brushColour: "#00ff00" },
{ name: "Bay 3", brushColour: "#0400ff" },
{ name: "Bay 4", brushColour: "#ffff00" },
{ name: "Bay 5", brushColour: "#fc35db" },
],
},
selectedRegionIndex: 0, selectedRegionIndex: 0,
modeByCamera: { modeByCamera: CAMERA_IDS.reduce(
A: "painter", (acc, id) => {
B: "painter", acc[id] = "painter";
C: "painter", return acc;
}, },
{} as Record<CameraID, string>,
),
zoomLevel: CAMERA_IDS.reduce(
(acc, id) => {
acc[id] = 1;
return acc;
},
{} as Record<CameraID, number>,
),
}; };
export function reducer(state: CameraFeedState, action: CameraFeedAction) { export function reducer(state: CameraFeedState, action: CameraFeedAction) {
@@ -106,7 +102,14 @@ export function reducer(state: CameraFeedState, action: CameraFeedAction) {
return { return {
...initialState, ...initialState,
}; };
case "SET_ZOOM_LEVEL":
return {
...state,
zoomLevel: {
...state.zoomLevel,
[action.payload.cameraFeedID]: action.payload.zoomLevel,
},
};
default: default:
return state; return state;
} }

View File

@@ -12,7 +12,7 @@ const CameraGrid = () => {
return ( return (
<> <>
<div className="grid grid-cols-1 md:grid-cols-3 md:gap-4 p-4 h-screen max-h-screen"> <div className="grid grid-cols-1 md:grid-cols-3 md:gap-4 p-4">
<div className="col-span-2 flex flex-col gap-4"> <div className="col-span-2 flex flex-col gap-4">
<div className=""> <div className="">
<VideoFeedGridPainter /> <VideoFeedGridPainter />

View File

@@ -2,6 +2,7 @@ import { Tabs, Tab, TabList, TabPanel } from "react-tabs";
import { useEffect } from "react"; import { useEffect } from "react";
import { useCameraFeedContext } from "../../../../app/context/CameraFeedContext"; import { useCameraFeedContext } from "../../../../app/context/CameraFeedContext";
import RegionSelector from "./RegionSelector"; import RegionSelector from "./RegionSelector";
import CameraControls from "./cameraControls/CameraControls";
type CameraPanelProps = { type CameraPanelProps = {
tabIndex: number; tabIndex: number;
@@ -27,6 +28,7 @@ const CameraPanel = ({ tabIndex, isResetAllModalOpen, handleClose, setIsResetMod
return "B"; return "B";
case 2: case 2:
return "C"; return "C";
//Add more cases if more cameras are added
default: default:
return "A"; return "A";
} }
@@ -54,10 +56,7 @@ const CameraPanel = ({ tabIndex, isResetAllModalOpen, handleClose, setIsResetMod
/> />
</TabPanel> </TabPanel>
<TabPanel> <TabPanel>
<div className="p-4"> <CameraControls cameraFeedID={cameraFeedID} />
<h2 className="text-lg font-semibold mb-4">Camera Controls</h2>
<p>Controls for camera {cameraFeedID} will go here.</p>
</div>
</TabPanel> </TabPanel>
</Tabs> </Tabs>
); );

View File

@@ -2,6 +2,7 @@ import Card from "../../../../ui/Card";
import { Tab, Tabs, TabList, TabPanel } from "react-tabs"; import { Tab, Tabs, TabList, TabPanel } from "react-tabs";
import "react-tabs/style/react-tabs.css"; import "react-tabs/style/react-tabs.css";
import CameraPanel from "./CameraPanel"; import CameraPanel from "./CameraPanel";
import { CAMERA_IDS } from "../../../../app/config/cameraConfig";
type CameraSettingsProps = { type CameraSettingsProps = {
setTabIndex: (tabIndex: number) => void; setTabIndex: (tabIndex: number) => void;
@@ -12,48 +13,33 @@ type CameraSettingsProps = {
}; };
const CameraSettings = ({ const CameraSettings = ({
tabIndex,
setTabIndex, setTabIndex,
isResetAllModalOpen, isResetAllModalOpen,
handleClose, handleClose,
setIsResetModalOpen, setIsResetModalOpen,
}: CameraSettingsProps) => { }: CameraSettingsProps) => {
return ( return (
<Card className="p-4 w-full h-full max-h-screen"> <Card className="p-4 w-full h-full ">
<Tabs <Tabs
selectedTabClassName="bg-gray-300 text-gray-900 font-semibold border-none rounded-sm mb-1" selectedTabClassName="bg-gray-300 text-gray-900 font-semibold border-none rounded-sm mb-1"
className="react-tabs" className="react-tabs"
onSelect={(index) => setTabIndex(index)} onSelect={(index) => setTabIndex(index)}
> >
<TabList> <TabList>
<Tab>Camera A</Tab> {CAMERA_IDS.map((id) => (
<Tab>Camera B</Tab> <Tab key={id}>Camera {id}</Tab>
<Tab>Camera C</Tab> ))}
</TabList> </TabList>
<TabPanel> {CAMERA_IDS.map((id, index) => (
<CameraPanel <TabPanel key={id}>
tabIndex={tabIndex} <CameraPanel
isResetAllModalOpen={isResetAllModalOpen} tabIndex={index}
handleClose={handleClose} isResetAllModalOpen={isResetAllModalOpen}
setIsResetModalOpen={setIsResetModalOpen} handleClose={handleClose}
/> setIsResetModalOpen={setIsResetModalOpen}
</TabPanel> />
<TabPanel> </TabPanel>
<CameraPanel ))}
tabIndex={tabIndex}
isResetAllModalOpen={isResetAllModalOpen}
handleClose={handleClose}
setIsResetModalOpen={setIsResetModalOpen}
/>
</TabPanel>
<TabPanel>
<CameraPanel
tabIndex={tabIndex}
isResetAllModalOpen={isResetAllModalOpen}
handleClose={handleClose}
setIsResetModalOpen={setIsResetModalOpen}
/>
</TabPanel>
</Tabs> </Tabs>
</Card> </Card>
); );

View File

@@ -4,12 +4,14 @@ import { useCameraFeedContext } from "../../../../app/context/CameraFeedContext"
import { useColourDectection } from "../../hooks/useColourDetection"; import { useColourDectection } from "../../hooks/useColourDetection";
import { useBlackBoard } from "../../../../hooks/useBlackBoard"; import { useBlackBoard } from "../../../../hooks/useBlackBoard";
import { toast } from "sonner"; import { toast } from "sonner";
import { useCameraFeedSocket } from "../../../../app/context/WebSocketContext";
import type { CameraID } from "../../../../app/config/cameraConfig";
type RegionSelectorProps = { type RegionSelectorProps = {
regions: Region[]; regions: Region[];
selectedRegionIndex: number; selectedRegionIndex: number;
mode: string; mode: string;
cameraFeedID: "A" | "B" | "C"; cameraFeedID: CameraID;
isResetAllModalOpen: boolean; isResetAllModalOpen: boolean;
handleClose: () => void; handleClose: () => void;
setIsResetModalOpen: React.Dispatch<React.SetStateAction<boolean>>; setIsResetModalOpen: React.Dispatch<React.SetStateAction<boolean>>;
@@ -28,6 +30,28 @@ const RegionSelector = ({
const { state, dispatch } = useCameraFeedContext(); const { state, dispatch } = useCameraFeedContext();
const { blackboardMutation } = useBlackBoard(); const { blackboardMutation } = useBlackBoard();
const paintedCells = state.paintedCells[cameraFeedID]; const paintedCells = state.paintedCells[cameraFeedID];
const cameraSocket = useCameraFeedSocket();
const getCurrentSocket = () => {
switch (cameraFeedID) {
case "A":
return cameraSocket;
case "B":
return cameraSocket;
case "C":
return cameraSocket;
}
};
const socket = getCurrentSocket();
const getMagnificationLevel = () => {
const test = socket?.data;
if (!socket?.data) return null;
console.log(test);
if (!test || !test.magnificationLevel) return "1x";
return test?.magnificationLevel;
};
const handleChange = (e: { target: { value: string } }) => { const handleChange = (e: { target: { value: string } }) => {
dispatch({ type: "CHANGE_MODE", payload: { cameraFeedID: cameraFeedID, mode: e.target.value } }); dispatch({ type: "CHANGE_MODE", payload: { cameraFeedID: cameraFeedID, mode: e.target.value } });
@@ -79,12 +103,12 @@ const RegionSelector = ({
const handleSaveclick = () => { const handleSaveclick = () => {
const regions: ColourData[] = []; const regions: ColourData[] = [];
const test = Array.from(paintedCells.entries()); const paintedCellsArray = Array.from(paintedCells.entries());
const region1 = test.filter(([, cell]) => cell.region.name === "Bay 1"); const region1 = paintedCellsArray.filter(([, cell]) => cell.region.name === "Bay 1");
const region2 = test.filter(([, cell]) => cell.region.name === "Bay 2"); const region2 = paintedCellsArray.filter(([, cell]) => cell.region.name === "Bay 2");
const region3 = test.filter(([, cell]) => cell.region.name === "Bay 3"); const region3 = paintedCellsArray.filter(([, cell]) => cell.region.name === "Bay 3");
const region4 = test.filter(([, cell]) => cell.region.name === "Bay 4"); const region4 = paintedCellsArray.filter(([, cell]) => cell.region.name === "Bay 4");
const region5 = test.filter(([, cell]) => cell.region.name === "Bay 5"); const region5 = paintedCellsArray.filter(([, cell]) => cell.region.name === "Bay 5");
const region1Data = { const region1Data = {
id: 1, id: 1,
cells: region1.map(([key]) => [parseInt(key.split("-")[1]), parseInt(key.split("-")[0])]), cells: region1.map(([key]) => [parseInt(key.split("-")[1]), parseInt(key.split("-")[0])]),
@@ -123,7 +147,7 @@ const RegionSelector = ({
colourMutation.mutate({ cameraFeedID, regions: regions }); colourMutation.mutate({ cameraFeedID, regions: regions });
// Convert Map to plain object for blackboard // Convert map to plain object for blackboard
const serializableState = { const serializableState = {
...state, ...state,
paintedCells: { paintedCells: {
@@ -137,7 +161,7 @@ const RegionSelector = ({
}; };
return ( return (
<div className="flex flex-col gap-4 max-h-[50%]"> <div className="flex flex-col gap-4 h-full overflow-y-auto mt-[5%]">
<div className="flex flex-col md:flex-row gap-3"> <div className="flex flex-col md:flex-row gap-3">
<div className="p-2 border border-gray-600 rounded-lg flex flex-col h-[10%] w-full"> <div className="p-2 border border-gray-600 rounded-lg flex flex-col h-[10%] w-full">
<h2 className="text-2xl mb-2">Tools</h2> <h2 className="text-2xl mb-2">Tools</h2>
@@ -174,6 +198,45 @@ const RegionSelector = ({
/> />
<span className="text-xl">Erase mode</span> <span className="text-xl">Erase mode</span>
</label> </label>
<label
htmlFor="magnifyMode"
className={`p-4 border rounded-lg mb-2
${mode === "magnify" ? "border-gray-400 bg-[#202b36]" : "bg-[#253445] border-gray-700"}
hover:bg-[#202b36] hover:cursor-pointer`}
>
<input
id="magnifyMode"
type="radio"
onChange={handleChange}
checked={mode === "magnify"}
value="magnify"
className="sr-only"
/>
<div className="flex flex-col space-y-3">
<span className="text-xl">Magnifier</span>
{mode === "magnify" && <small className={`text-gray-400 italic`}>Use mouse to magnify the image</small>}
</div>
</label>
<label
htmlFor="zoomMode"
className={`p-4 border rounded-lg mb-2
${mode === "zoom" ? "border-gray-400 bg-[#202b36]" : "bg-[#253445] border-gray-700"}
hover:bg-[#202b36] hover:cursor-pointer`}
>
<input
id="zoomMode"
type="radio"
onChange={handleChange}
checked={mode === "zoom"}
value="zoom"
className="sr-only"
/>
<div className="flex flex-col space-y-3">
<span className="text-xl">Digital Zoom mode</span>
<pre className="text-xs text-gray-400">{`Current Zoom: ${getMagnificationLevel()}`}</pre>
{mode === "zoom" && <small className={`text-gray-400 italic`}>Click image to digitally zoom</small>}
</div>
</label>
</div> </div>
</div> </div>
@@ -214,10 +277,16 @@ const RegionSelector = ({
})} })}
</> </>
<div className="flex flex-col gap-4 mt-4"> <div className="flex flex-col gap-4 mt-4">
<button className="border border-blue-900 bg-blue-700 px-4 py-1 rounded-md" onClick={handleAddRegionClick}> <button
className="border border-blue-900 bg-blue-700 px-4 py-1 rounded-md hover:bg-blue-800 hover:cursor-pointer"
onClick={handleAddRegionClick}
>
Add Bay Add Bay
</button> </button>
<button className="border border-red-900 bg-red-700 px-4 py-1 rounded-md" onClick={handleRemoveClick}> <button
className="border border-red-900 bg-red-700 px-4 py-1 rounded-md hover:bg-red-800 hover:cursor-pointer"
onClick={handleRemoveClick}
>
Remove Bay Remove Bay
</button> </button>
</div> </div>
@@ -226,22 +295,25 @@ const RegionSelector = ({
<div className="p-2 border border-gray-600 rounded-lg flex flex-col w-full"> <div className="p-2 border border-gray-600 rounded-lg flex flex-col w-full">
<h2 className="text-2xl mb-2">Actions</h2> <h2 className="text-2xl mb-2">Actions</h2>
<div className="flex flex-col md:flex-row mx-auto gap-4 justify-center"> <div className="flex flex-col gap-4 justify-center">
<button <div className="grid grid-cols-2 gap-2">
onClick={handleSaveclick} <button
className="mt-2 px-4 py-2 border border-blue-600 rounded-md text-white bg-blue-600 w-full md:w-full hover:bg-blue-700 hover:cursor-pointer" onClick={handleSaveclick}
> className="mt-2 px-4 py-2 border border-blue-600 rounded-md text-white bg-blue-600 w-full hover:bg-blue-700 hover:cursor-pointer"
Save Region >
</button> Save Region
<button </button>
onClick={handleResetRegion} <button
className="mt-2 px-4 py-2 border border-red-600 rounded-md text-white bg-red-600 w-full md:w-full hover:bg-red-700 hover:cursor-pointer" onClick={handleResetRegion}
> className="mt-2 px-4 py-2 border border-red-600 rounded-md text-white bg-red-600 w-full hover:bg-red-700 hover:cursor-pointer"
Reset Region >
</button> Reset Region
</button>
</div>
<button <button
onClick={openResetModal} onClick={openResetModal}
className="mt-2 px-4 py-2 border border-red-600 rounded-md text-white bg-red-600 w-full md:w-full hover:bg-red-700 hover:cursor-pointer" className="mt-2 px-4 py-2 border border-red-600 rounded-md text-white bg-red-600 w-full hover:bg-red-700 hover:cursor-pointer"
> >
Reset All Reset All
</button> </button>

View File

@@ -0,0 +1,43 @@
import type { CameraID } from "../../../../../app/config/cameraConfig";
import { useCameraFeedContext } from "../../../../../app/context/CameraFeedContext";
import SliderComponent from "../../../../../ui/SliderComponent";
import { useCameraZoom } from "../../../hooks/useCameraZoom";
import { useDebouncedCallback } from "use-debounce";
type CameraControlsProps = {
cameraFeedID: CameraID;
};
const CameraControls = ({ cameraFeedID }: CameraControlsProps) => {
const { state, dispatch } = useCameraFeedContext();
const { cameraZoomMutation } = useCameraZoom(cameraFeedID);
const zoomLevel = state.zoomLevel ? state.zoomLevel[cameraFeedID] : 1;
const debouncedMutation = useDebouncedCallback(async (value) => {
await cameraZoomMutation.mutateAsync({
cameraFeedID,
zoomLevel: value as number,
});
}, 1000);
const handleChange = (value: number | number[]) => {
const newZoom = value as number;
dispatch({
type: "SET_ZOOM_LEVEL",
payload: { cameraFeedID: cameraFeedID, zoomLevel: value as number },
});
debouncedMutation(newZoom);
};
return (
<div className="p-2 border border-gray-600 rounded-lg flex flex-col w-full mt-[5%]">
<h2 className="text-2xl mb-4">Camera {cameraFeedID}</h2>
<div className="w-[70%] ">
<label htmlFor="zoom">Zoom {zoomLevel} </label>
<SliderComponent id="zoom" onChange={handleChange} value={zoomLevel} min={1} max={3} step={0.1} />
</div>
</div>
);
};
export default CameraControls;

View File

@@ -1,43 +1,96 @@
import { useState } from "react";
import { useCameraFeedContext } from "../../../../app/context/CameraFeedContext"; import { useCameraFeedContext } from "../../../../app/context/CameraFeedContext";
import type { DecodeReading } from "../../../../types/types"; import type { DecodeReading } from "../../../../types/types";
import { useSightingEntryAndExit } from "../../hooks/useSightingEntryAndExit"; import { useSightingEntryAndExit } from "../../hooks/useSightingEntryAndExit";
import PlatePatchModal from "./platePatchModal/PlatePatchModal";
const SightingEntryTable = () => { const SightingEntryTable = () => {
const { state } = useCameraFeedContext(); const { state } = useCameraFeedContext();
const [isPlatePatchModalOpen, setIsPlatePatchModalOpen] = useState(false);
const [currentPatch, setCurrentPatch] = useState<DecodeReading | null>(null);
const cameraFeedID = state.cameraFeedID; const cameraFeedID = state.cameraFeedID;
const { entryQuery } = useSightingEntryAndExit(cameraFeedID); const { entryQuery } = useSightingEntryAndExit(cameraFeedID);
const isLoading = entryQuery?.isFetching; const isLoading = entryQuery?.isFetching;
const readings = entryQuery?.data?.decodes; const readings = entryQuery?.data?.decodes;
const handleRowClick = (reading: DecodeReading) => {
setCurrentPatch(reading);
setIsPlatePatchModalOpen(true);
};
if (isLoading) return <span className="text-slate-500">Loading Sighting data</span>; if (isLoading) return <span className="text-slate-500">Loading Sighting data</span>;
return ( return (
<div className="border border-gray-600 rounded-lg m-2"> <>
<div className="overflow-y-auto "> <div className="border border-gray-600 rounded-lg m-2">
<table className="w-full text-left text-sm"> {/* Desktop Table */}
<thead className="bg-gray-700/50 text-gray-200 sticky top-0"> <div className="hidden md:block overflow-y-auto">
<tr> <table className="w-full text-left text-sm">
<th className="px-4 py-3 font-semibold">VRM</th> <thead className="bg-gray-700/50 text-gray-200 sticky top-0">
<th className="px-4 py-3 font-semibold">Bay ID</th> <tr>
<th className="px-4 py-3 font-semibold text-center">Seen Count</th> <th className="px-4 py-3 font-semibold">VRM</th>
<th className="px-4 py-3 font-semibold">First Seen</th> <th className="px-4 py-3 font-semibold">Bay ID</th>
<th className="px-4 py-3 font-semibold">Last Seen</th> <th className="px-4 py-3 font-semibold text-center">Seen Count</th>
</tr> <th className="px-4 py-3 font-semibold">First Seen</th>
</thead> <th className="px-4 py-3 font-semibold">Last Seen</th>
<tbody className="divide-y divide-gray-700">
{readings?.map((reading: DecodeReading) => (
<tr className="hover:bg-gray-800/30 transition-colors" key={reading?.id}>
<td className="px-4 py-3 font-mono font-semibold text-blue-400 text-lg">{reading?.vrm}</td>
<td className="px-4 py-3 text-gray-300">{reading?.laneID}</td>
<td className="px-4 py-3 text-center text-gray-300">{reading?.seenCount}</td>
<td className="px-4 py-3 text-gray-400 text-md">{reading?.firstSeenTimeHumane}</td>
<td className="px-4 py-3 text-gray-400 text-md">{reading?.lastSeenTimeHumane}</td>
</tr> </tr>
))} </thead>
</tbody> <tbody className="divide-y divide-gray-700">
</table> {readings?.map((reading: DecodeReading) => (
<tr
className="hover:bg-gray-800/30 transition-colors hover:cursor-pointer"
key={reading?.id}
onClick={() => handleRowClick(reading)}
>
<td className="px-4 py-3 font-mono font-semibold text-blue-400 text-lg">{reading?.vrm}</td>
<td className="px-4 py-3 text-gray-300">{reading?.laneID}</td>
<td className="px-4 py-3 text-center text-gray-300">{reading?.seenCount}</td>
<td className="px-4 py-3 text-gray-400 text-md">{reading?.firstSeenTimeHumane}</td>
<td className="px-4 py-3 text-gray-400 text-md">{reading?.lastSeenTimeHumane}</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Mobile */}
<div className="md:hidden overflow-y-auto space-y-3 p-3">
{readings?.map((reading: DecodeReading) => (
<div
key={reading?.id}
className="bg-gray-800/30 rounded-lg p-4 space-y-2 border border-gray-700 hover:border-gray-600 transition-colors"
onClick={() => handleRowClick(reading)}
>
<div className="flex justify-between items-start">
<span className="font-mono font-semibold text-blue-400 text-xl">{reading?.vrm}</span>
<span className="text-gray-400 text-sm">Bay {reading?.laneID}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400">Seen Count:</span>
<span className="text-gray-300 font-semibold">{reading?.seenCount}</span>
</div>
<div className="pt-2 border-t border-gray-700 space-y-1 text-xs">
<div className="flex justify-between">
<span className="text-gray-500">First Seen:</span>
<span className="text-gray-400">{reading?.firstSeenTimeHumane}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Last Seen:</span>
<span className="text-gray-400">{reading?.lastSeenTimeHumane}</span>
</div>
</div>
</div>
))}
</div>
</div> </div>
</div> <PlatePatchModal
isPlatePatchModalOpen={isPlatePatchModalOpen}
handleClose={() => setIsPlatePatchModalOpen(false)}
currentPatch={currentPatch}
direction={"entry"}
/>
</>
); );
}; };

View File

@@ -1,8 +1,12 @@
import { useState } from "react";
import { useCameraFeedContext } from "../../../../app/context/CameraFeedContext"; import { useCameraFeedContext } from "../../../../app/context/CameraFeedContext";
import type { DecodeReading } from "../../../../types/types"; import type { DecodeReading } from "../../../../types/types";
import { useSightingEntryAndExit } from "../../hooks/useSightingEntryAndExit"; import { useSightingEntryAndExit } from "../../hooks/useSightingEntryAndExit";
import PlatePatchModal from "./platePatchModal/PlatePatchModal";
const SightingExitTable = () => { const SightingExitTable = () => {
const [isPlatePatchModalOpen, setIsPlatePatchModalOpen] = useState(false);
const [currentPatch, setCurrentPatch] = useState<DecodeReading | null>(null);
const { state } = useCameraFeedContext(); const { state } = useCameraFeedContext();
const cameraFeedID = state.cameraFeedID; const cameraFeedID = state.cameraFeedID;
const { exitQuery } = useSightingEntryAndExit(cameraFeedID); const { exitQuery } = useSightingEntryAndExit(cameraFeedID);
@@ -10,34 +14,82 @@ const SightingExitTable = () => {
const isLoading = exitQuery?.isFetching; const isLoading = exitQuery?.isFetching;
const readings = exitQuery?.data?.decodes; const readings = exitQuery?.data?.decodes;
const handleRowClick = (reading: DecodeReading) => {
setCurrentPatch(reading);
setIsPlatePatchModalOpen(true);
};
if (isLoading) return <span className="text-slate-500">Loading Sighting data</span>; if (isLoading) return <span className="text-slate-500">Loading Sighting data</span>;
return ( return (
<div className="border border-gray-600 rounded-lg overflow-hidden m-2"> <>
<div className="overflow-y-auto "> <div className="border border-gray-600 rounded-lg m-2">
<table className="w-full text-left text-sm"> {/* Desktop Table */}
<thead className="bg-gray-700/50 text-gray-200 sticky top-0"> <div className="hidden md:block overflow-y-auto">
<tr> <table className="w-full text-left text-sm">
<th className="px-4 py-3 font-semibold">VRM</th> <thead className="bg-gray-700/50 text-gray-200 sticky top-0">
<th className="px-4 py-3 font-semibold">Bay ID</th> <tr>
<th className="px-4 py-3 font-semibold text-center">Seen Count</th> <th className="px-4 py-3 font-semibold">VRM</th>
<th className="px-4 py-3 font-semibold">First Seen</th> <th className="px-4 py-3 font-semibold">Bay ID</th>
<th className="px-4 py-3 font-semibold">Last Seen</th> <th className="px-4 py-3 font-semibold text-center">Seen Count</th>
</tr> <th className="px-4 py-3 font-semibold">First Seen</th>
</thead> <th className="px-4 py-3 font-semibold">Last Seen</th>
<tbody className="divide-y divide-gray-700">
{readings?.map((reading: DecodeReading) => (
<tr className="hover:bg-gray-800/30 transition-colors" key={reading?.id}>
<td className="px-4 py-3 font-mono font-semibold text-red-400 text-lg">{reading?.vrm}</td>
<td className="px-4 py-3 text-gray-300">{reading?.laneID}</td>
<td className="px-4 py-3 text-center text-gray-300">{reading?.seenCount}</td>
<td className="px-4 py-3 text-gray-400 text-md">{reading?.firstSeenTimeHumane}</td>
<td className="px-4 py-3 text-gray-400 text-md">{reading?.lastSeenTimeHumane}</td>
</tr> </tr>
))} </thead>
</tbody> <tbody className="divide-y divide-gray-700">
</table> {readings?.map((reading: DecodeReading) => (
<tr
className="hover:bg-gray-800/30 transition-colors hover:cursor-pointer"
key={reading?.id}
onClick={() => handleRowClick(reading)}
>
<td className="px-4 py-3 font-mono font-semibold text-red-400 text-lg">{reading?.vrm}</td>
<td className="px-4 py-3 text-gray-300">{reading?.laneID}</td>
<td className="px-4 py-3 text-center text-gray-300">{reading?.seenCount}</td>
<td className="px-4 py-3 text-gray-400 text-md">{reading?.firstSeenTimeHumane}</td>
<td className="px-4 py-3 text-gray-400 text-md">{reading?.lastSeenTimeHumane}</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Mobile Cards */}
<div className="md:hidden overflow-y-auto space-y-3 p-3">
{readings?.map((reading: DecodeReading) => (
<div
key={reading?.id}
className="bg-gray-800/30 rounded-lg p-4 space-y-2 border border-gray-700 hover:border-gray-600 transition-colors"
onClick={() => handleRowClick(reading)}
>
<div className="flex justify-between items-start">
<span className="font-mono font-semibold text-red-400 text-xl">{reading?.vrm}</span>
<span className="text-gray-400 text-sm">Bay {reading?.laneID}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-400">Seen Count:</span>
<span className="text-gray-300 font-semibold">{reading?.seenCount}</span>
</div>
<div className="pt-2 border-t border-gray-700 space-y-1 text-xs">
<div className="flex justify-between">
<span className="text-gray-500">First Seen:</span>
<span className="text-gray-400">{reading?.firstSeenTimeHumane}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Last Seen:</span>
<span className="text-gray-400">{reading?.lastSeenTimeHumane}</span>
</div>
</div>
</div>
))}
</div>
</div> </div>
</div> <PlatePatchModal
isPlatePatchModalOpen={isPlatePatchModalOpen}
handleClose={() => setIsPlatePatchModalOpen(false)}
currentPatch={currentPatch}
direction={"exit"}
/>
</>
); );
}; };

View File

@@ -0,0 +1,20 @@
import type { DecodeReading } from "../../../../../types/types";
import ModalComponent from "../../../../../ui/ModalComponent";
import PlatePatchModalContent from "./PlatePatchModalContent";
type PlatePatchModalProps = {
isPlatePatchModalOpen: boolean;
handleClose: () => void;
currentPatch: DecodeReading | null;
direction?: "entry" | "exit";
};
const PlatePatchModal = ({ isPlatePatchModalOpen, handleClose, currentPatch, direction }: PlatePatchModalProps) => {
return (
<ModalComponent isModalOpen={isPlatePatchModalOpen} close={handleClose}>
<PlatePatchModalContent currentPatch={currentPatch} direction={direction} />
</ModalComponent>
);
};
export default PlatePatchModal;

View File

@@ -0,0 +1,64 @@
import type { DecodeReading } from "../../../../../types/types";
type PlatePatchModalContentProps = {
currentPatch: DecodeReading | null;
direction?: "entry" | "exit";
};
const PlatePatchModalContent = ({ currentPatch, direction }: PlatePatchModalContentProps) => {
const imageSrc = `data:image/png;base64,${currentPatch?.plate || ""}`;
const imageUrl = currentPatch ? imageSrc : "";
return (
<div className="space-y-4">
<div className="flex items-center justify-between border-b border-gray-600 pb-3">
<h2
className={`font-mono font-bold text-3xl tracking-wide
${direction === "entry" ? "text-blue-400" : "text-red-400"}`}
>
{currentPatch?.vrm}
</h2>
<span
className={`px-3 py-1 rounded-full text-xs font-semibold uppercase
${direction === "entry" ? "bg-blue-500/20 text-blue-400" : "bg-red-500/20 text-red-400"}`}
>
{direction === "entry" ? "Entry" : "Exit"}
</span>
</div>
<div className="border border-gray-600 rounded-2xl">
<div className="flex bg-gray-800/50 rounded-lg p-4">
<img
src={imageUrl}
alt={`${direction === "entry" ? "Entry" : "Exit"} Image for ${currentPatch?.vrm || "N/A"}`}
className="rounded-lg border border-gray-600 max-w-full h-auto shadow-lg"
/>
</div>
<div className="grid grid-cols-2 gap-4 bg-gray-800/30 rounded-lg p-4">
<div className="space-y-1">
<p className="text-gray-400 text-xs uppercase tracking-wider">Bay ID</p>
<p className="text-gray-200 font-semibold text-lg">{currentPatch?.laneID || "N/A"}</p>
</div>
<div className="space-y-1">
<p className="text-gray-400 text-xs uppercase tracking-wider">Seen Count</p>
<p className="text-gray-200 font-semibold text-lg">{currentPatch?.seenCount || "N/A"}</p>
</div>
<div className="space-y-1 col-span-2">
<p className="text-gray-400 text-xs uppercase tracking-wider">First Seen</p>
<p className="text-gray-300 text-sm">{currentPatch?.firstSeenTimeHumane || "N/A"}</p>
</div>
<div className="space-y-1 col-span-2">
<p className="text-gray-400 text-xs uppercase tracking-wider">Last Seen</p>
<p className="text-gray-300 text-sm">{currentPatch?.lastSeenTimeHumane || "N/A"}</p>
</div>
</div>
</div>
</div>
);
};
export default PlatePatchModalContent;

View File

@@ -2,8 +2,11 @@ import { useEffect, useRef, useState, type RefObject } from "react";
import { Stage, Layer, Image, Shape } from "react-konva"; import { Stage, Layer, Image, Shape } from "react-konva";
import type { KonvaEventObject } from "konva/lib/Node"; import type { KonvaEventObject } from "konva/lib/Node";
import { useCreateVideoSnapshot } from "../../hooks/useGetvideoSnapshots"; import { useCreateVideoSnapshot } from "../../hooks/useGetvideoSnapshots";
import { useCameraFeedContext } from "../../../../app/context/CameraFeedContext"; import { useCameraFeedContext } from "../../../../app/context/CameraFeedContext";
import { useCameraFeedSocket } from "../../../../app/context/WebSocketContext";
import { ReadyState } from "react-use-websocket";
import { toast } from "sonner";
import type { CameraID } from "../../../../app/config/cameraConfig";
const BACKEND_WIDTH = 640; const BACKEND_WIDTH = 640;
const BACKEND_HEIGHT = 360; const BACKEND_HEIGHT = 360;
@@ -23,12 +26,54 @@ const VideoFeedGridPainter = () => {
const { latestBitmapRef, isloading } = useCreateVideoSnapshot(); const { latestBitmapRef, isloading } = useCreateVideoSnapshot();
const [stageSize, setStageSize] = useState({ width: BACKEND_WIDTH, height: BACKEND_HEIGHT }); const [stageSize, setStageSize] = useState({ width: BACKEND_WIDTH, height: BACKEND_HEIGHT });
const isDrawingRef = useRef(false); const isDrawingRef = useRef(false);
const [scale, setScale] = useState(1);
const [position, setPosition] = useState({ x: 0, y: 0 });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const stageRef = useRef<any>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const paintLayerRef = useRef<any>(null);
const currentScale = stageSize.width / BACKEND_WIDTH; const currentScale = stageSize.width / BACKEND_WIDTH;
const size = BACKEND_CELL_SIZE * currentScale; const size = BACKEND_CELL_SIZE * currentScale;
// eslint-disable-next-line @typescript-eslint/no-explicit-any const cameraSocket = useCameraFeedSocket();
const paintLayerRef = useRef<any>(null);
const getCurrentSocket = () => {
switch (cameraFeedID) {
case "A":
return cameraSocket;
case "B":
return cameraSocket;
case "C":
return cameraSocket;
}
};
const handleZoomClick = (e: KonvaEventObject<MouseEvent>, cameraFeedID: CameraID) => {
if (mode !== "zoom") return;
const socket = getCurrentSocket();
const stage = e.target.getStage();
const coords = stage?.getPointerPosition();
if (!coords || !socket) return;
const newX = coords.x / stageSize.width;
const newY = coords.y / stageSize.height;
// Check if WebSocket is connected
if (socket.readyState !== ReadyState.OPEN) {
toast.error(`Camera ${cameraFeedID} WebSocket is not connected`);
return;
}
try {
socket.send(`ZOOM=${newX.toFixed(2)},${newY.toFixed(2)}`);
} catch (error) {
console.error("WebSocket send error:", error);
toast.error(`Failed to send command to Camera ${cameraFeedID}`);
}
};
const draw = (bmp: RefObject<ImageBitmap | null>): ImageBitmap | null => { const draw = (bmp: RefObject<ImageBitmap | null>): ImageBitmap | null => {
if (!bmp || !bmp.current) { if (!bmp || !bmp.current) {
@@ -60,6 +105,7 @@ const VideoFeedGridPainter = () => {
map.delete(key); map.delete(key);
paintLayerRef.current?.batchDraw(); paintLayerRef.current?.batchDraw();
} }
return; return;
} }
@@ -71,14 +117,14 @@ const VideoFeedGridPainter = () => {
}; };
const handleStageMouseDown = (e: KonvaEventObject<MouseEvent>) => { const handleStageMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (!regions[selectedRegionIndex]) return; if (!regions[selectedRegionIndex] || mode === "magnify" || mode === "zoom") return;
isDrawingRef.current = true; isDrawingRef.current = true;
const pos = e.target.getStage()?.getPointerPosition(); const pos = e.target.getStage()?.getPointerPosition();
if (pos) paintCell(pos.x, pos.y); if (pos) paintCell(pos.x, pos.y);
}; };
const handleStageMouseMove = (e: KonvaEventObject<MouseEvent>) => { const handleStageMouseMove = (e: KonvaEventObject<MouseEvent>) => {
if (!isDrawingRef.current) return; if (!isDrawingRef.current || mode === "magnify") return;
if (!regions[selectedRegionIndex]) return; if (!regions[selectedRegionIndex]) return;
const pos = e.target.getStage()?.getPointerPosition(); const pos = e.target.getStage()?.getPointerPosition();
if (pos) paintCell(pos.x, pos.y); if (pos) paintCell(pos.x, pos.y);
@@ -88,6 +134,38 @@ const VideoFeedGridPainter = () => {
isDrawingRef.current = false; isDrawingRef.current = false;
}; };
const handleMouseEnter = () => {
if (mode !== "magnify") return;
setScale(2);
};
const handleMouseLeave = () => {
document.body.style.cursor = "default";
setScale(1);
setPosition({ x: 0, y: 0 });
};
const handleMouseMove = (e: KonvaEventObject<MouseEvent>) => {
if (scale === 1) return;
const stage = e.target.getStage();
if (!stage) return;
const pointerPosition = stage.getPointerPosition();
if (!pointerPosition) return;
const newX = stageSize.width / 2 - pointerPosition.x * scale;
const newY = stageSize.height / 2 - pointerPosition.y * scale;
const maxX = 0;
const minX = stageSize.width - stageSize.width * scale;
const maxY = 0;
const minY = stageSize.height - stageSize.height * scale;
setPosition({
x: Math.max(minX, Math.min(maxX, newX)),
y: Math.max(minY, Math.min(maxY, newY)),
});
};
useEffect(() => { useEffect(() => {
const handleResize = () => { const handleResize = () => {
const width = window.innerWidth; const width = window.innerWidth;
@@ -112,48 +190,63 @@ const VideoFeedGridPainter = () => {
if (image === null || isloading) return <span className="text-slate-500">Loading Video feed</span>; if (image === null || isloading) return <span className="text-slate-500">Loading Video feed</span>;
return ( return (
<div <div>
className={`w-full md:row-span-3 md:col-span-3 ${mode === "painter" ? "hover:cursor-crosshair" : ""} ${
mode === "eraser" ? "hover:cursor-pointer" : ""
}`}
>
<Stage <Stage
ref={stageRef}
width={stageSize.width} width={stageSize.width}
height={stageSize.height} height={stageSize.height}
onMouseDown={handleStageMouseDown} onMouseDown={handleStageMouseDown}
onMouseMove={handleStageMouseMove} onMouseMove={handleStageMouseMove}
onMouseUp={handleStageMouseUp} onMouseUp={handleStageMouseUp}
onMouseLeave={handleStageMouseUp} onMouseLeave={handleStageMouseUp}
className="max-w-[55%]" className={`max-w-[55%] md:row-span-3 md:col-span-3 ${mode === "painter" ? "hover:cursor-crosshair" : ""} ${
mode === "eraser" ? "hover:cursor-pointer" : ""
} ${mode === "zoom" ? "hover:cursor-zoom-in" : ""}`}
> >
<Layer> <Layer
<Image image={image} width={stageSize.width} height={stageSize.height} classname={"rounded-lg"} /> scaleX={scale}
scaleY={scale}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onMouseMove={handleMouseMove}
x={position.x}
y={position.y}
>
<Image
image={image}
width={stageSize.width}
height={stageSize.height}
classname={"rounded-lg"}
onClick={(e) => handleZoomClick(e, cameraFeedID)}
/>
</Layer> </Layer>
<Layer ref={paintLayerRef} opacity={0.6}> <Layer ref={paintLayerRef} opacity={0.6}>
<Shape {mode === "painter" || mode === "eraser" ? (
sceneFunc={(ctx, shape) => { <Shape
const cells = paintedCells; sceneFunc={(ctx, shape) => {
if (!cells || cells.size === 0 || !paintLayerRef.current) return; const cells = paintedCells;
cells?.forEach((cell, key) => { if (!cells || cells.size === 0 || !paintLayerRef.current) return;
const [rowStr, colStr] = key.split("-"); cells?.forEach((cell, key) => {
const row = Number(rowStr); const [rowStr, colStr] = key.split("-");
const col = Number(colStr); const row = Number(rowStr);
const col = Number(colStr);
const x = col * (size + gap); const x = col * (size + gap);
const y = row * (size + gap); const y = row * (size + gap);
ctx.beginPath(); ctx.beginPath();
ctx.rect(x, y, size, size); ctx.rect(x, y, size, size);
ctx.fillStyle = cell.colour; ctx.fillStyle = cell.colour;
ctx.fill(); ctx.fill();
}); });
ctx.fillStrokeShape(shape); ctx.fillStrokeShape(shape);
}} }}
width={stageSize.width} width={stageSize.width}
height={stageSize.height} height={stageSize.height}
/> />
) : null}
</Layer> </Layer>
</Stage> </Stage>
</div> </div>

View File

@@ -0,0 +1,49 @@
import { useQuery, useMutation } from "@tanstack/react-query";
import { CAMBASE } from "../../../utils/config";
import type { CameraZoomConfig } from "../../../types/types";
import type { CameraID } from "../../../app/config/cameraConfig";
const fetchZoomLevel = async (cameraFeedID: string) => {
const response = await fetch(`${CAMBASE}/api/fetch-config?id=Camera${cameraFeedID}-onvif-controller`);
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
};
const postZoomLevel = async (zoomConfig: CameraZoomConfig) => {
const fields = [
{ property: "propPhysCurrent", value: zoomConfig.zoomLevel },
{ property: "propCameraHost", value: "192.168.0.101" },
{ property: "propCameraPort", value: 80 },
{ property: "propCameraUsername", value: "administrator" },
{ property: "propCameraPassword", value: "MAV12345" },
];
const zoomPayload = {
id: `Camera${zoomConfig.cameraFeedID}-onvif-controller`,
fields,
};
console.log(zoomPayload);
const response = await fetch(`${CAMBASE}/api/update-config`, {
method: "POST",
body: JSON.stringify(zoomPayload),
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
};
export const useCameraZoom = (cameraFeedID: CameraID) => {
const cameraZoomQuery = useQuery({
queryKey: ["cameraZoom", cameraFeedID],
queryFn: () => fetchZoomLevel(cameraFeedID),
});
const cameraZoomMutation = useMutation({
mutationKey: ["postCameraZoom"],
mutationFn: (zoomConfig: CameraZoomConfig) => postZoomLevel(zoomConfig),
});
return { cameraZoomQuery, cameraZoomMutation };
};

View File

@@ -1,7 +1,8 @@
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { CAMBASE } from "../../../utils/config"; import { CAMBASE } from "../../../utils/config";
import type { CameraID } from "../../../app/config/cameraConfig";
const getfeed = async (cameraFeedID: "A" | "B" | "C" | null) => { const targetDectionFeed = async (cameraFeedID: CameraID | null) => {
const response = await fetch(`${CAMBASE}/TargetDetectionColour${cameraFeedID}-preview`, { const response = await fetch(`${CAMBASE}/TargetDetectionColour${cameraFeedID}-preview`, {
signal: AbortSignal.timeout(300000), signal: AbortSignal.timeout(300000),
cache: "no-store", cache: "no-store",
@@ -12,12 +13,31 @@ const getfeed = async (cameraFeedID: "A" | "B" | "C" | null) => {
return response.blob(); return response.blob();
}; };
export const useGetVideoFeed = (cameraFeedID: "A" | "B" | "C" | null) => { const getVideoFeed = async (cameraFeedID: CameraID | null) => {
const videoQuery = useQuery({ const response = await fetch(`${CAMBASE}/Camera${cameraFeedID}-preview`, {
signal: AbortSignal.timeout(300000),
cache: "no-store",
});
if (!response.ok) {
throw new Error(`Cannot reach endpoint (${response.status})`);
}
return response.blob();
};
export const useGetVideoFeed = (cameraFeedID: CameraID | null, mode: string) => {
const targetDetectionQuery = useQuery({
queryKey: ["getfeed", cameraFeedID], queryKey: ["getfeed", cameraFeedID],
queryFn: () => getfeed(cameraFeedID), queryFn: () => targetDectionFeed(cameraFeedID),
refetchInterval: 500, refetchInterval: 500,
enabled: mode !== "magnify" && mode !== "zoom",
}); });
return { videoQuery }; const videoFeedQuery = useQuery({
queryKey: ["videoQuery", cameraFeedID, mode],
queryFn: () => getVideoFeed(cameraFeedID),
refetchInterval: 500,
enabled: mode === "magnify" || mode === "zoom",
});
return { targetDetectionQuery, videoFeedQuery };
}; };

View File

@@ -5,18 +5,30 @@ import { useCameraFeedContext } from "../../../app/context/CameraFeedContext";
export const useCreateVideoSnapshot = () => { export const useCreateVideoSnapshot = () => {
const { state } = useCameraFeedContext(); const { state } = useCameraFeedContext();
const cameraFeedID = state?.cameraFeedID; const cameraFeedID = state?.cameraFeedID;
const mode = state.modeByCamera[cameraFeedID];
const latestBitmapRef = useRef<ImageBitmap | null>(null); const latestBitmapRef = useRef<ImageBitmap | null>(null);
const { videoQuery } = useGetVideoFeed(cameraFeedID); const { targetDetectionQuery, videoFeedQuery } = useGetVideoFeed(cameraFeedID, mode);
const snapShot = videoQuery?.data; let snapShot = targetDetectionQuery?.data;
const isloading = videoQuery.isPending; const isloading = targetDetectionQuery.isPending;
const videoSnapShot = videoFeedQuery?.data;
const isVideoLoading = videoFeedQuery.isPending;
if ((isVideoLoading === false && videoSnapShot && mode === "magnify") || mode === "zoom") {
snapShot = videoSnapShot;
}
useEffect(() => { useEffect(() => {
async function createBitmap() { async function createBitmap() {
if (!snapShot) return; if (!snapShot) return;
try { try {
const bitmap = await createImageBitmap(snapShot); const bitmap = await createImageBitmap(snapShot, {
resizeWidth: 720,
resizeHeight: 1080,
resizeQuality: "high",
});
if (!bitmap) return; if (!bitmap) return;
latestBitmapRef.current = bitmap; latestBitmapRef.current = bitmap;
} catch (error) { } catch (error) {

View File

@@ -3,6 +3,7 @@ import { useGetSystemHealth } from "../hooks/useGetSystemHealth";
import CameraStatus from "./cameraStatus/CameraStatus"; import CameraStatus from "./cameraStatus/CameraStatus";
import SystemHealthCard from "./systemHealth/SystemHealthCard"; import SystemHealthCard from "./systemHealth/SystemHealthCard";
import SystemStatusCard from "./systemStatus/SystemStatusCard"; import SystemStatusCard from "./systemStatus/SystemStatusCard";
import { CAMERA_IDS } from "../../../app/config/cameraConfig";
const DashboardGrid = () => { const DashboardGrid = () => {
const { query } = useGetSystemHealth(); const { query } = useGetSystemHealth();
@@ -26,30 +27,35 @@ const DashboardGrid = () => {
channelA: [], channelA: [],
channelB: [], channelB: [],
channelC: [], channelC: [],
// todo: check if more cameras will be added later
default: [], default: [],
}, },
); );
const categoryA = statusCategories?.channelA ?? [];
const categoryB = statusCategories?.channelB ?? [];
const categoryC = statusCategories?.channelC ?? [];
return ( return (
<div className="grid grid-cols-1 md:grid-rows-2 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-rows-2 md:grid-cols-2 gap-4">
<SystemStatusCard /> <div className="grid grid-cols-1 md:grid-rows-0 md:grid-cols-2 gap-4 md:col-span-2">
<SystemHealthCard <SystemStatusCard />
startTime={startTime} <SystemHealthCard
uptime={uptime} startTime={startTime}
statuses={statuses} uptime={uptime}
isLoading={isLoading} statuses={statuses}
isError={isError} isLoading={isLoading}
dateUpdatedAt={dateUpdatedAt} isError={isError}
refetch={refetch} dateUpdatedAt={dateUpdatedAt}
/> refetch={refetch}
<div className="grid grid-cols-1 md:col-span-2 md:grid-cols-3 gap-x-4"> />
<CameraStatus title="Camera A" category={categoryA} isError={isError} /> </div>
<CameraStatus title="Camera B" category={categoryB} isError={isError} />
<CameraStatus title="Camera C" category={categoryC} isError={isError} /> <div className="grid grid-cols-1 md:col-span-2 md:grid-cols-[repeat(3,1fr)] gap-x-4">
{CAMERA_IDS.map((cameraID) => (
<CameraStatus
key={cameraID}
title={`Camera ${cameraID}`}
category={statusCategories?.[`channel${cameraID}`] ?? []}
isError={isError}
/>
))}
</div> </div>
</div> </div>
); );

View File

@@ -11,10 +11,14 @@ type CameraStatusProps = {
}; };
const CameraStatus = ({ title, category, isError }: CameraStatusProps) => { const CameraStatus = ({ title, category, isError }: CameraStatusProps) => {
const isAllGood = category && category.length > 0 && category.every((status) => status.tags.includes("RUNNING")); const isAllGood =
// check if some are down category &&
// check if all are down category.length > 0 &&
//check if offline category.every((status) => {
const allowedTags = ["RUNNING", "VIDEO-PLAYING"];
return status.tags.every((tag) => allowedTags.includes(tag));
});
return ( return (
<Card className="p-4"> <Card className="p-4">
<div className="border-b border-gray-600"> <div className="border-b border-gray-600">

View File

@@ -1,7 +1,8 @@
import { useState } from "react"; import { useState } from "react";
import type { SystemHealthStatus } from "../../../../types/types"; import type { SystemHealthStatus } from "../../../../types/types";
import { capitalize } from "../../../../utils/utils";
import SystemHealthModal from "../systemHealth/systemHealthModal/SystemHealthModal"; import SystemHealthModal from "../systemHealth/systemHealthModal/SystemHealthModal";
import Badge from "../../../../ui/Badge";
type CameraStatusGridItemProps = { type CameraStatusGridItemProps = {
title: string; title: string;
@@ -10,7 +11,14 @@ type CameraStatusGridItemProps = {
const CameraStatusGridItem = ({ title, statusCategory }: CameraStatusGridItemProps) => { const CameraStatusGridItem = ({ title, statusCategory }: CameraStatusGridItemProps) => {
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const isAllGood = statusCategory?.every((status) => status.tags.includes("RUNNING")); const isAllGood = statusCategory?.every((status) => {
const allowedTags = ["RUNNING", "VIDEO-PLAYING"];
return status.tags.every((tag) => allowedTags.includes(tag));
});
const downItems = statusCategory?.filter((status) => {
return status.tags.some((tag) => tag !== "RUNNING" && tag !== "VIDEO-PLAYING");
});
const handleClick = () => { const handleClick = () => {
setIsOpen(false); setIsOpen(false);
@@ -21,8 +29,21 @@ const CameraStatusGridItem = ({ title, statusCategory }: CameraStatusGridItemPro
className="flex flex-col border border-gray-600 p-4 rounded-lg mr-4 hover:bg-[#233241] hover:cursor-pointer m-2 h-70" className="flex flex-col border border-gray-600 p-4 rounded-lg mr-4 hover:bg-[#233241] hover:cursor-pointer m-2 h-70"
onClick={() => setIsOpen(true)} onClick={() => setIsOpen(true)}
> >
<h3 className="text-lg flex flex-row items-center">{capitalize(title)}</h3> <p className="text-sm text-slate-300">
<p className="text-sm text-slate-300">{isAllGood ? "Click to view module status" : "Some systems down"}</p> {isAllGood ? (
"Click to view module status"
) : (
<>
<ul>
{downItems.map((item) => (
<li key={item.id} className="flex justify-between mb-2">
<span>{item.id}</span> <Badge text={item.tags[0]} />
</li>
))}
</ul>
</>
)}
</p>
</div> </div>
<SystemHealthModal <SystemHealthModal
isSystemHealthModalOpen={isOpen} isSystemHealthModalOpen={isOpen}

View File

@@ -21,7 +21,7 @@ const StatusGridItem = ({ title, statusCategory }: StatusGridItemProps) => {
return ( return (
<> <>
<div <div
className="flex flex-col border border-gray-600 p-4 rounded-lg mr-4 hover:bg-[#233241] hover:cursor-pointer" className="flex flex-col border border-gray-600 p-4 rounded-lg hover:bg-[#233241] hover:cursor-pointer"
onClick={() => setIsOpen(true)} onClick={() => setIsOpen(true)}
> >
<h3 className="text-lg flex flex-row items-center"> <h3 className="text-lg flex flex-row items-center">

View File

@@ -39,11 +39,11 @@ const SystemHealth = ({ startTime, uptime, statuses, isLoading, isError, dateUpd
} }
return ( return (
<div className="relative h-100 md:h-75 overflow-y-auto flex flex-col gap-4"> <div className="relative h-100 md:h-75 overflow-y-auto flex flex-col gap-4">
<div className="p-2 border-b border-gray-600 grid grid-cols-2 justify-between"> <div className="p-2 border-b border-gray-600 grid grid-cols-1 md:grid-cols-2 gap-2 justify-between">
<div className="flex flex-col border border-gray-600 p-4 rounded-lg mr-4 hover:bg-[#233241]"> <div className="flex flex-col border border-gray-600 p-4 rounded-lg hover:bg-[#233241]">
<h3 className="text-lg">Start Time</h3> <span className="text-slate-300">{startTime}</span> <h3 className="text-lg">Start Time</h3> <span className="text-slate-300">{startTime}</span>
</div> </div>
<div className="flex flex-col border border-gray-600 p-4 rounded-lg mr-4 hover:bg-[#233241]"> <div className="flex flex-col border border-gray-600 p-4 rounded-lg hover:bg-[#233241]">
<h3 className="text-lg">Up Time</h3> <span className="text-slate-300">{uptime}</span> <h3 className="text-lg">Up Time</h3> <span className="text-slate-300">{uptime}</span>
</div> </div>
</div> </div>

View File

@@ -25,7 +25,7 @@ const SystemHealthCard = ({
refetch, refetch,
}: SystemOverviewProps) => { }: SystemOverviewProps) => {
return ( return (
<Card className="p-4"> <Card className="p-4 ">
<CardHeader title="System Health" refetch={refetch} icon={faArrowsRotate} /> <CardHeader title="System Health" refetch={refetch} icon={faArrowsRotate} />
<SystemHealth <SystemHealth
startTime={startTime} startTime={startTime}

View File

@@ -29,7 +29,7 @@ const SystemStatusCard = () => {
); );
} }
return ( return (
<Card className="p-4"> <Card className="p-4 ">
<CardHeader title="System Status" /> <CardHeader title="System Status" />
{stats ? ( {stats ? (
<div className="grid grid-cols-2 grid-rows-2 gap-4 col-span-2"> <div className="grid grid-cols-2 grid-rows-2 gap-4 col-span-2">

View File

@@ -4,7 +4,7 @@ import type { FormTypes } from "../../../types/types";
const BearerTypeFields = () => { const BearerTypeFields = () => {
useFormikContext<FormTypes>(); useFormikContext<FormTypes>();
return ( return (
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="format" className="text-xl"> <label htmlFor="format" className="text-xl">
Format Format
</label> </label>

View File

@@ -10,7 +10,7 @@ const ChannelCard = () => {
const { bearerQuery } = useGetBearerConfig(values?.format?.toLowerCase() || "json"); const { bearerQuery } = useGetBearerConfig(values?.format?.toLowerCase() || "json");
const outputData = bearerQuery?.data; const outputData = bearerQuery?.data;
return ( return (
<Card className="p-4 h-150 md:h-full"> <Card className="p-4 h-full">
<CardHeader title={`Channel (${values?.format})`} /> <CardHeader title={`Channel (${values?.format})`} />
<ChannelFields <ChannelFields
errors={errors} errors={errors}

View File

@@ -52,7 +52,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
<div className="flex flex-col gap-4 p-4"> <div className="flex flex-col gap-4 p-4">
{values.format.toLowerCase() !== "ftp" ? ( {values.format.toLowerCase() !== "ftp" ? (
<> <>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="backoffice" className="block mb-2 font-medium"> <label htmlFor="backoffice" className="block mb-2 font-medium">
Back Office URL Back Office URL
</label> </label>
@@ -64,7 +64,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
className={`p-1.5 border 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`}
/> />
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="username" className="block mb-2 font-medium"> <label htmlFor="username" className="block mb-2 font-medium">
Username Username
</label> </label>
@@ -76,7 +76,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
className={`p-1.5 border 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`}
/> />
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="password">Password</label> <label htmlFor="password">Password</label>
<Field <Field
name={"password"} name={"password"}
@@ -86,7 +86,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
className={`p-1.5 border 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`}
/> />
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="readTimeoutSeconds">Read Timeout Seconds</label> <label htmlFor="readTimeoutSeconds">Read Timeout Seconds</label>
<Field <Field
name={"readTimeoutSeconds"} name={"readTimeoutSeconds"}
@@ -96,7 +96,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
className={`p-1.5 border 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`}
/> />
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="connectTimeoutSeconds">Connect Timeout Seconds</label> <label htmlFor="connectTimeoutSeconds">Connect Timeout Seconds</label>
<Field <Field
name={"connectTimeoutSeconds"} name={"connectTimeoutSeconds"}
@@ -105,7 +105,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
className={`p-1.5 border 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`}
/> />
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="overviewQuality">Overview quality and scale</label> <label htmlFor="overviewQuality">Overview quality and scale</label>
<Field <Field
name={"overviewQuality"} name={"overviewQuality"}
@@ -118,7 +118,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
<option value={"LOW"}>Low</option> <option value={"LOW"}>Low</option>
</Field> </Field>
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="cropSizeFactor">Crop Size Factor</label> <label htmlFor="cropSizeFactor">Crop Size Factor</label>
<Field <Field
name={"cropSizeFactor"} name={"cropSizeFactor"}
@@ -138,7 +138,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
<h2 className="font-bold">{values.format} Constants</h2> <h2 className="font-bold">{values.format} Constants</h2>
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="SCID">Source ID / Camera ID</label> <label htmlFor="SCID">Source ID / Camera ID</label>
<Field <Field
name={"SCID"} name={"SCID"}
@@ -150,7 +150,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
} rounded-lg w-full md:w-60`} } rounded-lg w-full md:w-60`}
/> />
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="timestampSource">Timestamp Source</label> <label htmlFor="timestampSource">Timestamp Source</label>
<Field <Field
name={"timestampSource"} name={"timestampSource"}
@@ -162,7 +162,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
<option value={"LOCAL"}>Local</option> <option value={"LOCAL"}>Local</option>
</Field> </Field>
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="GPSFormat">GPS Format</label> <label htmlFor="GPSFormat">GPS Format</label>
<Field <Field
name={"GPSFormat"} name={"GPSFormat"}
@@ -182,7 +182,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
<div className="border-b border-gray-500 my-3"> <div className="border-b border-gray-500 my-3">
<h2 className="font-bold">{values.format} Constants</h2> <h2 className="font-bold">{values.format} Constants</h2>
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="FFID">Feed ID / Force ID</label> <label htmlFor="FFID">Feed ID / Force ID</label>
<Field <Field
name={"FFID"} name={"FFID"}
@@ -194,7 +194,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
} rounded-lg w-full md:w-60`} } rounded-lg w-full md:w-60`}
/> />
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="SCID">Source ID / Camera ID</label> <label htmlFor="SCID">Source ID / Camera ID</label>
<Field <Field
name={"SCID"} name={"SCID"}
@@ -206,7 +206,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
} rounded-lg w-full md:w-60`} } rounded-lg w-full md:w-60`}
/> />
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="timestampSource">Timestamp Source</label> <label htmlFor="timestampSource">Timestamp Source</label>
<Field <Field
name={"timestampSource"} name={"timestampSource"}
@@ -218,7 +218,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
<option value={"LOCAL"}>Local</option> <option value={"LOCAL"}>Local</option>
</Field> </Field>
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="GPSFormat">GPS Format</label> <label htmlFor="GPSFormat">GPS Format</label>
<Field <Field
name={"GPSFormat"} name={"GPSFormat"}
@@ -235,7 +235,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
<div className="border-b border-gray-500 my-3"> <div className="border-b border-gray-500 my-3">
<h2 className="font-bold">{values.format} Lane ID Config</h2> <h2 className="font-bold">{values.format} Lane ID Config</h2>
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="LID1">Lane ID 1 (Camera A)</label> <label htmlFor="LID1">Lane ID 1 (Camera A)</label>
<Field <Field
name={"LID1"} name={"LID1"}
@@ -247,7 +247,7 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
} rounded-lg w-full md:w-60`} } rounded-lg w-full md:w-60`}
/> />
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="LID2">Lane ID 2 (Camera B)</label> <label htmlFor="LID2">Lane ID 2 (Camera B)</label>
<Field <Field
name={"LID2"} name={"LID2"}
@@ -272,7 +272,10 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
{values?.customFields?.map((_, index) => { {values?.customFields?.map((_, index) => {
// if (!field.value) return null; // if (!field.value) return null;
return ( return (
<div key={index} className="flex flex-row justify-between items-center mb-4 gap-2"> <div
key={index}
className="flex flex-col md:flex-row space-y-4 md:space-y-0 justify-between items-center mb-4 gap-2"
>
<Field <Field
name={`customFields.${index}.label`} name={`customFields.${index}.label`}
className="p-2 border border-gray-400 rounded-lg w-full max-w-xs" className="p-2 border border-gray-400 rounded-lg w-full max-w-xs"
@@ -287,23 +290,25 @@ const ChannelFields = ({ errors, touched, values, outputData, onSetFieldValue }:
</div> </div>
); );
})} })}
<button <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
type="button"
onClick={() => arrayHelpers.push({ label: "", value: "" })}
className={`mr-2 border p-2 rounded-lg hover:bg-gray-700 hover:cursor-pointer ${values?.customFields && values?.customFields?.length >= 6 ? "opacity-50 cursor-not-allowed" : ""}`}
disabled={values?.customFields && values?.customFields?.length >= 6}
>
Add Custom Field
</button>
{values?.customFields && values?.customFields?.length > 0 && (
<button <button
type="button" type="button"
onClick={() => arrayHelpers.pop()} onClick={() => arrayHelpers.push({ label: "", value: "" })}
className="border p-2 rounded-lg hover:bg-gray-700 hover:cursor-pointer" className={`border p-2 rounded-lg hover:bg-gray-700 hover:cursor-pointer ${values?.customFields && values?.customFields?.length >= 6 ? "opacity-50 cursor-not-allowed" : ""}`}
disabled={values?.customFields && values?.customFields?.length >= 6}
> >
Remove Custom Field Add Custom Field
</button> </button>
)} {values?.customFields && values?.customFields?.length > 0 && (
<button
type="button"
onClick={() => arrayHelpers.pop()}
className="border p-2 rounded-lg hover:bg-gray-700 hover:cursor-pointer"
>
Remove Custom Field
</button>
)}
</div>
</> </>
)} )}
</FieldArray> </FieldArray>

View File

@@ -34,7 +34,7 @@ const OSDFields = ({ isOSDLoading }: OSDFieldsProps) => {
<OSDFieldToggle key={key} value={key} label={key.replace("include", "Include ")} /> <OSDFieldToggle key={key} value={key} label={key.replace("include", "Include ")} />
))} ))}
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="overlayPosition">Overlay Position</label> <label htmlFor="overlayPosition">Overlay Position</label>
<Field <Field
as="select" as="select"
@@ -45,7 +45,7 @@ const OSDFields = ({ isOSDLoading }: OSDFieldsProps) => {
<option value="Bottom">Bottom</option> <option value="Bottom">Bottom</option>
</Field> </Field>
</div> </div>
<div className="flex flex-row justify-between"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="OSDTimestampFormat">OSD Timestamp Format</label> <label htmlFor="OSDTimestampFormat">OSD Timestamp Format</label>
<Field <Field
as="select" as="select"

View File

@@ -65,8 +65,8 @@ const SystemConfig = () => {
return ( return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize> <Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize>
{({ values }) => ( {({ values }) => (
<Form> <Form className="flex flex-col space-y-4">
<div className="flex flex-row justify-between items-center mb-4"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="deviceName">Device Name</label> <label htmlFor="deviceName">Device Name</label>
<Field <Field
name="deviceName" name="deviceName"
@@ -76,7 +76,7 @@ const SystemConfig = () => {
autoComplete="off" autoComplete="off"
/> />
</div> </div>
<div className="flex flex-row justify-between items-center mb-4"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="timeZone">Timezone</label> <label htmlFor="timeZone">Timezone</label>
<Field <Field
name="timeZone" name="timeZone"
@@ -91,7 +91,7 @@ const SystemConfig = () => {
))} ))}
</Field> </Field>
</div> </div>
<div className="flex flex-row justify-between items-center mb-4"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="timeSource">Time Source</label> <label htmlFor="timeSource">Time Source</label>
<Field <Field
name="timeSource" name="timeSource"
@@ -106,8 +106,7 @@ const SystemConfig = () => {
))} ))}
</Field> </Field>
</div> </div>
<div className="flex flex-col md:flex-row space-y-4 justify-between">
<div className="flex flex-row justify-between items-center mb-4">
<label htmlFor="SNTPServer">SNTP Server</label> <label htmlFor="SNTPServer">SNTP Server</label>
<Field <Field
name="SNTPServer" name="SNTPServer"
@@ -117,7 +116,7 @@ const SystemConfig = () => {
autoComplete="off" autoComplete="off"
/> />
</div> </div>
<div className="flex flex-row justify-between items-center mb-4"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="SNTPInterval">SNTP Interval</label> <label htmlFor="SNTPInterval">SNTP Interval</label>
<Field <Field
name="SNTPInterval" name="SNTPInterval"
@@ -127,7 +126,7 @@ const SystemConfig = () => {
autoComplete="off" autoComplete="off"
/> />
</div> </div>
<div className="flex flex-row justify-between items-center mb-4"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="subnetMask">Subnet Mask</label> <label htmlFor="subnetMask">Subnet Mask</label>
<Field <Field
name="subnetMask" name="subnetMask"
@@ -137,7 +136,7 @@ const SystemConfig = () => {
autoComplete="off" autoComplete="off"
/> />
</div> </div>
<div className="flex flex-row justify-between items-center mb-4"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="ipAddress">IP Address</label> <label htmlFor="ipAddress">IP Address</label>
<Field <Field
name="ipAddress" name="ipAddress"
@@ -147,7 +146,7 @@ const SystemConfig = () => {
autoComplete="off" autoComplete="off"
/> />
</div> </div>
<div className="flex flex-row justify-between items-center mb-4"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="gateway">Gateway</label> <label htmlFor="gateway">Gateway</label>
<Field <Field
name="gateway" name="gateway"
@@ -157,7 +156,7 @@ const SystemConfig = () => {
autoComplete="off" autoComplete="off"
/> />
</div> </div>
<div className="flex flex-row justify-between items-center mb-4"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="primaryServer">Primary DNS Server</label> <label htmlFor="primaryServer">Primary DNS Server</label>
<Field <Field
name="primaryServer" name="primaryServer"
@@ -167,7 +166,7 @@ const SystemConfig = () => {
autoComplete="off" autoComplete="off"
/> />
</div> </div>
<div className="flex flex-row justify-between items-center mb-4"> <div className="flex flex-col md:flex-row space-y-4 justify-between">
<label htmlFor="secondaryServer">Secondary DNS Server</label> <label htmlFor="secondaryServer">Secondary DNS Server</label>
<Field <Field
name="secondaryServer" name="secondaryServer"
@@ -220,7 +219,7 @@ const SystemConfig = () => {
</div> </div>
<button <button
type="submit" type="submit"
className="px-4 py-2 bg-green-700 text-white rounded-lg hover:bg-green-800 hover:cursor-pointer" className="w-full md:w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5 hover:cursor-pointer"
disabled={isLoading} disabled={isLoading}
> >
{isLoading ? "Saving..." : "Save Settings"} {isLoading ? "Saving..." : "Save Settings"}

View File

@@ -0,0 +1,17 @@
import { useQuery } from "@tanstack/react-query";
import { CAMBASE } from "../utils/config";
const fetchVersions = async () => {
const response = await fetch(`${CAMBASE}/api/versions`);
if (!response.ok) throw new Error("Cannot get Versions");
return response.json();
};
export const useGetVersions = () => {
const versionsQuery = useQuery({
queryKey: ["getversions"],
queryFn: fetchVersions,
});
return { versionsQuery };
};

View File

@@ -6,7 +6,10 @@ import { AppProviders } from "./app/providers/AppProviders";
import "./index.css"; import "./index.css";
import Modal from "react-modal"; import Modal from "react-modal";
const router = createRouter({ routeTree }); const router = createRouter({
routeTree,
basepath: "/bayiq",
});
Modal.setAppElement("#root"); Modal.setAppElement("#root");

View File

@@ -11,7 +11,7 @@
import { Route as rootRouteImport } from './routes/__root' import { Route as rootRouteImport } from './routes/__root'
import { Route as SettingsRouteImport } from './routes/settings' import { Route as SettingsRouteImport } from './routes/settings'
import { Route as OutputRouteImport } from './routes/output' import { Route as OutputRouteImport } from './routes/output'
import { Route as BaywatchRouteImport } from './routes/baywatch' import { Route as CamerasRouteImport } from './routes/cameras'
import { Route as AboutRouteImport } from './routes/about' import { Route as AboutRouteImport } from './routes/about'
import { Route as IndexRouteImport } from './routes/index' import { Route as IndexRouteImport } from './routes/index'
@@ -25,9 +25,9 @@ const OutputRoute = OutputRouteImport.update({
path: '/output', path: '/output',
getParentRoute: () => rootRouteImport, getParentRoute: () => rootRouteImport,
} as any) } as any)
const BaywatchRoute = BaywatchRouteImport.update({ const CamerasRoute = CamerasRouteImport.update({
id: '/baywatch', id: '/cameras',
path: '/baywatch', path: '/cameras',
getParentRoute: () => rootRouteImport, getParentRoute: () => rootRouteImport,
} as any) } as any)
const AboutRoute = AboutRouteImport.update({ const AboutRoute = AboutRouteImport.update({
@@ -44,14 +44,14 @@ const IndexRoute = IndexRouteImport.update({
export interface FileRoutesByFullPath { export interface FileRoutesByFullPath {
'/': typeof IndexRoute '/': typeof IndexRoute
'/about': typeof AboutRoute '/about': typeof AboutRoute
'/baywatch': typeof BaywatchRoute '/cameras': typeof CamerasRoute
'/output': typeof OutputRoute '/output': typeof OutputRoute
'/settings': typeof SettingsRoute '/settings': typeof SettingsRoute
} }
export interface FileRoutesByTo { export interface FileRoutesByTo {
'/': typeof IndexRoute '/': typeof IndexRoute
'/about': typeof AboutRoute '/about': typeof AboutRoute
'/baywatch': typeof BaywatchRoute '/cameras': typeof CamerasRoute
'/output': typeof OutputRoute '/output': typeof OutputRoute
'/settings': typeof SettingsRoute '/settings': typeof SettingsRoute
} }
@@ -59,22 +59,22 @@ export interface FileRoutesById {
__root__: typeof rootRouteImport __root__: typeof rootRouteImport
'/': typeof IndexRoute '/': typeof IndexRoute
'/about': typeof AboutRoute '/about': typeof AboutRoute
'/baywatch': typeof BaywatchRoute '/cameras': typeof CamerasRoute
'/output': typeof OutputRoute '/output': typeof OutputRoute
'/settings': typeof SettingsRoute '/settings': typeof SettingsRoute
} }
export interface FileRouteTypes { export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/about' | '/baywatch' | '/output' | '/settings' fullPaths: '/' | '/about' | '/cameras' | '/output' | '/settings'
fileRoutesByTo: FileRoutesByTo fileRoutesByTo: FileRoutesByTo
to: '/' | '/about' | '/baywatch' | '/output' | '/settings' to: '/' | '/about' | '/cameras' | '/output' | '/settings'
id: '__root__' | '/' | '/about' | '/baywatch' | '/output' | '/settings' id: '__root__' | '/' | '/about' | '/cameras' | '/output' | '/settings'
fileRoutesById: FileRoutesById fileRoutesById: FileRoutesById
} }
export interface RootRouteChildren { export interface RootRouteChildren {
IndexRoute: typeof IndexRoute IndexRoute: typeof IndexRoute
AboutRoute: typeof AboutRoute AboutRoute: typeof AboutRoute
BaywatchRoute: typeof BaywatchRoute CamerasRoute: typeof CamerasRoute
OutputRoute: typeof OutputRoute OutputRoute: typeof OutputRoute
SettingsRoute: typeof SettingsRoute SettingsRoute: typeof SettingsRoute
} }
@@ -95,11 +95,11 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof OutputRouteImport preLoaderRoute: typeof OutputRouteImport
parentRoute: typeof rootRouteImport parentRoute: typeof rootRouteImport
} }
'/baywatch': { '/cameras': {
id: '/baywatch' id: '/cameras'
path: '/baywatch' path: '/cameras'
fullPath: '/baywatch' fullPath: '/cameras'
preLoaderRoute: typeof BaywatchRouteImport preLoaderRoute: typeof CamerasRouteImport
parentRoute: typeof rootRouteImport parentRoute: typeof rootRouteImport
} }
'/about': { '/about': {
@@ -122,7 +122,7 @@ declare module '@tanstack/react-router' {
const rootRouteChildren: RootRouteChildren = { const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute, IndexRoute: IndexRoute,
AboutRoute: AboutRoute, AboutRoute: AboutRoute,
BaywatchRoute: BaywatchRoute, CamerasRoute: CamerasRoute,
OutputRoute: OutputRoute, OutputRoute: OutputRoute,
SettingsRoute: SettingsRoute, SettingsRoute: SettingsRoute,
} }

View File

@@ -1,14 +1,10 @@
import { createFileRoute } from "@tanstack/react-router"; import { createFileRoute } from "@tanstack/react-router";
import CameraGrid from "../features/cameras/components/CameraGrid"; import CameraGrid from "../features/cameras/components/CameraGrid";
export const Route = createFileRoute("/baywatch")({ export const Route = createFileRoute("/cameras")({
component: RouteComponent, component: RouteComponent,
}); });
function RouteComponent() { function RouteComponent() {
return ( return <CameraGrid />;
<div>
<CameraGrid />
</div>
);
} }

View File

@@ -6,9 +6,5 @@ export const Route = createFileRoute("/output")({
}); });
function RouteComponent() { function RouteComponent() {
return ( return <OutputForms />;
<div>
<OutputForms />
</div>
);
} }

View File

@@ -6,9 +6,5 @@ export const Route = createFileRoute("/settings")({
}); });
function RouteComponent() { function RouteComponent() {
return ( return <Settings />;
<div>
<Settings />
</div>
);
} }

View File

@@ -1,3 +1,5 @@
import type { CameraID } from "../app/config/cameraConfig";
export type WebSocketContextValue = { export type WebSocketContextValue = {
connected: boolean; connected: boolean;
send?: (msg: unknown) => void; send?: (msg: unknown) => void;
@@ -11,6 +13,10 @@ export type InfoBarData = {
"thread-count": string; "thread-count": string;
}; };
export type CameraZoomData = {
magnificationLevel: string;
};
export type StatusIndicator = "neutral-quaternary" | "dark" | "info" | "success" | "warning" | "danger"; export type StatusIndicator = "neutral-quaternary" | "dark" | "info" | "success" | "warning" | "danger";
export type Region = { export type Region = {
name: string; name: string;
@@ -124,52 +130,42 @@ export type OptionalBOF2LaneIDs = {
}; };
export type CameraFeedState = { export type CameraFeedState = {
cameraFeedID: "A" | "B" | "C"; cameraFeedID: CameraID;
paintedCells: { paintedCells: Record<CameraID, Map<string, PaintedCell>>;
A: Map<string, PaintedCell>;
B: Map<string, PaintedCell>; regionsByCamera: Record<CameraID, Region[]>;
C: Map<string, PaintedCell>;
};
regionsByCamera: {
A: Region[];
B: Region[];
C: Region[];
};
selectedRegionIndex: number; selectedRegionIndex: number;
modeByCamera: { modeByCamera: Record<CameraID, string>;
A: string;
B: string;
C: string;
};
tabIndex?: number; tabIndex?: number;
zoomLevel: Record<CameraID, number>;
}; };
export type CameraFeedAction = export type CameraFeedAction =
| { | {
type: "SET_CAMERA_FEED"; type: "SET_CAMERA_FEED";
payload: "A" | "B" | "C"; payload: CameraID;
} }
| { | {
type: "CHANGE_MODE"; type: "CHANGE_MODE";
payload: { cameraFeedID: "A" | "B" | "C"; mode: string }; payload: { cameraFeedID: CameraID; mode: string };
} }
| { type: "SET_SELECTED_REGION_INDEX"; payload: number } | { type: "SET_SELECTED_REGION_INDEX"; payload: number }
| { | {
type: "SET_SELECTED_REGION_COLOUR"; type: "SET_SELECTED_REGION_COLOUR";
payload: { cameraFeedID: "A" | "B" | "C"; regionName: string; newColour: string }; payload: { cameraFeedID: CameraID; regionName: string; newColour: string };
} }
| { | {
type: "ADD_NEW_REGION"; type: "ADD_NEW_REGION";
payload: { cameraFeedID: "A" | "B" | "C"; regionName: string; brushColour: string }; payload: { cameraFeedID: CameraID; regionName: string; brushColour: string };
} }
| { | {
type: "REMOVE_REGION"; type: "REMOVE_REGION";
payload: { cameraFeedID: "A" | "B" | "C"; regionName: string }; payload: { cameraFeedID: CameraID; regionName: string };
} }
| { | {
type: "RESET_PAINTED_CELLS"; type: "RESET_PAINTED_CELLS";
payload: { cameraFeedID: "A" | "B" | "C"; paintedCells: Map<string, PaintedCell> }; payload: { cameraFeedID: CameraID; paintedCells: Map<string, PaintedCell> };
} }
| { | {
type: "SET_CAMERA_FEED_DATA"; type: "SET_CAMERA_FEED_DATA";
@@ -177,6 +173,10 @@ export type CameraFeedAction =
} }
| { | {
type: "RESET_CAMERA_FEED"; type: "RESET_CAMERA_FEED";
}
| {
type: "SET_ZOOM_LEVEL";
payload: { cameraFeedID: CameraID; zoomLevel: number };
}; };
export type DecodeReading = { export type DecodeReading = {
@@ -189,6 +189,7 @@ export type DecodeReading = {
duplicate?: true; duplicate?: true;
firstSeenTimeHumane: string; firstSeenTimeHumane: string;
lastSeenTimeHumane: string; lastSeenTimeHumane: string;
plate?: string;
}; };
export type ColourData = { export type ColourData = {
@@ -197,7 +198,7 @@ export type ColourData = {
}; };
export type ColourDetectionPayload = { export type ColourDetectionPayload = {
cameraFeedID: "A" | "B" | "C"; cameraFeedID: CameraID;
regions: ColourData[]; regions: ColourData[];
}; };
@@ -227,3 +228,18 @@ export type BlackBoardOptions = {
path?: string; path?: string;
value?: object | string | number | (string | number)[] | null; value?: object | string | number | (string | number)[] | null;
}; };
export type CameraZoomConfig = { cameraFeedID: string; zoomLevel: number };
export type versionInfo = {
version: string;
revision: string;
buildtime: string;
appname: string;
MAC: string;
timeStamp: number;
UUID: string;
proquint: string;
"Serial No.": string;
"Model No.": string;
};

76
src/ui/DevModal.tsx Normal file
View File

@@ -0,0 +1,76 @@
import type { versionInfo } from "../types/types";
import ModalComponent from "./ModalComponent";
type DevModalProps = {
isDevModalOpen: boolean;
handleClose: () => void;
data: versionInfo;
};
const DevModal = ({ isDevModalOpen, handleClose, data }: DevModalProps) => {
const uiName = __APP_NAME__;
const uiVersion = __APP_VERSION__;
const commitID = __GIT_COMMIT__;
const commitTimeStamp = __GIT_TIMESTAMP__;
return (
<ModalComponent isModalOpen={isDevModalOpen} close={handleClose}>
<div className="space-y-6">
<div className="border-b border-gray-600 pb-3">
<h2 className="text-2xl font-bold text-gray-100">System Information</h2>
<p className="text-sm text-gray-400 mt-1">Application version details</p>
</div>
<div className="space-y-3">
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wide">Frontend (UI)</h3>
<div className="bg-gray-800/50 rounded-lg p-4 space-y-3">
<div className="flex justify-between items-center border-b border-gray-700 pb-2">
<span className="text-gray-400 text-sm">Name</span>
<span className="text-gray-200 font-mono font-semibold">{uiName}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-400 text-sm">Version</span>
<span className="text-gray-200 font-mono font-semibold">{uiVersion}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-400 text-sm">Revision (Commit ID)</span>
<span className="bg-[#233241] p-2 rounded-md text-gray-200 font-mono text-sm">{commitID}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-400 text-sm">Build Time</span>
<span className="text-gray-200 font-mono text-sm">{commitTimeStamp}</span>
</div>
</div>
</div>
<div className="space-y-3">
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wide">Backend</h3>
<div className="bg-gray-800/50 rounded-lg p-4 space-y-3">
<div className="flex justify-between items-center border-b border-gray-700 pb-2">
<span className="text-gray-400 text-sm"> Name</span>
<span className="text-gray-200 font-mono font-semibold">{data?.appname || "N/A"}</span>
</div>
<div className="flex justify-between items-center pb-2">
<span className="text-gray-400 text-sm">Version</span>
<span className="text-gray-200 font-mono font-semibold">{data?.version || "N/A"}</span>
</div>
<div className="flex justify-between items-center pb-2">
<span className="text-gray-400 text-sm">Revision (Commit ID)</span>
<span className="bg-[#233241] p-2 rounded-md text-gray-200 font-mono text-sm">
{data?.revision || "N/A"}
</span>
</div>
<div className="flex justify-between items-center pb-2">
<span className="text-gray-400 text-sm">Build Time</span>
<span className="text-gray-200 font-mono text-sm">{data?.buildtime || "N/A"}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-400 text-sm">MAC Address</span>
<span className="text-gray-200 font-mono text-sm">{data?.MAC || "N/A"}</span>
</div>
</div>
</div>
</div>
</ModalComponent>
);
};
export default DevModal;

View File

@@ -1,11 +1,25 @@
import { useState } from "react";
import Logo from "/MAV.svg"; import Logo from "/MAV.svg";
import DevModal from "./DevModal";
import { useGetVersions } from "../hooks/useGetVersions";
const Footer = () => { const Footer = () => {
const [isDevModalOpen, setDevModalOpen] = useState(false);
const { versionsQuery } = useGetVersions();
const versionData = versionsQuery?.data;
const handleClick = () => {
setDevModalOpen(true);
};
return ( return (
<footer className="bg-gray-900 border-t border-gray-700 text-white py-5 text-left p-8 h-30 mt-5 flex flex-col space-y-4 "> <>
<img src={Logo} alt="Logo" width={100} height={100} /> <footer className="bg-gray-900 border-t border-gray-700 text-white py-5 text-left p-8 h-30 mt-5 flex flex-col space-y-4 ">
<p className="text-sm">{new Date().getFullYear()} MAV Systems &copy; All rights reserved.</p> <img src={Logo} alt="Logo" width={100} height={100} onClick={handleClick} />
</footer> <p className="text-sm">{new Date().getFullYear()} MAV Systems &copy; All rights reserved.</p>
</footer>
<DevModal isDevModalOpen={isDevModalOpen} handleClose={() => setDevModalOpen(false)} data={versionData} />
</>
); );
}; };

View File

@@ -1,15 +1,29 @@
import { useState } from "react";
import { Link } from "@tanstack/react-router"; import { Link } from "@tanstack/react-router";
import Logo from "/MAV.svg"; import Logo from "/MAV.svg";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBars } from "@fortawesome/free-solid-svg-icons";
const Header = () => { const Header = () => {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const toggleMenu = () => {
setIsMenuOpen(!isMenuOpen);
};
return ( return (
<header className="bg-[#253445] p-4 flex border-b border-gray-500 justify-between items-center"> <nav className="bg-[#253445] p-4 flex border-b border-gray-500 justify-between items-center md:flex-row flex-col">
<div className="w-28"> <div className="flex flex-row justify-between w-full items-center">
<Link to={"/"}> <div className="w-28">
<img src={Logo} alt="Logo" width={150} height={150} /> <Link to={"/"} onClick={() => setIsMenuOpen(false)}>
</Link> <img src={Logo} alt="Logo" width={150} height={150} />
</Link>
</div>
<div className="hover:cursor-pointer md:hidden" onClick={toggleMenu}>
<FontAwesomeIcon icon={faBars} />
</div>
</div> </div>
<div className="flex gap-4 text-lg items-center">
<div className="md:flex hidden gap-4 text-lg items-center">
<Link <Link
to="/" to="/"
className="[&.active]:font-bold [&.active]:bg-gray-700 p-2 rounded-lg flex items-center gap-2 hover:bg-gray-700" className="[&.active]:font-bold [&.active]:bg-gray-700 p-2 rounded-lg flex items-center gap-2 hover:bg-gray-700"
@@ -19,7 +33,7 @@ const Header = () => {
</Link> </Link>
<Link <Link
to="/baywatch" to="/cameras"
className="[&.active]:font-bold [&.active]:bg-gray-700 p-2 rounded-lg flex items-center gap-2 hover:bg-gray-700" className="[&.active]:font-bold [&.active]:bg-gray-700 p-2 rounded-lg flex items-center gap-2 hover:bg-gray-700"
> >
Cameras Cameras
@@ -37,7 +51,26 @@ const Header = () => {
Settings Settings
</Link> </Link>
</div> </div>
</header> {/* mobile menu */}
{isMenuOpen && (
<div className="md:hidden flex flex-col w-full mt-4 gap-4 text-lg items-end">
<Link to="/" className="" onClick={toggleMenu}>
{/* <FontAwesomeIcon icon={faGaugeHigh} /> */}
Dashboard
</Link>
<Link to="/cameras" className="" onClick={toggleMenu}>
{/* <FontAwesomeIcon icon={faGaugeHigh} /> */}
Cameras
</Link>
<Link to="/output" className="" onClick={toggleMenu}>
Output
</Link>
<Link to="/settings" className="" onClick={toggleMenu}>
Settings
</Link>
</div>
)}
</nav>
); );
}; };

View File

@@ -23,6 +23,14 @@ const ModalComponent = ({ isModalOpen, children, close }: ModalComponentProps) =
}, },
}} }}
> >
<div className="flex justify-end">
<button
onClick={close}
className="bg-gray-700 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded-lg mb-4 hover:cursor-pointer"
>
Close
</button>
</div>
{children} {children}
</Modal> </Modal>
); );

View File

@@ -0,0 +1,24 @@
import Slider from "rc-slider";
import "rc-slider/assets/index.css";
type SliderComponentProps = {
id: string;
onChange: (value: number | number[]) => void;
value?: number;
min?: number;
max?: number;
step?: number;
};
const SliderComponent = ({ id, onChange, value = 0, min = 0, max = 100, step = 1 }: SliderComponentProps) => {
const handleChange = (val: number | number[]) => {
onChange(val);
};
return (
<>
<Slider id={id} onChange={handleChange} value={value} min={min} max={max} step={step} />
</>
);
};
export default SliderComponent;

View File

@@ -1 +1,9 @@
export const CAMBASE = import.meta.env.VITE_BASEURL; export const cambase = import.meta.env.VITE_BASEURL;
export const CAMBASEWS = import.meta.env.VITE_BASE_WS;
const environment = import.meta.env.MODE;
export const CAMBASE = environment === "development" ? cambase : window.location.origin;
export const CAMBASE_WS = environment === "development" ? CAMBASEWS : window.location.origin.replace(/^http/, "ws");

6
src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
/// <reference types="vite/client" />
declare const __APP_NAME__: string;
declare const __APP_VERSION__: string;
declare const __GIT_COMMIT__: string;
declare const __GIT_TIMESTAMP__: string;

View File

@@ -2,13 +2,38 @@ import { defineConfig } from "vite";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite"; import tailwindcss from "@tailwindcss/vite";
import { tanstackRouter } from "@tanstack/router-plugin/vite"; import { tanstackRouter } from "@tanstack/router-plugin/vite";
import pkg from "./package.json";
import { execSync } from "child_process";
const gitCommitHash = (() => {
try {
return execSync("git rev-parse --short HEAD").toString().trim();
} catch {
return "unknown";
}
})();
const gitCommitTimeStamp = (() => {
try {
return execSync("git log -1 --format=%cd --date=iso").toString().trim();
} catch {
return "unknown";
}
})();
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig({
base: "/bayiq",
define: {
__APP_NAME__: JSON.stringify(pkg.name),
__APP_VERSION__: JSON.stringify(pkg.version),
__GIT_COMMIT__: JSON.stringify(gitCommitHash),
__GIT_TIMESTAMP__: JSON.stringify(gitCommitTimeStamp),
},
plugins: [ plugins: [
tanstackRouter({ tanstackRouter({
target: "react", target: "react",
autoCodeSplitting: true, autoCodeSplitting: false,
}), }),
react(), react(),
tailwindcss(), tailwindcss(),
@@ -21,4 +46,11 @@ export default defineConfig({
}, },
}, },
}, },
build: {
rollupOptions: {
output: {
manualChunks: undefined,
},
},
},
}); });

View File

@@ -226,6 +226,11 @@
"@babel/plugin-transform-modules-commonjs" "^7.27.1" "@babel/plugin-transform-modules-commonjs" "^7.27.1"
"@babel/plugin-transform-typescript" "^7.28.5" "@babel/plugin-transform-typescript" "^7.28.5"
"@babel/runtime@^7.10.1", "@babel/runtime@^7.18.3":
version "7.28.4"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.28.4.tgz#a70226016fabe25c5783b2f22d3e1c9bc5ca3326"
integrity sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==
"@babel/template@^7.27.2": "@babel/template@^7.27.2":
version "7.27.2" version "7.27.2"
resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.27.2.tgz#fa78ceed3c4e7b63ebf6cb39e5852fca45f6809d" resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.27.2.tgz#fa78ceed3c4e7b63ebf6cb39e5852fca45f6809d"
@@ -1314,6 +1319,11 @@ chokidar@^3.6.0:
optionalDependencies: optionalDependencies:
fsevents "~2.3.2" fsevents "~2.3.2"
classnames@^2.2.5:
version "2.5.1"
resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.5.1.tgz#ba774c614be0f016da105c858e7159eae8e7687b"
integrity sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==
clsx@^2.0.0, clsx@^2.1.1: clsx@^2.0.0, clsx@^2.1.1:
version "2.1.1" version "2.1.1"
resolved "https://registry.yarnpkg.com/clsx/-/clsx-2.1.1.tgz#eed397c9fd8bd882bfb18deab7102049a2f32999" resolved "https://registry.yarnpkg.com/clsx/-/clsx-2.1.1.tgz#eed397c9fd8bd882bfb18deab7102049a2f32999"
@@ -2142,6 +2152,23 @@ queue-microtask@^1.2.2:
resolved "https://registry.yarnpkg.com/queue-microtask/-/queue-microtask-1.2.3.tgz#4929228bbc724dfac43e0efb058caf7b6cfb6243" resolved "https://registry.yarnpkg.com/queue-microtask/-/queue-microtask-1.2.3.tgz#4929228bbc724dfac43e0efb058caf7b6cfb6243"
integrity sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A== integrity sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==
rc-slider@^11.1.9:
version "11.1.9"
resolved "https://registry.yarnpkg.com/rc-slider/-/rc-slider-11.1.9.tgz#d872130fbf4ec51f28543d62e90451091d6f5208"
integrity sha512-h8IknhzSh3FEM9u8ivkskh+Ef4Yo4JRIY2nj7MrH6GQmrwV6mcpJf5/4KgH5JaVI1H3E52yCdpOlVyGZIeph5A==
dependencies:
"@babel/runtime" "^7.10.1"
classnames "^2.2.5"
rc-util "^5.36.0"
rc-util@^5.36.0:
version "5.44.4"
resolved "https://registry.yarnpkg.com/rc-util/-/rc-util-5.44.4.tgz#89ee9037683cca01cd60f1a6bbda761457dd6ba5"
integrity sha512-resueRJzmHG9Q6rI/DfK6Kdv9/Lfls05vzMs1Sk3M2P+3cJa+MakaZyWY8IPfehVuhPJFKrIY1IK4GqbiaiY5w==
dependencies:
"@babel/runtime" "^7.18.3"
react-is "^18.2.0"
react-dom@^19.2.0: react-dom@^19.2.0:
version "19.2.0" version "19.2.0"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-19.2.0.tgz#00ed1e959c365e9a9d48f8918377465466ec3af8" resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-19.2.0.tgz#00ed1e959c365e9a9d48f8918377465466ec3af8"
@@ -2159,6 +2186,11 @@ react-is@^16.13.1, react-is@^16.7.0:
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==
react-is@^18.2.0:
version "18.3.1"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.3.1.tgz#e83557dc12eae63a99e003a46388b1dcbb44db7e"
integrity sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==
react-konva@^19.2.0: react-konva@^19.2.0:
version "19.2.0" version "19.2.0"
resolved "https://registry.yarnpkg.com/react-konva/-/react-konva-19.2.0.tgz#b4cc5d73cd6d642569e4df36a0139996c3dcf8e6" resolved "https://registry.yarnpkg.com/react-konva/-/react-konva-19.2.0.tgz#b4cc5d73cd6d642569e4df36a0139996c3dcf8e6"
@@ -2461,6 +2493,11 @@ uri-js@^4.2.2:
dependencies: dependencies:
punycode "^2.1.0" punycode "^2.1.0"
use-debounce@^10.0.6:
version "10.0.6"
resolved "https://registry.yarnpkg.com/use-debounce/-/use-debounce-10.0.6.tgz#e05060a5e561432ec740c653698f3eb162bd28ec"
integrity sha512-C5OtPyhAZgVoteO9heXMTdW7v/IbFI+8bSVKYCJrSmiWWCLsbUxiBSp4t9v0hNBTGY97bT72ydDIDyGSFWfwXg==
use-sync-external-store@^1.6.0: use-sync-external-store@^1.6.0:
version "1.6.0" version "1.6.0"
resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz#b174bfa65cb2b526732d9f2ac0a408027876f32d" resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz#b174bfa65cb2b526732d9f2ac0a408027876f32d"