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

@danidoble/serial-node-relay

v0.0.2

Published

A Node.js library to control serial relays using SerialPort and Serial-Core.

Readme

Serial Node Relay

A powerful TypeScript library to control serial relay devices using Node.js. Built on top of SerialPort and Serial-Core for robust serial communication.

npm version License: GPL-3.0 Node.js Version

Features

  • Easy Relay Control - Turn relays on/off with simple methods
  • Serial Communication - Built on SerialPort for reliable serial connections
  • Event-Driven - EventEmitter-based architecture for reactive programming
  • Type-Safe - Full TypeScript support with comprehensive type definitions
  • Well-Tested - Extensive test coverage with Vitest (65+ tests)
  • JSDoc Documented - Complete JSDoc comments for all public APIs
  • Flexible Configuration - Customizable handshake and connection settings

Installation

npm install @danidoble/serial-node-relay serial-core serialport

Or with yarn:

yarn add @danidoble/serial-node-relay serial-core serialport

Or with bun:

bun add @danidoble/serial-node-relay serial-core serialport

Quick Start

import { Relay } from '@danidoble/serial-node-relay';

const relay = new Relay({
  path: '/dev/ttyUSB0', // Serial port path
  baudRate: 9600, // Baud rate
  autoConnect: true, // Auto-connect on instantiation
  reconnectInterval: 2000 // Reconnection interval in ms
});

// Handle connection
relay.on('serial:connected', info => {
  console.log('Connected:', info);
});

// Handle serial messages
relay.on('serial:message', message => {
  console.log('Message:', message.name);
});

// Start the relay service
relay.start();

// Turn relay 1 on
await relay.turnOn({ rele: 1 });

// Turn relay 1 off
await relay.turnOff({ rele: 1 });

// Toggle relay 1 (on -> off with 300ms delay)
await relay.toggle({ rele: 1, ms: 300 });

// Stop the service
await relay.stop();

API Reference

Relay Class

Constructor

constructor(config: SerialConfig)

Creates a new Relay instance with the specified serial configuration.

Parameters:

  • config (SerialConfig): Configuration object
    • path (string): Serial port path (e.g., /dev/ttyUSB0)
    • baudRate (number): Baud rate (default: 9600)
    • autoConnect (boolean): Auto-connect on instantiation
    • reconnectInterval (number): Reconnection interval in milliseconds
    • handshake (optional): Custom handshake configuration

Methods

start(): void

Starts the relay service and initiates connection to the serial device.

relay.start();
stop(): Promise<void>

Stops the relay service and closes the serial connection.

await relay.stop();
turnOn(options?: RelayAction): Promise<void>

Sends a turn-on command to activate a specific relay.

await relay.turnOn(); // Turn on relay 1 (default)
await relay.turnOn({ rele: 2 }); // Turn on relay 2
turnOff(options?: RelayAction): Promise<void>

Sends a turn-off command to deactivate a specific relay.

await relay.turnOff(); // Turn off relay 1 (default)
await relay.turnOff({ rele: 3 }); // Turn off relay 3
toggle(options?: ToggleOptions): Promise<void>

Toggles a relay on and off with configurable delay and direction.

await relay.toggle(); // Toggle relay 1 (on->off, 300ms delay)
await relay.toggle({ rele: 2, ms: 500 }); // Toggle relay 2 with 500ms delay
await relay.toggle({ rele: 1, inverse: true, ms: 100 }); // Toggle off->on with 100ms delay

Options:

  • rele (number): Relay number (default: 1)
  • ms (number): Delay in milliseconds (default: 300)
  • inverse (boolean): Reverse toggle direction - off->on instead of on->off (default: false)

Events

serial:connected

Emitted when the serial connection is established.

relay.on('serial:connected', info => {
  console.log('Connected:', info);
});

serial:disconnected

Emitted when the serial connection is closed.

relay.on('serial:disconnected', reason => {
  console.log('Disconnected:', reason);
});

serial:message

Emitted when a serial message is received and processed.

relay.on('serial:message', message => {
  console.log('Message:', {
    name: message.name, // Human-readable name
    description: message.description,
    relay: message.relay, // Relay number
    no_code: message.no_code, // Status code
    request: message.request // Original request alias
  });
});

serial:error

Emitted when a serial communication error occurs.

relay.on('serial:error', error => {
  console.error('Serial error:', error);
});

serial:status

Emitted when the serial status changes.

relay.on('serial:status', status => {
  console.log('Status:', status);
});

Commands Class

The Commands class provides low-level command building utilities:

import { Commands } from '@danidoble/serial-node-relay';

// Build commands
Commands.activate(1); // Create activation command for relay 1
Commands.deactivate(1); // Create deactivation command
Commands.connection(1); // Create connection/status check command
Commands.custom(data); // Create custom command with checksum
Commands.expectedResponseConnection(1); // Get expected response pattern

Advanced Configuration

Custom Handshake

import { Commands } from '@danidoble/serial-node-relay';

const relay = new Relay({
  path: '/dev/ttyUSB0',
  baudRate: 9600,
  handshake: {
    command: Buffer.from(Commands.connection(1)),
    pattern: Buffer.from(Commands.connection(1)).toString('hex'),
    timeout: 1000,
    hexPattern: true
  }
});

With Parser

import { ByteLengthParser } from 'serialport';

const relay = new Relay({
  path: '/dev/ttyUSB0',
  baudRate: 9600,
  parser: new ByteLengthParser({ length: 4 })
});

Examples

Multiple Relays

const relay = new Relay({ path: '/dev/ttyUSB0', baudRate: 9600 });

relay.on('serial:connected', async () => {
  // Control multiple relays
  await relay.turnOn({ rele: 1 });
  await relay.turnOn({ rele: 2 });
  await relay.turnOn({ rele: 3 });
});

Sequential Operations

async function sequence() {
  try {
    await relay.turnOn({ rele: 1 });
    await new Promise(r => setTimeout(r, 500));
    await relay.turnOff({ rele: 1 });
  } catch (error) {
    console.error('Sequence failed:', error);
  }
}

Monitoring Relay Status

relay.on('serial:message', message => {
  switch (message.no_code) {
    case 1:
      console.log(`Relay ${message.relay} turned OFF`);
      break;
    case 2:
      console.log(`Relay ${message.relay} turned ON`);
      break;
    default:
      console.log(`Relay ${message.relay}: ${message.name}`);
  }
});

Development

Setup

npm install

Available Scripts

  • npm run dev - Watch mode development with TypeScript compilation
  • npm run build - Build the library and format code
  • npm run test - Run tests with Vitest
  • npm run typecheck - Type check without emitting
  • npm run lint - Run ESLint
  • npm run format - Format code with Prettier
  • npm run clean - Remove build artifacts

Running Tests

npm run test

All tests pass (65+ tests covering Commands, Relay, and utility functions).

Building

npm run build

This will:

  1. Format the source code with Prettier
  2. Compile TypeScript to JavaScript and type definitions

Requirements

  • Node.js: >= 18.0.0
  • serial-core: ^0.2.0-dev.5
  • serialport: ^13.0.0

License

GPL-3.0 © Danidoble

Contributing

Contributions are welcome! Please read our CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests.

Support

Changelog

See CHANGELOG.md for version history and updates.