Skip to content

Commit

Permalink
Merge pull request #65 from Ritika8081/web-worker
Browse files Browse the repository at this point in the history
Updated code to provide more control over data plotting.
  • Loading branch information
lorforlinux authored Dec 28, 2024
2 parents 61e7ae3 + bbcacb4 commit f947aaf
Show file tree
Hide file tree
Showing 6 changed files with 168 additions and 31 deletions.
54 changes: 35 additions & 19 deletions src/components/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ interface CanvasProps {
selectedBits: BitSelection;
isDisplay: boolean;
canvasCount?: number;
currentValue?:number;
Zoom: number;
currentSnapshot: number;
snapShotRef: React.MutableRefObject<boolean[]>;
Expand All @@ -27,6 +28,7 @@ const Canvas = forwardRef(
selectedBits,
isDisplay,
canvasCount = 6, // default value in case not provided
currentValue=4,
Zoom,
currentSnapshot,
snapShotRef,
Expand All @@ -37,14 +39,14 @@ const Canvas = forwardRef(
let previousCounter: number | null = null; // Variable to store the previous counter value for loss detection
const canvasContainerRef = useRef<HTMLDivElement>(null);
const [numChannels, setNumChannels] = useState<number>(canvasCount);
const numXRef = useRef<number>(2000); // To track the calculated value
const [canvases, setCanvases] = useState<HTMLCanvasElement[]>([]);
const [samplingRate,setSamplingRate]=useState<number>(500);
const [wglPlots, setWglPlots] = useState<WebglPlot[]>([]);
const [lines, setLines] = useState<WebglLine[]>([]);
const linesRef = useRef<WebglLine[]>([]);
const samplingRate = 500; // Set the sampling rate in Hz
const sweepPositions = useRef<number[]>(new Array(6).fill(0)); // Array for sweep positions
const currentSweepPos = useRef<number[]>(new Array(6).fill(0)); // Array for sweep positions
let numX: number;
const array3DRef = useRef<number[][][]>(
Array.from({ length: 6 }, () =>
Array.from({ length: 6 }, () => Array())
Expand All @@ -53,21 +55,26 @@ const Canvas = forwardRef(
const activebuffer = useRef(0); // Initialize useRef with 0
const indicesRef = useRef<number[]>([]); // Use `useRef` for indices

//select point
const getpoints = useCallback((bits: BitSelection): number => {
switch (bits) {
case "ten":
return samplingRate * 2;
return 250;
case "twelve":
return samplingRate * 4;
case "fourteen":
return samplingRate * 4;
case "sixteen":
return samplingRate * 4;
return 500;
default:
return 0; // Or any other fallback value you'd like
return 500; // Default fallback
}
}, []);
numX = getpoints(selectedBits);


useEffect(() => {
numXRef.current= (getpoints(selectedBits) * currentValue)+1;

}, [ currentValue]);

const prevCanvasCountRef = useRef<number>(canvasCount);

const processIncomingData = (incomingData: number[]) => {
Expand All @@ -81,18 +88,18 @@ const Canvas = forwardRef(
}
prevCanvasCountRef.current = canvasCount;
}
if (array3DRef.current[activebuffer.current][i].length >= numX) {
if (array3DRef.current[activebuffer.current][i].length >= numXRef.current) {
array3DRef.current[activebuffer.current][i] = [];
}
array3DRef.current[activebuffer.current][i].push(incomingData[i + 1]);

if (array3DRef.current[activebuffer.current][i].length < numX && !pauseRef.current) {
if (array3DRef.current[activebuffer.current][i].length < numXRef.current && !pauseRef.current) {
array3DRef.current[activebuffer.current][i] = [];
}
}


if (array3DRef.current[activebuffer.current][0].length >= numX) {
if (array3DRef.current[activebuffer.current][0].length >= numXRef.current) {
snapShotRef.current[activebuffer.current] = true;
activebuffer.current = (activebuffer.current + 1) % 6;
snapShotRef.current[activebuffer.current] = false;
Expand All @@ -107,6 +114,14 @@ const Canvas = forwardRef(
setNumChannels(canvasCount);
}, [canvasCount]);


useEffect(() => {
// Reset when currentValue changes
currentSweepPos.current = new Array(numChannels).fill(0);
sweepPositions.current = new Array(numChannels).fill(0);
}, [currentValue]);


useImperativeHandle(
ref,
() => ({
Expand All @@ -116,6 +131,7 @@ const Canvas = forwardRef(
currentSweepPos.current = new Array(numChannels).fill(0);
sweepPositions.current = new Array(numChannels).fill(0);
}

if (pauseRef.current) {
processIncomingData(data);
updatePlots(data, Zoom);
Expand All @@ -133,7 +149,7 @@ const Canvas = forwardRef(
previousCounter = data[0]; // Update the previous counter with the current counter
},
}),
[Zoom, numChannels]
[Zoom, numChannels,currentValue]
);

const createCanvases = () => {
Expand Down Expand Up @@ -170,7 +186,7 @@ const Canvas = forwardRef(
const opacityLightMajor = "0.4"; // Opacity for every 5th line in light theme
const opacityLightMinor = "0.1"; // Opacity for other lines in light theme
const distanceminor = samplingRate * 0.04;
const numGridLines = numX / distanceminor;
const numGridLines = getpoints(selectedBits)*4 / distanceminor;
for (let j = 1; j < numGridLines; j++) {
const gridLineX = document.createElement("div");
gridLineX.className = "absolute bg-[rgb(128,128,128)]";
Expand Down Expand Up @@ -226,10 +242,10 @@ const Canvas = forwardRef(
const wglp = new WebglPlot(canvas);
newWglPlots.push(wglp);
wglp.gScaleY = Zoom;
const line = new WebglLine(getLineColor(i, theme), numX);
const line = new WebglLine(getLineColor(i, theme), numXRef.current);
wglp.gOffsetY = 0;
line.offsetY = 0;
line.lineSpaceX(-1, 2 / numX);
line.lineSpaceX(-1, 2 / numXRef.current);

wglp.addLine(line);
newLines.push(line);
Expand Down Expand Up @@ -294,19 +310,19 @@ const Canvas = forwardRef(
line.setY(currentSweepPos.current[i] % line.numPoints, data[i + 1]);

// Clear the next point to create a gap (optional, for visual effect)
const clearPosition = (currentSweepPos.current[i] + (numX / 100)) % line.numPoints;
const clearPosition = (currentSweepPos.current[i] + (numXRef.current / 100)) % line.numPoints;
line.setY(clearPosition, NaN);

// Increment the sweep position for the current line
sweepPositions.current[i] = (currentSweepPos.current[i] + 1) % line.numPoints;
});
},
[lines, wglPlots, numChannels, theme]
[lines, wglPlots, numChannels, theme,currentValue]
);

useEffect(() => {
createCanvases();
}, [numChannels, theme]);
}, [numChannels, theme,currentValue]);


const animate = useCallback(() => {
Expand All @@ -318,7 +334,7 @@ const Canvas = forwardRef(
wglPlots.forEach((wglp) => wglp.update());
requestAnimationFrame(animate); // Continue the animation loop
}
}, [currentSnapshot, numX, pauseRef.current, wglPlots, Zoom]);
}, [currentSnapshot, numXRef.current, pauseRef.current, wglPlots, Zoom]);


const updatePlotSnapshot = (currentSnapshot: number) => {
Expand Down
85 changes: 79 additions & 6 deletions src/components/Connection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ interface ConnectionProps {
setCanvasCount: React.Dispatch<React.SetStateAction<number>>; // Specify type for setCanvasCount
canvasCount: number;
channelCount: number;
currentValue:number;
setCurrentValue: React.Dispatch<React.SetStateAction<number>>;
SetZoom: React.Dispatch<React.SetStateAction<number>>;
SetcurrentSnapshot: React.Dispatch<React.SetStateAction<number>>;
currentSnapshot: number;
Expand All @@ -76,6 +78,8 @@ const Connection: React.FC<ConnectionProps> = ({
snapShotRef,
SetZoom,
Zoom,
currentValue,
setCurrentValue,
}) => {
const [isConnected, setIsConnected] = useState<boolean>(false); // State to track if the device is connected
const isConnectedRef = useRef<boolean>(false); // Ref to track if the device is connected
Expand Down Expand Up @@ -127,6 +131,12 @@ const Connection: React.FC<ConnectionProps> = ({
}
};

const increaseValue = () => {
if(currentValue < 10){
setCurrentValue(currentValue + 1);
}
};

const enabledClicks = (snapShotRef.current?.filter(Boolean).length ?? 0) - 1;

// Enable/Disable left arrow button
Expand Down Expand Up @@ -155,6 +165,12 @@ const Connection: React.FC<ConnectionProps> = ({
setCanvasCount(canvasCount - 1); // Decrease canvas count but not below 1
}
};
const decreaseValue = () => {
if(currentValue > 1){
setCurrentValue(currentValue - 1);
}
};

const toggleShowAllChannels = () => {
if (canvasCount === (detectedBitsRef.current == "twelve" ? 3 : 6)) {
setCanvasCount(1); // If canvasCount is 6, reduce it to 1
Expand Down Expand Up @@ -218,6 +234,14 @@ const Connection: React.FC<ConnectionProps> = ({
});
}
};
const setCanvasCountInWorker = (canvasCount:number) => {
if (!workerRef.current) {
initializeWorker();
}
// Send canvasCount independently to the worker
workerRef.current?.postMessage({ action: 'setCanvasCount', canvasCount: canvasnumbersRef.current });
};
setCanvasCountInWorker(canvasnumbersRef.current);

const processBuffer = async (bufferIndex: number, canvasCount: number) => {
if (!workerRef.current) {
Expand Down Expand Up @@ -890,20 +914,20 @@ const Connection: React.FC<ConnectionProps> = ({
{/* Left-aligned section */}
<div className="absolute left-4 flex items-center mx-0 px-0 space-x-1">
{isRecordingRef.current && (
<div className="flex items-center space-x-1 w-min ml-2">
<button className="flex items-center justify-center px-3 py-2 select-none min-w-20 bg-primary text-destructive whitespace-nowrap rounded-xl"
<div className="flex items-center space-x-1 w-min">
<button className="flex items-center justify-center px-1 py-2 select-none min-w-20 bg-primary text-destructive whitespace-nowrap rounded-xl"
>
{formatTime(recordingElapsedTime)}
</button>
<Separator orientation="vertical" className="bg-primary h-9 ml-2" />
<Separator orientation="vertical" className="bg-primary h-9 " />
<div>
<Popover
open={isEndTimePopoverOpen}
onOpenChange={setIsEndTimePopoverOpen}
>
<PopoverTrigger asChild>
<Button
className="flex items-center justify-center px-3 py-2 select-none min-w-12 text-destructive whitespace-nowrap rounded-xl"
className="flex items-center justify-center px-1 py-2 select-none min-w-10 text-destructive whitespace-nowrap rounded-xl"
variant="destructive"
>
{endTimeRef.current === null ? (
Expand Down Expand Up @@ -968,7 +992,7 @@ const Connection: React.FC<ConnectionProps> = ({
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button className="flex items-center justify-center gap-1 py-2 px-6 sm:py-3 sm:px-8 rounded-xl font-semibold" onClick={handleClick}>
<Button className="flex items-center justify-center gap-1 py-2 px-2 sm:py-3 sm:px-4 rounded-xl font-semibold" onClick={handleClick}>
{isConnected ? (
<>
Disconnect
Expand Down Expand Up @@ -1497,9 +1521,58 @@ const Connection: React.FC<ConnectionProps> = ({
</Tooltip>
</TooltipProvider>
)}
{isConnected && (
<TooltipProvider>
<Tooltip>
<div className="flex items-center mx-0 px-0">
{/* Decrease Current Value */}
<Tooltip>
<TooltipTrigger asChild>
<Button
className="rounded-xl rounded-r-none"
onClick={decreaseValue}
disabled={currentValue == 1}
>
<Minus size={16} />
</Button>
</TooltipTrigger>
</Tooltip>

<Separator orientation="vertical" className="h-full" />

{/* Toggle All Channels Button */}
<Tooltip>
<TooltipTrigger asChild>
<Button
className="flex items-center justify-center px-3 py-2 rounded-none select-none"
>
{currentValue} Sec
</Button>
</TooltipTrigger>
</Tooltip>

<Separator orientation="vertical" className="h-full" />

{/* Increase Canvas Button */}
<Tooltip>
<TooltipTrigger asChild>
<Button
className="rounded-xl rounded-l-none"
onClick={increaseValue}
disabled={currentValue >= 10}
>
<Plus size={16} />
</Button>
</TooltipTrigger>
</Tooltip>
</div>
</Tooltip>
</TooltipProvider>
)}
</div>
</div>
);
};

export default Connection;
export default Connection;

4 changes: 4 additions & 0 deletions src/components/DataPass.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const DataPass = () => {
const [isConnected, setIsConnected] = useState<boolean>(false); // Connection status
const [isDisplay, setIsDisplay] = useState<boolean>(true); // Display state
const [canvasCount, setCanvasCount] = useState<number>(1); // Number of canvases
const [currentValue, setCurrentValue] = useState<number>(4); // To track the current index to show
const [channelCount, setChannelCount] = useState<number>(1); // Number of channels
const canvasRef = useRef<any>(null); // Create a ref for the Canvas component
let previousCounter: number | null = null; // Variable to store the previous counter value for loss detection
Expand Down Expand Up @@ -55,6 +56,7 @@ const DataPass = () => {
selectedBits={selectedBits}
isDisplay={isDisplay}
canvasCount={canvasCount} // Pass canvas count
currentValue={currentValue}
/>
) : (
<Steps />
Expand All @@ -70,6 +72,8 @@ const DataPass = () => {
setIsDisplay={setIsDisplay}
setCanvasCount={setCanvasCount}
canvasCount={canvasCount}
setCurrentValue={setCurrentValue}
currentValue={currentValue}
channelCount={channelCount}
SetZoom={SetZoom}
SetcurrentSnapshot={SetcurrentSnapshot}
Expand Down
7 changes: 4 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
Expand All @@ -22,17 +22,18 @@
"name": "next"
}
],
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
"src/*",
"workers/*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
".next/types/**/*.ts",
"**/*.ts",
"**/*.tsx",
"out/types/**/*.ts"
],
Expand Down
Loading

0 comments on commit f947aaf

Please sign in to comment.