Serial Ports
Real serial devices for the guest's /dev/ttyACM0 to ttyACM3.
import { createKernel, webSerialBackend } from "unkernel";
const vm = await createKernel({ serial: true }); // /dev/ttyACM0..3, nothing attached
button.onclick = async () => {
const port = await navigator.serial.requestPort(); // Web Serial, from a click
const slot = vm.serial.attach(webSerialBackend(port)); // the first free port: /dev/ttyACM<slot>
};
// in the guest: picocom -b 115200 /dev/ttyACM0, esptool, arduino-cli...The guest's tty settings become the real port's: an open opens it with the guest's speed, data bits, stop bits, parity and RTS/CTS, and the last close closes it. Web Serial cannot change an open port, so a speed change while it is open closes and reopens it, with writes held in order. DTR, RTS and break follow the guest in order with its writes (reset sequences of esptool and the Arduino tools work), and CTS, DSR, DCD and RI are read every 75 ms while a program has the port open.
Opening a port with nothing attached fails. Unplugging a device, or vm.serial.detach(slot), hangs up the program using it, as on Linux.
vm.serial.state(slot) and onChange() say what is attached and how it is used; onWanted() reports a guest program opening a port that has no backend (it gets ENODEV), which is the moment to offer the chooser. serial: { ports: 2, attach: [backend] } offers fewer ports and attaches at boot.
webSerialBackend() needs Web Serial: Chromium-based desktop browsers, in a secure context; webSerialBlocker() says why it is missing. In worker mode the ports still run on your thread, where requestPort() works. Any object with open, close, read, write, setSignals and getSignals can be a backend; FakeSerialBackend is an in-memory loopback for tests that records every call.
Nothing of a port is in a snapshot (vm.snapshot()): programs that had one open see a hangup after a restore.