Automatic Reconnection
Relevant source files
The following files were used as context for generating this wiki page:
Automatic Reconnection is a robust feature within the tauri-plugin-serialplugin designed to maintain stable serial communication by automatically attempting to restore a connection when a port is physically or logically disconnected. This system abstracts the complexity of manual polling and retry logic, providing a seamless experience for applications that require persistent links to serial hardware.
The feature is primarily managed through the AutoReconnectManager class in the guest JavaScript layer, which coordinates with the core SerialPort class to monitor lifecycle events and execute reconnection attempts based on user-defined configurations such as intervals and maximum retry counts.
Sources: guest-js/auto-reconnect-manager.ts, guest-js/index.ts:445-475
Architecture and Components
The reconnection logic is split between a dedicated manager and the main API interface. This separation of concerns allows the reconnection state to be tracked independently of the port's operational state.
AutoReconnectManager
The AutoReconnectManager is the central engine for reconnection logic. It maintains the state of reconnection attempts, handles timers, and executes the reconnectFunction provided by the SerialPort instance.
- State Tracking: It tracks whether the feature is
enabled, theintervalbetween attempts, and thecurrentAttemptsmade. - Timer Management: Uses
NodeJS.Timeoutto schedule staggered reconnection attempts. - Callback Support: Supports an
onReconnectcallback to notify the UI or other modules of success or failure during retry cycles.
Sources: guest-js/auto-reconnect-manager.ts:7-105
SerialPort Integration
The SerialPort class initializes an internal AutoReconnectManager and provides high-level methods to interface with it. When enableAutoReconnect is called, the port sets up a specialized disconnected listener.
The diagram shows the relationship between the SerialPort and the manager's loop.
Sources: guest-js/index.ts:445-475, guest-js/auto-reconnect-manager.ts:110-145
Configuration Options
Reconnection behavior can be customized using the enableAutoReconnect options object.
| Parameter | Type | Default | Description |
|---|---|---|---|
interval | number | 5000 | Time in milliseconds between reconnection attempts. |
maxAttempts | number | null | 10 | Maximum retries before stopping. Set to null for infinite attempts. |
onReconnect | Function | undefined | Callback: (success: boolean, attempt: number) => void. |
Sources: guest-js/auto-reconnect-manager.ts:24-35, guest-js/index.ts:445-450
Reconnection Logic Flow
The reconnection process is triggered by a disconnect event emitted from the native side of the plugin.
Disconnect Detection
The plugin uses a specific event pattern: plugin-serialplugin-disconnected-{path}. When this event is detected, the SerialPort instance sets its isOpen state to false and starts the manager.
Sources: guest-js/index.ts:468-472, guest-js/index.ts:410-415
The Retry Loop
Once started, the manager enters a recursive attempt cycle:
- Check Limits: If
currentAttemptsreachesmaxAttempts, the process stops and logs an error. - Execution: Calls the
reconnectFunction(which internally callsserialPort.open()). - Outcome Handling:
- Success: Resets the attempt counter and stops the timer.
- Failure: Schedules the next
performAttemptcall using the configuredinterval.
The sequence diagram illustrates the retry loop between the JS guest and the native layer.
Sources: guest-js/auto-reconnect-manager.ts:110-155, guest-js/index.ts:451-465
Manual Reconnection
In addition to automatic cycles, the system provides a manualReconnect() method. This is useful for UI implementations where a user might want to force a retry without waiting for the next scheduled interval.
- Pre-check: If the port is already open, it returns
trueimmediately. - Action: Directly invokes the
open()command. - Logging: Provides info/error logs to track the manual intervention.
Sources: guest-js/index.ts:498-515
Testing the Feature
The project includes a comprehensive test suite to verify reconnection behavior without requiring physical hardware toggling. This is achieved by mocking the Tauri invoke and listen functions.
Simulation Pattern
Tests simulate a disconnect by:
- Capturing the callback provided to
mockListen. - Enabling auto-reconnect on the instance.
- Manually setting
serialPort.isOpen = false. - Executing the captured disconnect callback to trigger the manager.
Sources: tests/auto-reconnect.test.ts:22-45
Conclusion
The Automatic Reconnection system provides a resilient layer for serial communication in Tauri applications. By leveraging the AutoReconnectManager, developers can ensure that their hardware integrations are self-healing, handling transient disconnections through configurable retry logic and asynchronous event monitoring.
Sources: guest-js/auto-reconnect-manager.ts, guest-js/index.ts