npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

serial-core

v0.2.2

Published

Resilient serial communication service with automatic reconnection and queues.

Downloads

824

Readme

serial-core

npm version License: GPL-3.0

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 EventEmitter to provide real-time updates on connection status and incoming data.

Installation

npm install serial-core serialport

Note: 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

  1. The service opens the serial port
  2. Sends the handshake command to the device
  3. Waits for a response that matches the pattern
  4. If the pattern matches within the timeout period, the connection is considered successful
  5. 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