This is the shortest path to opening a serial port, receiving newline-delimited lines, sending data, and closing the port. For the full map of state$, isConnected$, receive$, lines$, errors$, and the imperative methods, read SerialSession (v2) overview first.
Use lines$ for standard newline-framed text (\n, \r\n). receive$ is still the raw UTF-8 decoder chunk stream when you need custom framing (see Advanced Usage). For a simple "are we connected?" boolean, use isConnected$ (or still derive from state$ with map if you prefer).
| Constant | Value | Meaning |
|---|---|---|
SerialSessionState.Idle |
'idle' |
No open port; initial when Web Serial is supported. |
SerialSessionState.Connecting |
'connecting' |
connect$ in progress. |
SerialSessionState.Connected |
'connected' |
Port open; read pump running. |
SerialSessionState.Disconnecting |
'disconnecting' |
disconnect$ in progress. |
SerialSessionState.Unsupported |
'unsupported' |
Web Serial unavailable at session creation. |
SerialSessionState.Error |
'error' |
Fatal failure; disconnect$ or a new session. |
Details and lifecycle: API Reference – SerialSessionState.
import { createSerialSession } from '@gurezo/web-serial-rxjs';
const session = createSerialSession({ baudRate: 115200 });
if (!session.isBrowserSupported()) {
console.error('Web Serial API is not supported in this browser');
}
session.isConnected$.subscribe((isConnected) =>
console.log('Connected:', isConnected),
);
session.lines$.subscribe((line) => console.log('line:', line));
// In production apps, subscribe to errors$ and handle SerialError
session.errors$.subscribe((err) => console.error('Serial error:', err));
session.connect$().subscribe({
next: () => {
session.send$('ls\r\n').subscribe({
error: (e) => console.error('Send error:', e),
});
},
error: (e) => console.error('Connection error:', e),
});
Prefer SerialSessionState for comparisons (not raw strings such as 'connected'):
import { SerialSessionState } from '@gurezo/web-serial-rxjs';
session.state$.subscribe((s) => {
if (s === SerialSessionState.Unsupported) {
console.warn('Web Serial is not available');
}
});
Call disconnect$ when you want to close the port.
session.disconnect$().subscribe({
error: (e) => console.error('Disconnect error:', e),
});