Skip to content

Commit 6b8d789

Browse files
author
Ritika Mishra
committed
updated logic to get all information about board from boardlist file
1 parent f356cde commit 6b8d789

File tree

2 files changed

+157
-124
lines changed

2 files changed

+157
-124
lines changed

src/components/Connection.tsx

Lines changed: 100 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,8 @@ interface ConnectionProps {
5959
setTimeBase: React.Dispatch<React.SetStateAction<number>>;
6060
SetZoom: React.Dispatch<React.SetStateAction<number>>;
6161
SetCurrentSnapshot: React.Dispatch<React.SetStateAction<number>>;
62-
currentSamplingRate:number;
63-
setCurrentSamplingRate :React.Dispatch<React.SetStateAction<number>>;
62+
currentSamplingRate: number;
63+
setCurrentSamplingRate: React.Dispatch<React.SetStateAction<number>>;
6464
currentSnapshot: number;
6565
Zoom: number;
6666
snapShotRef: React.RefObject<boolean[]>;
@@ -208,11 +208,11 @@ const Connection: React.FC<ConnectionProps> = ({
208208
setFullZoom(true);
209209
}
210210
};
211-
212-
// Added useEffect to sync canvasCount state with the canvasnumbersRef and re-render when isRecordingRef changes
213-
useEffect(() => {
214-
canvasnumbersRef.current = canvasCount; // Sync the ref with the state
215-
}, [canvasCount, isRecordingRef]);
211+
212+
// Added useEffect to sync canvasCount state with the canvasnumbersRef and re-render when isRecordingRef changes
213+
useEffect(() => {
214+
canvasnumbersRef.current = canvasCount; // Sync the ref with the state
215+
}, [canvasCount, isRecordingRef]);
216216

217217

218218
const handleTimeSelection = (minutes: number | null) => {
@@ -343,45 +343,49 @@ useEffect(() => {
343343
const formatPortInfo = useCallback(
344344
(info: SerialPortInfo, deviceName: string, fieldPid?: number) => {
345345
if (!info || !info.usbVendorId) {
346-
return { formattedInfo: "Port with no info", bits: null, channel: null };
346+
return { formattedInfo: "Port with no info", bits: null, channel: null, baudRate: null, serialTimeout: null };
347347
}
348-
348+
349349
// Find the board matching both name and field_pid
350350
const board = BoardsList.find(
351351
(b) =>
352-
b.name.toLowerCase() === deviceName.toLowerCase() &&
352+
b.chords_id.toLowerCase() === deviceName.toLowerCase() &&
353353
(!fieldPid || parseInt(b.field_pid, 10) === fieldPid) // Match field_pid if provided
354354
);
355-
355+
356356
if (board) {
357-
setifBits(board.bits as BitSelection);
358-
setSelectedBits(board.bits as BitSelection);
359-
detectedBitsRef.current = board.bits as BitSelection;
360-
361-
const channel = board.channel ? parseInt(board.channel, 10) : 0;
357+
setifBits(board.adc_resolution as BitSelection);
358+
setSelectedBits(board.adc_resolution as BitSelection);
359+
detectedBitsRef.current = board.adc_resolution as BitSelection;
360+
361+
const channel = board.channel_count ? parseInt(board.channel_count, 10) : 0;
362362
maxCanvasCountRef.current = channel;
363-
363+
364364
if (board.sampling_rate) {
365365
setCurrentSamplingRate(parseInt(board.sampling_rate, 10));
366366
}
367-
367+
368368
return {
369369
formattedInfo: (
370370
<>
371371
{board.device_name} <br /> Product ID: {info.usbProductId}
372372
</>
373373
),
374-
bits: board.bits,
375-
channel: board.channel,
374+
adcResolution: board.adc_resolution,
375+
channelCount: board.channel_count,
376+
baudRate: parseInt(board.baud_Rate, 10), // Return baudRate
377+
serialTimeout: parseInt(board.serial_timeout, 10), // Return serialTimeout
376378
};
377379
}
378-
380+
379381
setDetectedBits(null);
380-
return { formattedInfo: `${deviceName}`, bits: null, channel: null };
382+
return { formattedInfo: `${deviceName}`, adcResolution: null, channelCount: null, baudRate: null, serialTimeout: null };
381383
},
382384
[]
383385
);
384-
386+
387+
388+
385389
const handleClick = () => {
386390
// Function to handle toggle for connect/disconnect button
387391
if (isConnected) {
@@ -402,107 +406,121 @@ useEffect(() => {
402406
if (portRef.current && portRef.current.readable) {
403407
await disconnectDevice();
404408
}
405-
406-
const savedPorts: SavedDevice[] = JSON.parse(localStorage.getItem('savedDevices') || '[]');
407-
let port: SerialPort | null = null;
408-
let baudRate = 230400; // Default baud rate
409-
409+
410+
const savedPorts = JSON.parse(localStorage.getItem('savedDevices') || '[]');
411+
let port = null;
412+
410413
const ports = await navigator.serial.getPorts();
411-
console.log(ports);
414+
412415
// Check for saved ports
413416
if (savedPorts.length > 0) {
414-
port = ports.find((p) => {
415-
const info = p.getInfo();
416-
return savedPorts.some(
417-
(saved: SavedDevice) =>
418-
saved.usbVendorId === (info.usbVendorId ?? 0) &&
419-
saved.usbProductId === (info.usbProductId ?? 0)
420-
);
421-
}) || null;
417+
port =
418+
ports.find((p) => {
419+
const info = p.getInfo();
420+
return savedPorts.some(
421+
(saved: SavedDevice) =>
422+
saved.usbVendorId === (info.usbVendorId ?? 0) &&
423+
saved.usbProductId === (info.usbProductId ?? 0)
424+
);
425+
}) || null;
422426
}
423-
427+
428+
// Request a new port if no saved port matches
429+
port = await navigator.serial.requestPort();
430+
const newPortInfo = await port.getInfo();
431+
const usbVendorId = newPortInfo.usbVendorId ?? 0;
432+
const usbProductId = newPortInfo.usbProductId ?? 0;
433+
434+
// Match the board from BoardsList
435+
const board = BoardsList.find(
436+
(b) => parseInt(b.field_pid, 10) === usbProductId
437+
);
438+
439+
let baudRate = board ? parseInt(board.baud_Rate, 10) : 0;
440+
let serialTimeout = board ? parseInt(board.serial_timeout, 10) : 0;
441+
442+
424443
if (!port) {
425444
port = await navigator.serial.requestPort();
426445
const newPortInfo = await port.getInfo();
427-
446+
428447
const usbVendorId = newPortInfo.usbVendorId ?? 0;
429448
const usbProductId = newPortInfo.usbProductId ?? 0;
430-
431-
if (usbProductId === 29987 ) {
432-
baudRate = 115200;
433-
}
434-
449+
435450
const existingDevice = savedPorts.find(
436-
(saved) =>
437-
saved.usbVendorId === usbVendorId && saved.usbProductId === usbProductId
451+
(saved: SavedDevice) =>
452+
saved.usbVendorId === usbVendorId &&
453+
saved.usbProductId === usbProductId
438454
);
439-
455+
440456
if (!existingDevice) {
441457
savedPorts.push({ usbVendorId, usbProductId, baudRate });
442458
localStorage.setItem('savedDevices', JSON.stringify(savedPorts));
443-
console.log(`New device saved: Vendor ${usbVendorId}, Product ${usbProductId}, Baud Rate ${baudRate}`);
444459
}
445-
460+
446461
await port.open({ baudRate });
447462
} else {
448463
const newPortInfo = port.getInfo();
449464
const usbProductId = newPortInfo.usbProductId ?? 0;
450-
451-
if (usbProductId === 29987 ) {
452-
baudRate = 115200;
453-
}
454-
465+
455466
await port.open({ baudRate });
456467
}
457-
468+
458469
if (port.readable) {
459470
const reader = port.readable.getReader();
460471
readerRef.current = reader;
461472
const writer = port.writable?.getWriter();
462473
if (writer) {
463-
// Query the board for its name
464474
writerRef.current = writer;
465-
475+
476+
// Query the board for its name
466477
const whoAreYouMessage = new TextEncoder().encode("WHORU\n");
467-
await writerRef.current.write(whoAreYouMessage);
468-
setTimeout(() => writer.write(whoAreYouMessage), 2000);
469-
478+
479+
setTimeout(() => writer.write(whoAreYouMessage), serialTimeout);
480+
470481
let buffer = "";
471482
while (true) {
472483
const { value, done } = await reader.read();
473484
if (done) break;
474-
485+
475486
if (value) {
476487
buffer += new TextDecoder().decode(value);
477488
if (buffer.includes("\n")) break;
478489
}
479490
}
480-
491+
481492
// Extract the device name
482-
const response: string | undefined = buffer.trim().split("\n").pop();
483-
const extractedName = response?.match(/[A-Za-z0-9\-]+$/)?.[0] ?? "Unknown Device";
484-
485-
const currentPortInfo = port.getInfo(); // Ensure correct variable name and scope
486-
const usbProductId = currentPortInfo.usbProductId ?? 0; // Access usbProductId correctly
487-
493+
const response = buffer.trim().split("\n").pop();
494+
const extractedName =
495+
response?.match(/[A-Za-z0-9\-]+$/)?.[0] ?? "Unknown Device";
496+
497+
const currentPortInfo = port.getInfo();
498+
const usbProductId = currentPortInfo.usbProductId ?? 0;
499+
488500
// Pass the name and field_pid to formatPortInfo
489-
const { formattedInfo, bits, channel } = formatPortInfo(
490-
currentPortInfo,
491-
extractedName,
492-
usbProductId
493-
);
494-
501+
const {
502+
formattedInfo,
503+
adcResolution,
504+
channelCount,
505+
baudRate: extractedBaudRate,
506+
serialTimeout: extractedSerialTimeout,
507+
} = formatPortInfo(currentPortInfo, extractedName, usbProductId);
508+
509+
// Use extracted baudRate and serialTimeout
510+
baudRate = extractedBaudRate ?? baudRate;
511+
serialTimeout = extractedSerialTimeout ?? serialTimeout;
512+
495513
toast.success("Connection Successful", {
496514
description: (
497515
<div className="mt-2 flex flex-col space-y-1">
498516
<p>Device: {formattedInfo}</p>
499517
<p>Baud Rate: {baudRate}</p>
500-
{bits && <p>Resolution: {bits} bits</p>}
501-
{channel && <p>Channel: {channel}</p>}
518+
{adcResolution && <p>Resolution: {adcResolution} bits</p>}
519+
{channelCount && <p>Channel: {channelCount}</p>}
502520
</div>
503521
),
504522
});
505-
523+
506524
const startMessage = new TextEncoder().encode("START\n");
507525
setTimeout(() => writer.write(startMessage), 2000);
508526
} else {
@@ -511,16 +529,16 @@ useEffect(() => {
511529
} else {
512530
console.error("Readable stream not available");
513531
}
514-
532+
515533
Connection(true);
516534
setIsConnected(true);
517-
535+
518536
onPauseChange(true);
519537
setIsDisplay(true);
520538
setCanvasCount(1);
521539
isConnectedRef.current = true;
522540
portRef.current = port;
523-
541+
524542
const data = await getFileCountFromIndexedDB();
525543
setDatasets(data); // Update datasets with the latest data
526544
readData();
@@ -531,7 +549,6 @@ useEffect(() => {
531549
toast.error("Failed to connect to device.");
532550
}
533551
};
534-
535552

536553

537554
const getFileCountFromIndexedDB = async (): Promise<any[]> => {
@@ -611,7 +628,7 @@ useEffect(() => {
611628
Connection(false);
612629
}
613630
};
614-
631+
615632

616633
const appliedFiltersRef = React.useRef<{ [key: number]: number }>({});
617634
const appliedEXGFiltersRef = React.useRef<{ [key: number]: number }>({});
@@ -1567,7 +1584,7 @@ useEffect(() => {
15671584
<Button
15681585
className="rounded-xl rounded-l-none"
15691586
onClick={increaseCanvas}
1570-
disabled={canvasCount >= maxCanvasCountRef.current || !isDisplay || isRecordButtonDisabled}
1587+
disabled={canvasCount >= maxCanvasCountRef.current || !isDisplay || isRecordButtonDisabled}
15711588
>
15721589
<Plus size={16} />
15731590
</Button>

0 commit comments

Comments
 (0)