Basic reconnect
import { SerialPilot } from 'serialpilot' import { SerialPilotReconnect } from '@serialpilot/reconnect'const port = new SerialPilot({ path: ‘/dev/ttyUSB0’, baudRate: 9600, autoOpen: false, })
const reconnect = new SerialPilotReconnect({ port })
reconnect.on(‘reconnecting’, n => console.log(
attempt ${n})) reconnect.on(‘reconnected’, n => console.log(back after ${n} tries)) reconnect.on(‘reconnect-failed’, () => console.error(‘gave up’))
reconnect.start() port.open()
Set autoOpen: false on the port — the reconnect wrapper takes over open/close orchestration, and you call port.open() once after starting the wrapper.
Reconnect by device, not by path
USB paths shift when devices replug into a different port. Pin to the device's fingerprint instead, and the wrapper finds it again wherever it shows up:
const reconnect = new SerialPilotReconnect({
port,
deviceFilter: { vendorId: '2341' },
})
Exponential backoff
Hammering a missing device every second wastes CPU and floods the OS log. Tell the wrapper to back off, with a sensible cap:
const reconnect = new SerialPilotReconnect({
port,
reconnectInterval: 500, // start at 500 ms
backoffFactor: 2, // double each attempt
maxReconnectInterval: 30000, // cap at 30 s
maxReconnectAttempts: 20,
})
Full options
| Option | Default | Notes |
|---|---|---|
autoReconnect | true | Master switch. |
reconnectInterval | 1000 | Milliseconds between attempts. |
maxReconnectAttempts | Infinity | Cap before reconnect-failed. |
backoffFactor | 1 | >1 enables exponential backoff. |
maxReconnectInterval | 30000 | Backoff ceiling. |
deviceFilter | — | DeviceFilter for find-by-fingerprint. |
onDisconnect / onReconnect / onReconnectFailed | — | Imperative-style callbacks. |
Events & methods
- Events:
disconnect,reconnecting,reconnected,reconnect-failed. - Methods:
start(),stop(),forceReconnect().
disconnectAfter: { bytesWritten: 256 } on a MockBinding port to drive your reconnect path in unit tests. Real disconnect, no real hardware.