Tauri 插件 — SerialPort 一个面向 Tauri 应用程序的全面插件,用于与串口通信。此插件提供了完整的 A…
Tauri 插件 — SerialPort 一个面向 Tauri 应用程序的全面插件,用于与串口通信。此插件提供了完整的 A…
A comprehensive plugin for Tauri applications to communicate with serial ports. This plugin provides a complete API for reading from and writing to serial devices, with support for various configuration options and control signals.
v3.0 breaking change:
listen/startListening/disconnectedwere removed. Usewatch()andSerialPort.getCapabilities(). See Migrating to v3 below.
In v2 you attached stream callbacks separately (startListening / listen / disconnected).
In v3 one call — watch() — registers all of them; stop with the returned handle.
// v2
await port.startListening();
await port.listen((data) => console.log(data));
await port.disconnected((reason) => console.log("gone", reason));
await port.cancelListen();
// v3 — same thing in one watch()
const handle = await port.watch({
onData: (data) => console.log(data),
onDisconnect: (reason) => console.log("gone", reason), // replaces disconnected(fn)
});
await handle.unwatch();| v2 | v3 |
|---|---|
startListening() + listen(fn) |
const handle = await port.watch({ onData: fn }) |
disconnected(fn) |
pass onDisconnect: fn into the same watch({ ... }) |
cancelListen() / stopListening() |
await handle.unwatch() |
Legacy Tauri events (plugin-serialplugin-read-*) and Android plugin triggers (serialData, serialError) are no longer part of the public API.
New in v3: SerialPort.getCapabilities() — { transport, platform, version } from Rust (cfg!), if the app needs to branch by platform (replaces ad-hoc window / @tauri-apps/plugin-os probing on the app side).
Breaking API changes (v3):
| Field / behavior | v2 | v3 |
|---|---|---|
AtCommandResult.raw / ExchangeResponse.raw |
number[] |
Uint8Array |
AtCommandResult.timedOut |
literal false |
boolean (timeouts surfaced by native layer) |
open() |
void |
returns canonical path (Android re-keys to UsbPath.sessionKey; desktop echoes input) |
cancel_read |
also detached watch on some builds | does not unwatch — use close() or handle.unwatch() |
| TX queue after error | port could stay halted until reopen | next exchange / sendAt job runs normally (stopOnError only stops remaining phases in one sendAtPhases batch) |
Early RX before exchange |
often lost or raced with wait | native hub keeps idle bytes; exchange replays them via take_idle_bytes after write (no extra line response needed) |
SerialEvent)kind |
Meaning | Port stays open? |
|---|---|---|
data |
Incoming bytes (decoded to string in JS when decode !== false) |
Yes |
error |
Non-fatal notification (e.g. emitter glitch); watch continues | Yes |
disconnect |
Fatal end of stream (unplug, IO manager stopped); triggers auto-reconnect if enabled | No (isOpen = false) |
| Option | Desktop | Android |
|---|---|---|
timeout |
Batch coalescing window (ms) | Coalescing / flush hint where supported |
serialDataFlushIntervalMs |
Preferred batch interval for hub batch_timeout_ms (falls back to timeout) |
Same; clamped typically 10–2000 ms |
size |
Read chunk size per syscall | Reserved |
decode |
JS-only: TextDecoder on onData |
JS-only |
routeUrc |
Split AT URC lines into onUrc (strips them from onData). Default: off; JS sets on when onUrc is passed. Keep off for binary/NMEA. |
Same |
Use the Tauri CLI to automatically install both the Rust and JavaScript parts of the plugin:
# npm
npm run tauri add serialplugin
# yarn
yarn run tauri add serialplugin
# pnpm
pnpm tauri add serialplugin
# deno
deno task tauri add serialplugin
# bun
bun tauri add serialplugin
# cargo
cargo tauri add serialpluginAdd the plugin using cargo:
cd ./src-tauri
cargo add tauri-plugin-serialpluginInstall the JavaScript API:
npm install tauri-plugin-serialplugin-api
# or
pnpm add tauri-plugin-serialplugin-apiUSB serial on Android uses pure Rust drivers in crates/android-usb-serial (nusb). Kotlin provides USB permission, enumeration, and a dup'd fd; no vendored Java stack or JitPack dependency.
Register the Plugin
// src-tauri/src/main.rs
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_serialplugin::init())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}Configure Permissions
// src-tauri/capabilities/default.json
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"serialplugin:default"
]
}Basic Example
……This plugin provides full TypeScript support with comprehensive type definitions. All methods, interfaces, and enums are properly typed for better development experience.
import {
SerialPort,
DataBits,
FlowControl,
Parity,
StopBits,
ClearBuffer,
PortInfo,
SerialportOptions,
ReadOptions
} from "tauri-plugin-serialplugin-api";SerialPort - Main class for serial port operationsDataBits - Enum: Five, Six, Seven, EightFlowControl - Enum: None, Software, HardwareParity - Enum: None, Odd, EvenStopBits - Enum: One, TwoClearBuffer - Enum: Input, Output, AllPortInfo - Interface for port informationSerialportOptions - Interface for port configurationReadOptions - Interface for read operation options…// Set control signals
await port.writeRequestToSend(true);
await port.writeDataTerminalReady(true);
// Alternative methods (writeRequestToSend and writeDataTerminalReady)
await port.writeRequestToSend(true);
await port.writeDataTerminalReady(true);
// Read control signals
const cts = await port.readClearToSend();
const dsr = await port.readDataSetReady();
const ri = await port.readRingIndicator();
const cd = await port.readCarrierDetect();import { ClearBuffer } from "tauri-plugin-serialplugin-api";
// Check buffer status
const bytesToRead = await port.bytesToRead();
const bytesToWrite = await port.bytesToWrite();
// Clear buffers with type-safe enum
await port.clearBuffer(ClearBuffer.Input);
await port.clearBuffer(ClearBuffer.Output);
await port.clearBuffer(ClearBuffer.All);
// Break signal control
await port.setBreak();
await port.clearBreak();The plugin provides comprehensive logging control to help you manage verbosity in production environments. By default, the plugin logs informational messages, but you can adjust this to reduce noise or enable detailed debugging.
…use tauri_plugin_serialplugin::state::{LogLevel, set_log_level};
// Set log level on plugin initialization
fn main() {
// Disable logs in production
set_log_level(LogLevel::None);
tauri::Builder::default()
.plugin(tauri_plugin_serialplugin::init())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}Or configure via command:
use tauri_plugin_serialplugin::commands::set_log_level;
use tauri_plugin_serialplugin::state::LogLevel;
use tauri::{AppHandle, State};
#[tauri::command]
async fn configure_production_logging(
app: AppHandle,
serial: State>
) -> Result {
// Only show errors in production
set_log_level(app, serial, LogLevel::Error)
.map_err(|e| e.to_string())
}None - No logging output (recommended for production)Error - Only critical errorsWarn - Errors and warningsInfo - Errors, warnings, and general information (default)Debug - All logging including debug information (for development)// Disable noisy logs when polling for available ports
await SerialPort.setLogLevel(LogLevel.None);
setInterval(async () => {
const ports = await SerialPort.available_ports();
// No extra console noise from the plugin while polling
}, 1000);// Enable detailed logging for troubleshooting
await SerialPort.setLogLevel(LogLevel.Debug);
const port = new SerialPort({ path: "COM1", baudRate: 9600 });
await port.open();
// See all internal events and state changes// Set log level based on environment
const isDevelopment = import.meta.env.DEV;
await SerialPort.setLogLevel(isDevelopment ? LogLevel.Debug : LogLevel.Error);This plugin can also be used directly from Rust code in your Tauri backend. For complete API documentation, see docs.rs.
Here's how to use it:
You can import and use the command functions directly from the plugin:
………You have two ways to use the plugin in Rust:
Import and use the command functions directly. These functions are documented in the docs.rs documentation:
use tauri_plugin_serialplugin::commands::{available_ports, open, write, read, close};
use tauri::{AppHandle, State};
#[tauri::command]
async fn my_serial_function(
app: AppHandle,
serial: State>
) -> Result {
// Use command functions
let ports = available_ports(app.clone(), serial.clone())?;
open(app.clone(), serial.clone(), "COM1".to_string(), 9600, None, None, None, None, None)?;
// ... rest of your code
}Use the SerialPort methods directly:
use tauri::State;
use tauri_plugin_serialplugin::api::SerialPort;
#[tauri::command]
async fn my_serial_function(
serial: State>
) -> Result {
// Use serial methods directly
let ports = serial.available_ports(false)?;
// ... rest of your code
}The plugin provides the following Rust types for conf
暂无开放 Issues,或尚未同步最近议题。