A Node.js library to control serial relays using SerialPort and Serial-Core.
npm install @danidoble/serial-node-relayA powerful TypeScript library to control serial relay devices using Node.js. Built on top of SerialPort and Serial-Core for robust serial communication.



- 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
``bash`
npm install @danidoble/serial-node-relay serial-core serialport
Or with yarn:
`bash`
yarn add @danidoble/serial-node-relay serial-core serialport
Or with bun:
`bash`
bun add @danidoble/serial-node-relay serial-core serialport
`typescript
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();
`
#### Constructor
`typescript`
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.
`typescript`
relay.start();
##### stop(): Promise
Stops the relay service and closes the serial connection.
`typescript`
await relay.stop();
##### turnOn(options?: RelayAction): Promise
Sends a turn-on command to activate a specific relay.
`typescript`
await relay.turnOn(); // Turn on relay 1 (default)
await relay.turnOn({ rele: 2 }); // Turn on relay 2
##### turnOff(options?: RelayAction): Promise
Sends a turn-off command to deactivate a specific relay.
`typescript`
await relay.turnOff(); // Turn off relay 1 (default)
await relay.turnOff({ rele: 3 }); // Turn off relay 3
##### toggle(options?: ToggleOptions): Promise
Toggles a relay on and off with configurable delay and direction.
`typescript`
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)
#### serial:connected
Emitted when the serial connection is established.
`typescript`
relay.on('serial:connected', info => {
console.log('Connected:', info);
});
#### serial:disconnected
Emitted when the serial connection is closed.
`typescript`
relay.on('serial:disconnected', reason => {
console.log('Disconnected:', reason);
});
#### serial:message
Emitted when a serial message is received and processed.
`typescript`
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.
`typescript`
relay.on('serial:error', error => {
console.error('Serial error:', error);
});
#### serial:status
Emitted when the serial status changes.
`typescript`
relay.on('serial:status', status => {
console.log('Status:', status);
});
The Commands class provides low-level command building utilities:
`typescript
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
`
`typescript
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
}
});
`
`typescript
import { ByteLengthParser } from 'serialport';
const relay = new Relay({
path: '/dev/ttyUSB0',
baudRate: 9600,
parser: new ByteLengthParser({ length: 4 })
});
`
`typescript
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 });
});
`
`typescript`
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);
}
}
`typescriptRelay ${message.relay} turned OFF
relay.on('serial:message', message => {
switch (message.no_code) {
case 1:
console.log();Relay ${message.relay} turned ON
break;
case 2:
console.log();Relay ${message.relay}: ${message.name}
break;
default:
console.log();`
}
});
`bash`
npm install
- 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
`bash`
npm run test
All tests pass (65+ tests covering Commands, Relay, and utility functions).
`bash``
npm run build
This will:
1. Format the source code with Prettier
2. Compile TypeScript to JavaScript and type definitions
- Node.js: >= 18.0.0
- serial-core: ^0.2.0-dev.5
- serialport: ^13.0.0
GPL-3.0 © Danidoble
Contributions are welcome! Please read our CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests.
- 📖 Documentation
- 🐛 Issue Tracker
- 💬 Discussions
See CHANGELOG.md for version history and updates.