2024-04-15 02:23:59 +02:00
|
|
|
let port;
|
|
|
|
|
|
2024-04-15 05:03:06 +02:00
|
|
|
async function getPort() {
|
|
|
|
|
if (port) return port;
|
2024-04-15 02:23:59 +02:00
|
|
|
try {
|
2024-04-15 05:03:06 +02:00
|
|
|
[port] = await navigator.serial.getPorts();
|
2024-04-15 02:23:59 +02:00
|
|
|
await port.open({ baudRate: 115200 });
|
|
|
|
|
console.log('Connected to serial device:', port);
|
2024-04-15 05:03:06 +02:00
|
|
|
return port;
|
2024-04-15 02:23:59 +02:00
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error connecting to serial device:', error);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-15 05:03:06 +02:00
|
|
|
async function write(data) {
|
|
|
|
|
const port = await getPort();
|
|
|
|
|
const writer = port.writable.getWriter();
|
|
|
|
|
await writer.write(new TextEncoder().encode(data));
|
|
|
|
|
await writer.releaseLock();
|
2024-04-15 02:23:59 +02:00
|
|
|
}
|
|
|
|
|
|
2024-04-15 05:03:06 +02:00
|
|
|
async function read() {
|
|
|
|
|
const port = await getPort();
|
|
|
|
|
const reader = port.readable.getReader();
|
|
|
|
|
const {value, done} = await reader.read();
|
|
|
|
|
reader.releaseLock();
|
2024-04-15 02:23:59 +02:00
|
|
|
|
2024-04-15 05:03:06 +02:00
|
|
|
if (!done) {
|
2024-04-15 05:57:16 +02:00
|
|
|
return new TextDecoder().decode(value);
|
2024-04-15 02:23:59 +02:00
|
|
|
}
|
|
|
|
|
}
|
2024-04-15 05:57:16 +02:00
|
|
|
|
|
|
|
|
self.addEventListener('message', async function(event) {
|
|
|
|
|
await write(event.data);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
async function readWrapper() {
|
|
|
|
|
if (port) {
|
|
|
|
|
self.postMessage(await read()); // this is a hack but i'm curious
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
setInterval(readWrapper, 500);
|