@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.
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 serialportOr with yarn:
yarn add @danidoble/serial-node-relay serial-core serialportOr with bun:
bun add @danidoble/serial-node-relay serial-core serialportQuick 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 objectpath(string): Serial port path (e.g.,/dev/ttyUSB0)baudRate(number): Baud rate (default: 9600)autoConnect(boolean): Auto-connect on instantiationreconnectInterval(number): Reconnection interval in millisecondshandshake(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 2turnOff(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 3toggle(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 delayOptions:
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 patternAdvanced 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 installAvailable Scripts
npm run dev- Watch mode development with TypeScript compilationnpm run build- Build the library and format codenpm run test- Run tests with Vitestnpm run typecheck- Type check without emittingnpm run lint- Run ESLintnpm run format- Format code with Prettiernpm run clean- Remove build artifacts
Running Tests
npm run testAll tests pass (65+ tests covering Commands, Relay, and utility functions).
Building
npm run buildThis will:
- Format the source code with Prettier
- 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.
