百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

tauri-plugin-serialplugin

> 编程语言
开源

Tauri 插件 — SerialPort 一个面向 Tauri 应用程序的全面插件,用于与串口通信。此插件提供了完整的 A…

180 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

Tauri 插件 — SerialPort 一个面向 Tauri 应用程序的全面插件,用于与串口通信。此插件提供了完整的 A…

Tauri Plugin — SerialPort

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 / disconnected were removed. Use watch() and SerialPort.getCapabilities(). See Migrating to v3 below.


Migrating to v3

In v2 you attached stream callbacks separately (startListening / listen / disconnected). In v3 one call — watch() — registers all of them; stop with the returned handle.

typescript
// 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)

Watch events (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)

Watch options

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

Table of Contents

  1. Installation
  2. Basic Usage
  3. TypeScript Support
  4. Log Level Control
  5. Rust Usage
  6. Permissions
  7. API Reference
    7.1. Port Discovery
    7.2. Connection Management
    7.3. Data Transfer
    7.4. Port Configuration
    7.5. Control Signals
    7.6. Buffer Management
    7.7. Log Control
    7.8. Auto-Reconnect
  8. Common Use Cases
  9. Android Setup
  10. Development Setup
  11. Testing
  12. Partners
  13. License

Installation

Prerequisites

  • Rust version 1.79 or higher (MSRV)
  • Tauri 2.0 or higher
  • Node.js and an npm-compatible package manager (npm, yarn, pnpm)

Automatic Installation (Recommended)

Use the Tauri CLI to automatically install both the Rust and JavaScript parts of the plugin:

bash
# 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 serialplugin

Manual Installation

Backend (Rust)

Add the plugin using cargo:

bash
cd ./src-tauri
cargo add tauri-plugin-serialplugin

Frontend (JavaScript/TypeScript)

Install the JavaScript API:

bash
npm install tauri-plugin-serialplugin-api
# or
pnpm add tauri-plugin-serialplugin-api

Android

USB 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.


Basic Usage

  1. Register the Plugin

    rust
    // 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");
    }
  2. Configure Permissions

    jsonc
    // 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"
      ]
    }
  3. Basic Example

…
  1. Error Handling Example
…

TypeScript Support

This plugin provides full TypeScript support with comprehensive type definitions. All methods, interfaces, and enums are properly typed for better development experience.

Available Types

typescript
import { 
  SerialPort, 
  DataBits, 
  FlowControl, 
  Parity, 
  StopBits, 
  ClearBuffer,
  PortInfo,
  SerialportOptions,
  ReadOptions 
} from "tauri-plugin-serialplugin-api";

Type Definitions

  • SerialPort - Main class for serial port operations
  • DataBits - Enum: Five, Six, Seven, Eight
  • FlowControl - Enum: None, Software, Hardware
  • Parity - Enum: None, Odd, Even
  • StopBits - Enum: One, Two
  • ClearBuffer - Enum: Input, Output, All
  • PortInfo - Interface for port information
  • SerialportOptions - Interface for port configuration
  • ReadOptions - Interface for read operation options

Configuration Example with Types

…

Control Signals with Types

typescript
// 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();

Buffer Management with Types

typescript
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();

Log Level Control

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.

TypeScript/JavaScript Usage

…

Rust Usage

rust
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:

rust
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())
}

Log Levels

  • None - No logging output (recommended for production)
  • Error - Only critical errors
  • Warn - Errors and warnings
  • Info - Errors, warnings, and general information (default)
  • Debug - All logging including debug information (for development)

Common Use Cases

Production Environment

typescript
// 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);

Development with Debugging

typescript
// 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

Conditional Logging

typescript
// Set log level based on environment
const isDevelopment = import.meta.env.DEV;
await SerialPort.setLogLevel(isDevelopment ? LogLevel.Debug : LogLevel.Error);

Rust Usage

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:

Using Commands Directly

You can import and use the command functions directly from the plugin:

…

Advanced Rust Example with Error Handling

…

Binary Data Handling in Rust

…

Using Commands vs Direct API

You have two ways to use the plugin in Rust:

Option 1: Using Commands (Recommended)

Import and use the command functions directly. These functions are documented in the docs.rs documentation:

rust
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
}

Option 2: Using Direct API

Use the SerialPort methods directly:

rust
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
}

Available Rust Types

The plugin provides the following Rust types for conf

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rust

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言