Skip to content

Commit 8a49c5d

Browse files
committed
Use TextDecoder to decode text instead of manual approach
1 parent 6c44120 commit 8a49c5d

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

demo/micropython-run.ts

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -56,22 +56,24 @@ function handleDeviceConnected(cdc: USBCDC, useCircuitPython: boolean) {
5656
cdc.sendSerialByte('\n'.charCodeAt(0));
5757
}
5858

59-
function handleSerialData(value: Uint8Array, expectText: string | null) {
59+
function testWriteSerialData(value: Uint8Array, expectText: string, decoder: TextDecoder) {
6060
process.stdout.write(value);
61-
let currentLine = '';
62-
63-
for (const byte of value) {
64-
const char = String.fromCharCode(byte);
65-
if (char === '\n') {
66-
if (expectText && currentLine.includes(expectText)) {
67-
console.log(`Expected text found: "${expectText}"`);
68-
console.log('TEST PASSED.');
69-
process.exit(0);
70-
}
71-
currentLine = '';
72-
} else {
73-
currentLine += char;
74-
}
61+
62+
const current = decoder.decode(value);
63+
64+
if (current.includes(expectText)) {
65+
console.log(`\nExpected text found: "${expectText}"`);
66+
console.log('TEST PASSED.');
67+
process.exit(0);
68+
}
69+
}
70+
71+
function installSerialDataWriter(cdc: USBCDC, expectText: string | null) {
72+
if (expectText) {
73+
const decoder = new TextDecoder();
74+
cdc.onSerialData = (value) => testWriteSerialData(value, expectText, decoder);
75+
} else {
76+
cdc.onSerialData = (value) => process.stdout.write(value);
7577
}
7678
}
7779

@@ -90,7 +92,7 @@ function simulateMicropythonImage(opts: CliOptions) {
9092

9193
const cdc = new USBCDC(mcu.usbCtrl);
9294
cdc.onDeviceConnected = () => handleDeviceConnected(cdc, opts['circuit-python']);
93-
cdc.onSerialData = (value) => handleSerialData(value, opts['expect-text']);
95+
installSerialDataWriter(cdc, opts['expect-text']);
9496

9597
if (process.stdin.isTTY) process.stdin.setRawMode(true);
9698

0 commit comments

Comments
 (0)