This is a vanilla JavaScript example application demonstrating how to use the @gurezo/web-serial-rxjs library with RxJS to interact with serial ports through the Web Serial API.
- Browser support detection
- Serial port connection/disconnection
- Configuration options (baud rate)
- Send data to serial port
- Receive data from serial port
- Real-time data display
- Modern browser with Web Serial API support (Chrome, Edge, Opera, etc.)
- Node.js and npm
- Nx workspace
Make sure all dependencies are installed:
pnpm installStart the development server:
pnpm exec nx serve example-vanilla-jsThe application will be available at http://localhost:4230
Build the application for production:
pnpm exec nx build example-vanilla-jsRun tests:
pnpm exec nx test example-vanilla-jsRun linting:
pnpm exec nx lint example-vanilla-jsThis example uses RxJS observables to handle serial port communication reactively:
-
Browser Support Check: On initialization, the app checks if the browser supports the Web Serial API.
-
Connection: Users can connect to a serial port by clicking the "接続" (Connect) button. The app uses
createSerialClient()to create a client instance. -
Configuration: Users can select the baud rate before connecting.
-
Data Sending: Users can type text in the input field and send it to the serial port. The text is encoded as UTF-8 and sent as
Uint8Array. -
Data Receiving: Data received from the serial port is decoded as UTF-8 and displayed in real-time in the textarea.
src/main.js: Application entry pointsrc/app.js: Main application class with serial port logicsrc/styles.css: Stylingindex.html: HTML structurevite.config.ts: Vite configurationproject.json: Nx project configuration
import { createSerialClient } from '@gurezo/web-serial-rxjs';
// Create a serial client
const client = createSerialClient({ baudRate: 115200 });
// Connect to a port
client.connect().subscribe({
next: () => {
console.log('Connected!');
// Start reading
client.getReadStream().subscribe({
next: (data) => {
const text = new TextDecoder().decode(data);
console.log('Received:', text);
},
});
},
error: (error) => {
console.error('Connection error:', error);
},
});
// Send data
const encoder = new TextEncoder();
const data = encoder.encode('Hello, Serial!');
client.write(data).subscribe({
next: () => console.log('Data sent'),
error: (error) => console.error('Send error:', error),
});This example requires a browser that supports the Web Serial API:
- Chrome 89+
- Edge 89+
- Opera 75+
- Chrome Android 89+
Safari and Firefox do not currently support the Web Serial API.