Skip to content

Commit 0fcfb62

Browse files
committed
Feature: Patch send functions with ArrayBuffer
1 parent 6261d52 commit 0fcfb62

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

src/js/protocols/WebSerial.js

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -333,18 +333,26 @@ class WebSerial extends EventTarget {
333333
// AT32 on macOS requires smaller chunks (63 bytes) to work correctly due to
334334
// USB buffer size limitations in the macOS implementation
335335
const batchWriteSize = 63;
336-
let remainingData = data;
337-
while (remainingData.byteLength > batchWriteSize) {
338-
const sliceData = remainingData.slice(0, batchWriteSize);
339-
remainingData = remainingData.slice(batchWriteSize);
336+
337+
// Ensure data is a Uint8Array for proper slicing
338+
const dataArray = data instanceof Uint8Array ? data : new Uint8Array(data);
339+
340+
let offset = 0;
341+
while (offset + batchWriteSize < dataArray.byteLength) {
342+
const chunk = dataArray.slice(offset, offset + batchWriteSize);
343+
offset += batchWriteSize;
340344
try {
341-
await this.writer.write(sliceData);
345+
await this.writer.write(chunk);
342346
} catch (error) {
343347
console.error(`${logHead} Error writing batch chunk:`, error);
344348
throw error; // Re-throw to be caught by the send method
345349
}
346350
}
347-
await this.writer.write(remainingData);
351+
352+
// Write the remaining data
353+
if (offset < dataArray.byteLength) {
354+
await this.writer.write(dataArray.slice(offset));
355+
}
348356
}
349357

350358
async send(data, callback) {
@@ -357,14 +365,17 @@ class WebSerial extends EventTarget {
357365
}
358366

359367
try {
368+
// Create a buffer from the data
369+
const buffer = data instanceof ArrayBuffer ? data : new Uint8Array(data).buffer;
370+
360371
if (this.isNeedBatchWrite) {
361-
await this.batchWrite(data);
372+
await this.batchWrite(buffer);
362373
} else {
363-
await this.writer.write(data);
374+
await this.writer.write(new Uint8Array(buffer));
364375
}
365-
this.bytesSent += data.byteLength;
376+
this.bytesSent += buffer.byteLength;
366377

367-
const result = { bytesSent: data.byteLength };
378+
const result = { bytesSent: buffer.byteLength };
368379
if (callback) {
369380
callback(result);
370381
}

0 commit comments

Comments
 (0)