Device Discovery & Port Lifecycle
Relevant source files
The following files were used as context for generating this wiki page:
Device discovery and port lifecycle management in the Serial Plugin facilitate the detection, initialization, and termination of serial connections across desktop and mobile platforms. The system provides multiple layers of discovery—ranging from standard library enumerations to direct operating system queries—and maintains a strictly controlled state machine for every managed port to prevent resource leaks and concurrent access conflicts.
The lifecycle is orchestrated through a combination of a Rust-based backend state manager and a JavaScript/TypeScript frontend API. On desktop, ports are tracked in a global HashMap protected by a mutex, while on Android, the plugin leverages ActivityLifecycleCallbacks to ensure hardware resources are released when the host application is destroyed.
Device Discovery Mechanisms
The plugin offers three distinct methods for identifying serial hardware connected to the system. These methods cater to different reliability requirements and platform-specific behaviors.
Available Ports (Standard)
The available_ports method is the primary discovery tool. It utilizes the underlying serialport crate on desktop to enumerate devices. It returns a map of port paths to detailed metadata, including Vendor ID (VID), Product ID (PID), manufacturer, and serial numbers.
Sources: src/desktop_api.rs:60-72, guest-js/index.ts:510-521
Direct Port Discovery
The available_ports_direct method serves as a fallback or high-detail alternative. Instead of relying on standard library enumeration, it executes platform-specific shell commands to query the OS directly.
- Windows: Executes
wmicto queryWin32_PnPEntityandWin32_SerialPort. - Linux: Uses
lsusband parses the/devdirectory forttyUSB,ttyS,rfcomm, andttyACMentries. - macOS: Executes
system_profiler SPUSBDataTypeand scans/devforcu.*andtty.*devices.
Sources: src/desktop_api.rs:74-199, guest-js/index.ts:523-534
Managed Ports
Managed ports represent the subset of discovered devices that have been actively initialized by the plugin. Calling managed_ports returns a list of paths for all ports currently existing in the backend state (regardless of whether they are fully open or in the process of opening).
Sources: src/desktop_api.rs:211-224, android/src/main/kotlin/app/tauri/serialplugin/SerialPlugin.kt:150-161
Port Lifecycle Management
The lifecycle of a serial port connection is defined by a transition between states: Closed, Opening, and Connected.
The Discovery and Connection Flow
This diagram illustrates the sequence from discovering a physical device to establishing an active data stream.
Connection State Transitions
The backend utilizes a PortState enum to manage the internal status of each port. This prevents race conditions, such as attempting to read from a port that is still in the Opening phase.
| State | Description | Transition Trigger |
|---|---|---|
| Closed | Port exists in configuration but has no active handle. | Default state or post-close(). |
| Opening | The backend is currently negotiating with the OS for a hardware handle. | Call to open(). |
| Connected | Hardware handle is active; data can be sent or received. | Successful OS handle acquisition. |
Sources: src/desktop_api.rs:282-320, src/lib.rs:185-200
Termination and Cleanup
Properly closing ports is critical to avoid "Port Busy" errors in subsequent sessions. The plugin provides three mechanisms for termination.
1. Standard Closure (close)
The close command performs an orderly shutdown. It emits a plugin-serialplugin-disconnected-<path> event to the frontend, stops any active listening threads by sending a signal via an mpsc channel, joins the worker thread, and finally drops the hardware handle.
Sources: src/desktop_api.rs:241-268, guest-js/index.ts:705-715
2. Force Closure (force_close)
Used when a port becomes unresponsive or the standard close sequence hangs. It immediately removes the port from the managed internal map and attempts to drop the resources without waiting for thread joins.
Sources: src/desktop_api.rs:331-341, guest-js/index.ts:548-559
3. Global Cleanup (close_all)
During application exit or plugin reset, close_all iterates through the entire serialports map, draining every entry and executing the full teardown sequence for each.
Sources: src/desktop_api.rs:344-372, guest-js/index.ts:561-572
Android Lifecycle Integration
On Android, the plugin implements Application.ActivityLifecycleCallbacks. This ensures that if the user closes the app or the OS kills the activity, SerialPortManager.cleanup() is triggered automatically to release USB permissions and close hardware connections.
API Summary Table
The following table summarizes the discovery and lifecycle commands available in the SerialPort class.
| Method | Type | Scope | Description |
|---|---|---|---|
available_ports() | Static | Global | Lists all serial ports detected by the system. |
available_ports_direct() | Static | Global | Platform-specific deep scan for devices. |
managed_ports() | Static | Global | Lists ports currently tracked in the plugin state. |
open() | Instance | Instance | Initializes the connection to the physical hardware. |
close() | Instance | Instance | Gracefully shuts down the specific port instance. |
closeAll() | Static | Global | Shuts down all active connections managed by the plugin. |
forceClose(path) | Static | Global | Immediately kills a port connection by path. |
Sources: guest-js/index.ts:510-572, src/commands.rs:10-50
Conclusion
The Device Discovery and Port Lifecycle system ensures a robust interface between web-based frontends and physical serial hardware. By combining direct OS discovery commands with a rigorous state-controlled lifecycle and automated cleanup handlers (especially on mobile), the plugin minimizes common serial communication issues such as ghost handles, resource exhaustion, and device detection failures.