Skip to content

Commit cce575b

Browse files
author
Ritika Mishra
committed
improved code
1 parent 144338e commit cce575b

File tree

5 files changed

+71
-37
lines changed

5 files changed

+71
-37
lines changed

src/components/Canvas.tsx

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,6 @@ const Canvas = forwardRef(
6060
const activeBufferIndexRef = useRef(0); // Initialize useRef with 0
6161
const dataIndicesRef = useRef<number[]>([]); // Ref to store data indices
6262

63-
class ColorRGBA {
64-
constructor(public r: number, public g: number, public b: number, public a: number) { }
65-
}
66-
6763
//select point
6864
const getpoints = useCallback((bits: BitSelection): number => {
6965
switch (bits) {
@@ -91,7 +87,7 @@ const Canvas = forwardRef(
9187

9288
const processIncomingData = (incomingData: number[]) => {
9389
const currentBuffer = array3DRef.current[activeBufferIndexRef.current];
94-
90+
9591
// Handle canvas count changes and reset buffers
9692
if (prevCanvasCountRef.current !== canvasCount) {
9793
for (let bufferIndex = 0; bufferIndex < 6; bufferIndex++) {
@@ -100,23 +96,23 @@ const Canvas = forwardRef(
10096
}
10197
prevCanvasCountRef.current = canvasCount;
10298
}
103-
99+
104100
// Process incoming data for each canvas
105101
currentBuffer.forEach((buffer, i) => {
106-
if (buffer.length >= dataPointCountRef.current ||
107-
(!pauseRef.current && buffer.length < dataPointCountRef.current)) {
102+
if (buffer.length >= dataPointCountRef.current ||
103+
(!pauseRef.current && buffer.length < dataPointCountRef.current)) {
108104
currentBuffer[i] = [];
109105
}
110106
currentBuffer[i].push(incomingData[i + 1]);
111107
});
112-
108+
113109
// Update snapshot and buffer index when data is ready
114110
if (currentBuffer[0].length >= dataPointCountRef.current) {
115111
snapShotRef.current[activeBufferIndexRef.current] = true;
116112
activeBufferIndexRef.current = (activeBufferIndexRef.current + 1) % 6;
117113
snapShotRef.current[activeBufferIndexRef.current] = false;
118114
}
119-
115+
120116
// Update data indices for referencing past buffers
121117
dataIndicesRef.current = Array.from(
122118
{ length: 5 },

src/components/Colors.ts

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,30 +18,22 @@ export const customColors = {
1818
'custom-16': '#F2728B',
1919
};
2020

21-
export const lightThemeColors = Object.values(customColors).map((hex) => {
22-
// Darken the colors more significantly for the light theme
23-
return darkenColor(hex, 0.3); // Stronger darkening for light theme (0.3 instead of 0.1)
24-
});
25-
26-
export const darkThemeColors = Object.values(customColors).map((hex) => {
27-
// Lighten the colors slightly for the dark theme
28-
return lightenColor(hex, 0.1); // Lightening for dark theme
29-
});
30-
3121
// Function to darken a color
3222
function darkenColor(hex: string, amount: number): string {
23+
validateInput(hex, amount);
3324
return adjustColor(hex, -amount); // Negative amount for darkening
3425
}
3526

3627
// Function to lighten a color
3728
function lightenColor(hex: string, amount: number): string {
29+
validateInput(hex, amount);
3830
return adjustColor(hex, amount); // Positive amount for lightening
3931
}
4032

4133
// General color adjustment function (darkens or lightens based on amount)
4234
function adjustColor(hex: string, amount: number): string {
43-
// Ensure that hex starts with '#'
44-
if (hex[0] !== '#') {
35+
// Validate hex format
36+
if (!/^#[0-9A-Fa-f]{6}$/.test(hex)) {
4537
throw new Error('Invalid hex color');
4638
}
4739

@@ -56,6 +48,29 @@ function adjustColor(hex: string, amount: number): string {
5648
g = Math.min(255, Math.max(0, g + Math.floor(255 * amount)));
5749
b = Math.min(255, Math.max(0, b + Math.floor(255 * amount)));
5850

59-
// Convert RGB back to hex
60-
return `#${(1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1)}`;
51+
// Convert RGB back to hex with leading zeros
52+
return `#${[r, g, b]
53+
.map(x => x.toString(16).padStart(2, '0'))
54+
.join('')}`;
55+
}
56+
57+
// Validate input for hex color and amount
58+
function validateInput(hex: string, amount: number): void {
59+
if (!/^#[0-9A-Fa-f]{6}$/.test(hex)) {
60+
throw new Error('Invalid hex color format');
61+
}
62+
if (amount < 0 || amount > 1) {
63+
throw new Error('Amount must be between 0 and 1');
64+
}
6165
}
66+
67+
// Example usage
68+
export const lightThemeColors = Object.values(customColors).map((hex) => {
69+
// Darken the colors more significantly for the light theme
70+
return darkenColor(hex, 0.3); // Stronger darkening for light theme (0.3 instead of 0.1)
71+
});
72+
73+
export const darkThemeColors = Object.values(customColors).map((hex) => {
74+
// Lighten the colors slightly for the dark theme
75+
return lightenColor(hex, 0.1); // Lightening for dark theme
76+
});

src/components/Connection.tsx

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,7 @@ const Connection: React.FC<ConnectionProps> = ({
509509
channelCount: null,
510510
baudRate: null,
511511
serialTimeout: null,
512+
usbProductId: null, // Add usbProductId to the return value
512513
};
513514
}
514515

@@ -520,7 +521,14 @@ const Connection: React.FC<ConnectionProps> = ({
520521
);
521522

522523
if (board) {
523-
const { adc_resolution, channel_count, sampling_rate, baud_Rate, serial_timeout, device_name } = board;
524+
const {
525+
adc_resolution,
526+
channel_count,
527+
sampling_rate,
528+
baud_Rate,
529+
serial_timeout,
530+
device_name,
531+
} = board;
524532

525533
// Update state and refs
526534
const bitSelection = adc_resolution as BitSelection;
@@ -536,13 +544,14 @@ const Connection: React.FC<ConnectionProps> = ({
536544
return {
537545
formattedInfo: (
538546
<>
539-
{device_name} <br /> Product ID: {info.usbProductId}
547+
{device_name}
540548
</>
541549
),
542550
adcResolution: adc_resolution,
543551
channelCount: channel_count,
544552
baudRate: baud_Rate,
545553
serialTimeout: serial_timeout,
554+
usbProductId: info.usbProductId, // Return usbProductId as well
546555
};
547556
}
548557

@@ -554,11 +563,13 @@ const Connection: React.FC<ConnectionProps> = ({
554563
channelCount: null,
555564
baudRate: null,
556565
serialTimeout: null,
566+
usbProductId: info.usbProductId, // Return the usbProductId even if no matching board is found
557567
};
558568
},
559569
[] // Dependency array
560570
);
561571

572+
562573
interface SavedDevice {
563574
usbVendorId: number;
564575
usbProductId: number;
@@ -705,6 +716,7 @@ const Connection: React.FC<ConnectionProps> = ({
705716
description: (
706717
<div className="mt-2 flex flex-col space-y-1">
707718
<p>Device: {formattedInfo}</p>
719+
<p>Product ID: {usbProductId}</p> {/* Display the Product ID */}
708720
<p>Baud Rate: {baudRate}</p>
709721
{adcResolution && <p>Resolution: {adcResolution} bits</p>}
710722
{channelCount && <p>Channel: {channelCount}</p>}
@@ -807,7 +819,7 @@ const Connection: React.FC<ConnectionProps> = ({
807819
}
808820
portRef.current = null;
809821
setIsDeviceConnected(false); // Update connection state
810-
toast("DisDeviceConnected from device", {
822+
toast("Disconnected from device", {
811823
action: {
812824
label: "Reconnect",
813825
onClick: () => connectToDevice(),

src/components/boards.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,17 @@ export const BoardsList: ReadonlyArray<BoardConfig> = Object.freeze([
5353
channel_count: 8,
5454
baud_Rate: 115200,
5555
}),
56+
createBoardConfig({
57+
chords_id: "BLACK-PILL",
58+
device_name: "Black Pill - STM32F4",
59+
field_pid: 22336,
60+
adc_resolution: 12,
61+
channel_count: 10,
62+
sampling_rate: 500,
63+
serial_timeout: 200,
64+
baud_Rate: 230400
65+
}),
66+
5667
createBoardConfig({
5768
chords_id: "NANO-CLONE",
5869
device_name: "Arduino Nano Clone",

workers/indexedDBWorker.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ const openIndexedDB = async (): Promise<IDBDatabase> => {
110110
};
111111

112112
// Helper function for IndexedDB transactions
113-
const performTransaction = async <T>(
113+
const performIndexDBTransaction = async <T>(
114114
db: IDBDatabase,
115115
storeName: string,
116116
mode: IDBTransactionMode,
@@ -133,7 +133,7 @@ const writeToIndexedDB = async (
133133
filename: string
134134
): Promise<boolean> => {
135135
try {
136-
const existingRecord = await performTransaction(db, "ChordsRecordings", "readwrite", (store) => {
136+
const existingRecord = await performIndexDBTransaction(db, "ChordsRecordings", "readwrite", (store) => {
137137
return new Promise<any>((resolve, reject) => {
138138
const getRequest = store.get(filename);
139139
getRequest.onsuccess = () => resolve(getRequest.result);
@@ -143,7 +143,7 @@ const writeToIndexedDB = async (
143143

144144
if (existingRecord) {
145145
existingRecord.content.push(...data);
146-
await performTransaction(db, "ChordsRecordings", "readwrite", (store) => {
146+
await performIndexDBTransaction(db, "ChordsRecordings", "readwrite", (store) => {
147147
return new Promise<void>((resolve, reject) => {
148148
const putRequest = store.put(existingRecord);
149149
putRequest.onsuccess = () => resolve();
@@ -152,7 +152,7 @@ const writeToIndexedDB = async (
152152
});
153153
} else {
154154
const newRecord = { filename, content: [...data] };
155-
await performTransaction(db, "ChordsRecordings", "readwrite", (store) => {
155+
await performIndexDBTransaction(db, "ChordsRecordings", "readwrite", (store) => {
156156
return new Promise<void>((resolve, reject) => {
157157
const putRequest = store.put(newRecord);
158158
putRequest.onsuccess = () => resolve();
@@ -172,7 +172,7 @@ const writeToIndexedDB = async (
172172
// Function to get all data from IndexedDB
173173
const getAllDataFromIndexedDB = async (db: IDBDatabase): Promise<any[]> => {
174174
try {
175-
return await performTransaction(db, "ChordsRecordings", "readonly", (store) => {
175+
return await performIndexDBTransaction(db, "ChordsRecordings", "readonly", (store) => {
176176
return new Promise<any[]>((resolve, reject) => {
177177
const request = store.getAll();
178178
request.onsuccess = () => resolve(request.result);
@@ -233,7 +233,7 @@ const saveAllDataAsZip = async (canvasCount: number, selectedChannels: number[])
233233
try {
234234
const db = await openIndexedDB();
235235

236-
const allData = await performTransaction(db, "ChordsRecordings", "readonly", (store) => {
236+
const allData = await performIndexDBTransaction(db, "ChordsRecordings", "readonly", (store) => {
237237
return new Promise<any[]>((resolve, reject) => {
238238
const request = store.getAll();
239239
request.onsuccess = () => resolve(request.result);
@@ -275,7 +275,7 @@ const saveDataByFilename = async (
275275
try {
276276
const db = await openIndexedDB();
277277

278-
const record = await performTransaction(db, "ChordsRecordings", "readonly", (store) => {
278+
const record = await performIndexDBTransaction(db, "ChordsRecordings", "readonly", (store) => {
279279
return new Promise<any>((resolve, reject) => {
280280
const index = store.index("filename");
281281
const getRequest = index.get(filename);
@@ -310,7 +310,7 @@ const saveDataByFilename = async (
310310

311311
// Function to get file count from IndexedDB
312312
const getFileCountFromIndexedDB = async (db: IDBDatabase): Promise<string[]> => {
313-
return performTransaction(db, "ChordsRecordings", "readonly", (store) => {
313+
return performIndexDBTransaction(db, "ChordsRecordings", "readonly", (store) => {
314314
return new Promise<string[]>((resolve, reject) => {
315315
const filenames: string[] = [];
316316
const cursorRequest = store.openCursor();
@@ -342,7 +342,7 @@ const deleteFilesByFilename = async (filename: string) => {
342342
const db = (event.target as IDBOpenDBRequest).result;
343343

344344
try {
345-
await performTransaction(db, "ChordsRecordings", "readwrite", async (store) => {
345+
await performIndexDBTransaction(db, "ChordsRecordings", "readwrite", async (store) => {
346346
if (!store.indexNames.contains("filename")) {
347347
throw new Error("Index 'filename' does not exist.");
348348
}
@@ -383,7 +383,7 @@ const deleteAllDataFromIndexedDB = async () => {
383383
const db = (event.target as IDBOpenDBRequest).result;
384384

385385
try {
386-
await performTransaction(db, "ChordsRecordings", "readwrite", async (store) => {
386+
await performIndexDBTransaction(db, "ChordsRecordings", "readwrite", async (store) => {
387387
const clearRequest = store.clear();
388388

389389
return new Promise<void>((resolveClear, rejectClear) => {

0 commit comments

Comments
 (0)