summaryrefslogtreecommitdiffstats
path: root/assets/js/serialUtil.js
blob: 8ce3c6e2fcff52fd8abdc98a6bb3280fde613d3e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function openPortLineBreak(port, baudRate, outputErrorCallback) {
    try {
        await port.open({ baudRate: baudRate });
    } catch (err) {
        outputErrorCallback(`Error: ${err.message}`);
        return;
    }

    const textDecoder = new TextDecoderStream();
    const readableStreamClosed = port.readable.pipeTo(textDecoder.writable);
    const reader = await textDecoder.readable.pipeThrough(new TransformStream(new LineBreakTransformer())).getReader();
    const textEncoderStream = new TextEncoderStream();
    const writerStreamClosed = textEncoderStream.readable.pipeTo(port.writable);
    const writer = await textEncoderStream.writable.getWriter();

    return { reader, writer, readableStreamClosed, writerStreamClosed };
}

async function closePortLineBreak(port, reader, writer, readableStreamClosed, writerStreamClosed) {
    reader.cancel();
    await readableStreamClosed.catch(() => { /* Ignore the error */ });
    writer.close();
    await writerStreamClosed;
    await port.close();
}