serial-core
v0.2.2
Published
Resilient serial communication service with automatic reconnection and queues.
Downloads
824
Maintainers
Readme
serial-core
Resilient serial communication service with automatic reconnection and queues.
serial-core is a robust TypeScript library designed to manage serial port communications in Node.js applications. It provides a resilient architecture with built-in features for automatic reconnection, message queuing, and device scanning.
[!WARNING] This library is currently in active development. The API is subject to change at any time before the first stable release (v1.0.0).
Features
- Resilience: Automatically handles connection drops and attempts to reconnect.
- Message Queuing: Internal queue manager ensures data is sent sequentially and handles backpressure.
- Auto-Discovery: Can scan for devices by Vendor ID (VID) and Product ID (PID) if a specific path is not provided.
- Handshake Support: Built-in mechanism to verify device connection with a handshake command and response pattern.
- TypeScript Support: Written in TypeScript with full type definitions included.
- Event-Driven: Extends
EventEmitterto provide real-time updates on connection status and incoming data.
Installation
npm install serial-core serialportNote: serialport is a peer dependency.
Usage
Here is a basic example of how to use SerialService:
import { SerialService, SerialStatus } from 'serial-core';
// Configuration
const config = {
// Option 1: Direct path
path: '/dev/ttyUSB0',
// Option 2: Auto-discovery (used if path is not set)
// vendorId: '1234',
// productId: '5678',
baudRate: 9600,
autoConnect: true,
reconnectInterval: 5000,
// Optional: Verify connection
// handshake: {
// command: 'PING\n',
// pattern: 'PONG',
// timeout: 2000
// }
};
// Initialize Service
const serial = new SerialService(config);
// Listen to Status Changes
serial.on('status', (status: SerialStatus) => {
console.log(`Serial Status: ${status}`);
// Possible values: DISCONNECTED, SCANNING, CONNECTING, CONNECTED, RECONNECTING
});
// Listen to Incoming Data
serial.on('data', (data: any) => {
console.log('Received:', data.toString());
});
// Listen to Errors
serial.on('error', (err: Error) => {
console.error('Serial Error:', err.message);
});
// Send Data
async function sendCommand() {
try {
// Sends data using the internal queue
await serial.send('HELLO_WORLD\n');
console.log('Message sent successfully');
} catch (error) {
console.error('Failed to send:', error);
}
}
// Manual Control
// serial.connect();
// serial.disconnect();Handshake
The handshake feature allows you to verify the device identity and connection before considering the port as fully connected. This is useful when you need to confirm that the connected device is the expected one.
Basic Handshake Configuration
const serial = new SerialService({
path: '/dev/ttyUSB0',
baudRate: 9600,
autoConnect: true,
reconnectInterval: 5000,
handshake: {
command: 'AT\r\n', // Command to send to the device
pattern: /OK/, // Expected response pattern (string or RegExp)
timeout: 2000 // Maximum time to wait for response (ms)
}
});Handshake with Binary Data (Hex Comparison)
When working with devices that respond with binary data or non-printable characters, you can use the hexPattern option to compare responses in hexadecimal format:
const connectionCommand = Buffer.from([0x01, 0x02, 0x03, 0x04]);
const serial = new SerialService({
path: '/dev/ttyUSB0',
baudRate: 9600,
autoConnect: true,
reconnectInterval: 5000,
handshake: {
command: connectionCommand,
pattern: connectionCommand.toString('hex'), // Compare in hex format
timeout: 3000,
hexPattern: true // Enable hex comparison
}
});Handshake Configuration Options
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| command | string \| Buffer | Yes | Command to send to the device upon connection. |
| pattern | string \| RegExp | Yes | Expected pattern in the device response. |
| timeout | number | Yes | Maximum time (in ms) to wait for the handshake response. |
| hexPattern | boolean | No | If true, received data will be converted to hex before pattern matching. Useful for binary protocols. |
How Handshake Works
- The service opens the serial port
- Sends the handshake
commandto the device - Waits for a response that matches the
pattern - If the pattern matches within the
timeoutperiod, the connection is considered successful - If no match or timeout occurs, the connection fails and a reconnection attempt is scheduled
Handshake Examples
Text-based handshake:
handshake: {
command: 'PING\n',
pattern: 'PONG',
timeout: 1000
}RegExp pattern for version checking:
handshake: {
command: 'VERSION\r\n',
pattern: /v\d+\.\d+\.\d+/, // Matches v1.2.3 format
timeout: 2000
}Binary protocol with hex comparison:
handshake: {
command: Buffer.from([0xFF, 0x01, 0x00]),
pattern: 'ff0100', // Expected response in hex
timeout: 3000,
hexPattern: true
}API Reference
SerialService
The main class for managing the serial connection.
Configuration (SerialConfig)
| Property | Type | Description |
|----------|------|-------------|
| path? | string | The system path to the serial port (e.g., /dev/ttyUSB0). |
| vendorId? | string | USB Vendor ID for auto-discovery (if path is omitted). |
| productId? | string | USB Product ID for auto-discovery. |
| baudRate | number | Serial baud rate (default: 9600). |
| autoConnect | boolean | Whether to connect automatically on instantiation. |
| reconnectInterval | number | Time in ms to wait before retrying connection. |
| handshake? | object | Optional handshake configuration to verify device identity. See Handshake section for details. |
Methods
connect(): Promise<void>: Initiates the connection process (scanning -> connecting -> handshake -> connected).disconnect(): Promise<void>: Manually closes the connection and stops reconnection attempts.send(data: string | Buffer, options?): Promise<void>: Queues data to be sent to the device.status:SerialStatus: Getter for the current connection state.
Events
status: Emitted when the connection status changes.connected: Emitted when a connection is successfully established (and handshake passes).disconnected: Emitted when the connection is lost or closed.data: Emitted when data is received from the device.error: Emitted when an error occurs.
License
GPL-3.0-only
