SerialPilot

/03 — Recipes

Production reconnect

Real devices come and go. They reboot mid-session, change USB paths between hosts, and survive fewer cable cycles than spec sheets claim. @serialpilot/reconnect wraps your port and brings it back when the world wobbles.

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

OptionDefaultNotes
autoReconnecttrueMaster switch.
reconnectInterval1000Milliseconds between attempts.
maxReconnectAttemptsInfinityCap before reconnect-failed.
backoffFactor1>1 enables exponential backoff.
maxReconnectInterval30000Backoff ceiling.
deviceFilterDeviceFilter for find-by-fingerprint.
onDisconnect / onReconnect / onReconnectFailedImperative-style callbacks.

Events & methods

  • Events: disconnect, reconnecting, reconnected, reconnect-failed.
  • Methods: start(), stop(), forceReconnect().
Pair with the mock Set disconnectAfter: { bytesWritten: 256 } on a MockBinding port to drive your reconnect path in unit tests. Real disconnect, no real hardware.

Edit this page on GitHub