@ya-modbus/cli
v0.7.0
Published
CLI tool for testing and developing Modbus device drivers
Maintainers
Readme
@ya-modbus/cli
CLI tool for testing and developing Modbus device drivers.
Requirements
- Node.js >= 18.0.0
Features
- Discover devices automatically by scanning serial ports for Modbus RTU devices
- Read data points from Modbus devices (RTU/TCP)
- Write data points to Modbus devices with confirmation
- List supported devices from multi-device drivers
- Auto-detect drivers from current package during development
- Multiple output formats (table, JSON)
- Performance metrics (response time, operation count)
- Value verification after writes
Installation
Global Installation (Production)
npm install -g @ya-modbus/cliLocal Development
npm install --save-dev @ya-modbus/cliUsage
Read Data Points
Read single data point:
# RTU (serial) - uses driver defaults for baud rate, parity, etc.
ya-modbus read \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--data-point temperature
# TCP
ya-modbus read \
--host 192.168.1.100 \
--slave-id 1 \
--data-point temperatureRead multiple data points:
# Uses driver defaults
ya-modbus read \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--data-point temperature humidityRead all readable data points:
# Uses driver defaults
ya-modbus read \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--allJSON output:
# Uses driver defaults
ya-modbus read \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--data-point temperature \
--format jsonWrite Data Points
Write with confirmation:
# Uses driver defaults
ya-modbus write \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--data-point setpoint \
--value 25.5Write without confirmation:
# Uses driver defaults
ya-modbus write \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--data-point setpoint \
--value 25.5 \
--yesWrite with verification:
# Uses driver defaults
ya-modbus write \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--data-point setpoint \
--value 25.5 \
--yes \
--verifyDiscover Devices
Automatic device discovery scans a serial port to find Modbus RTU devices by testing different slave IDs and connection parameters.
Quick discovery (uses driver configuration):
# Discover using driver SUPPORTED_CONFIG to limit parameter combinations
ya-modbus discover \
--port /dev/ttyUSB0 \
--driver @ya-modbus/driver-xymd1Discovery without driver (tests common parameters):
# Tests standard baud rates (9600, 19200) and common parameters
ya-modbus discover --port /dev/ttyUSB0Thorough discovery (tests all parameters):
# Tests all standard Modbus parameters (slower but comprehensive)
ya-modbus discover \
--port /dev/ttyUSB0 \
--strategy thoroughControl number of devices to find:
# Stop after finding one device (default behavior)
ya-modbus discover \
--port /dev/ttyUSB0 \
--driver @ya-modbus/driver-xymd1 \
--max-devices 1
# Find unlimited devices
ya-modbus discover \
--port /dev/ttyUSB0 \
--max-devices 0Silent mode (for scripts):
# Suppress all progress messages, output only results
ya-modbus discover \
--port /dev/ttyUSB0 \
--silent \
--format json
# Example: Extract slave IDs with jq
devices=$(ya-modbus discover -p /dev/ttyUSB0 --silent -f json | jq '.[].slaveId')Verbose progress:
# Show each parameter combination being tested
ya-modbus discover \
--port /dev/ttyUSB0 \
--verboseCustom timing:
# Adjust timeout and delay for specific bus conditions
ya-modbus discover \
--port /dev/ttyUSB0 \
--timeout 100 \
--delay 50Discovery Options:
--strategy <type>- Discovery strategy:quick(default) orthorough- Quick: Tests SUPPORTED_CONFIG params or common Modbus parameters
- Thorough: Tests all standard Modbus parameters (8 baud rates, 3 parity modes, 247 addresses)
--driver <package>- Driver package to use for parameter prioritization (auto-detects from cwd if not specified)--timeout <ms>- Response timeout in milliseconds (default: 1000)--delay <ms>- Delay between attempts in milliseconds (default: 100)--max-devices <count>- Maximum number of devices to find (default: 1, use 0 for unlimited)--verbose- Show detailed progress with current parameters being tested--silent- Suppress all output except final result (useful for scripts)--format <type>- Output format:table(default) orjson
Output Example:
Starting Modbus device discovery on /dev/ttyUSB0...
Strategy: quick
Timeout: 1000ms, Delay: 100ms
Using driver: @ya-modbus/driver-xymd1
Using driver SUPPORTED_CONFIG to limit parameter combinations
Testing 1482 parameter combinations...
✓ Found device: Slave ID 52 @ 9600,N,8,1
Discovery complete! Found 1 device(s).
┌──────────┬───────────┬────────┬──────────┬──────────┬────────────┬──────────────┐
│ Slave ID │ Baud Rate │ Parity │ Data Bits│ Stop Bits│ Response │ Supports │
│ │ │ │ │ │ Time (ms) │ │
├──────────┼───────────┼────────┼──────────┼──────────┼────────────┼──────────────┤
│ 52 │ 9600 │ none │ 8 │ 1 │ 45.67 │ FC04 │
└──────────┴───────────┴────────┴──────────┴──────────┴────────────┴──────────────┘Discovery Time Estimates:
Based on real-world testing with default settings (timeout=1000ms, delay=100ms):
- Quick with driver: ~25 minutes (1,482 combinations typical, ~1.0s per combination)
- Quick without driver: ~50 minutes (2,964 combinations, ~1.0s per combination)
- Thorough: ~6.5 hours (23,712 combinations, ~1.0s per combination)
Performance Tips:
- Reduce timeout for faster scans:
--timeout 500achieves ~0.5s per combination (2x faster) - Use
--driverto prioritize likely parameters and reduce search space - Use
--max-devices 1(default) to stop after finding first device - Further reduce
--timeoutif your devices respond quickly (e.g.,--timeout 100for local devices) - Increase
--delayif you experience bus contention
Connection Options
RTU (Serial):
--port <path>- Serial port (e.g.,/dev/ttyUSB0,COM3)--baud-rate <rate>- Baud rate (default: 9600)--parity <type>- Parity: none, even, odd (default: even)--data-bits <bits>- Data bits: 7 or 8 (default: 8)--stop-bits <bits>- Stop bits: 1 or 2 (default: 1)
TCP:
--host <host>- TCP host (IP or hostname)--tcp-port <port>- TCP port (default: 502)
Common:
--slave-id <id>- Modbus slave ID (1-247) (required)--timeout <ms>- Response timeout in milliseconds (default: 1000)--driver <package>- Explicit driver package name--device <key>- Device key for multi-device drivers (uselist-devicesto see available devices)
Driver Loading
Auto-detect (development mode):
When running from a driver package directory, the CLI auto-detects the driver:
cd packages/driver-xymd1
npx ya-modbus read --port /dev/ttyUSB0 --slave-id 1 --data-point temperatureExplicit driver (production mode):
ya-modbus read \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--slave-id 1 \
--data-point temperatureDriver Defaults and Validation
The CLI automatically uses configuration defaults from driver packages, reducing the number of required options.
Driver-provided defaults:
Drivers export DEFAULT_CONFIG and SUPPORTED_CONFIG constants that the CLI uses to:
- Apply sensible defaults for connection parameters (baud rate, parity, data bits, stop bits, slave ID)
- Validate user input against device-specific constraints
- Show helpful error messages with valid values and defaults
Configuration priority (highest to lowest):
- User-specified - Command-line options (e.g.,
--baud-rate 19200) - Device-specific -
DEVICES[key].defaultConfigwhen--deviceis used - Driver-level -
DEFAULT_CONFIGexport from driver package - CLI fallback - Built-in defaults (9600 8E1, slave ID 1)
The same priority applies to validation constraints (supportedConfig).
Before (manual configuration):
ya-modbus read \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--baud-rate 9600 \
--parity even \
--data-bits 8 \
--stop-bits 1 \
--slave-id 1 \
--data-point temperatureAfter (using driver defaults):
# CLI uses driver defaults - just specify port and data point
ya-modbus read \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--data-point temperatureOverriding defaults:
User-specified values always take precedence over driver defaults:
# Use driver defaults but override baud rate and slave ID
ya-modbus read \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--baud-rate 19200 \
--slave-id 5 \
--data-point temperatureValidation:
The CLI validates user input against driver constraints. Invalid values trigger helpful error messages:
$ ya-modbus read --driver @ya-modbus/driver-xymd1 --port /dev/ttyUSB0 --baud-rate 115200
Error: Invalid baud rate 115200. This driver supports: 9600, 14400, 19200 (default: 9600)Backward compatibility:
- Drivers without
DEFAULT_CONFIGwork as before (all parameters required) - User-specified values always override defaults
- TCP connections ignore serial-specific defaults
Working with Third-Party and Development Drivers
⚠️ Important Safety Notes:
The CLI supports loading drivers from:
- First-party drivers (official
ya-modbus-driver-*packages) - Third-party drivers (community/vendor packages)
- Development drivers (local packages under development)
When using third-party or development drivers, be aware:
Runtime Validation: The CLI validates driver exports at load time and provides helpful error messages:
$ ya-modbus read --driver broken-driver --port /dev/ttyUSB0 Error: Invalid DEFAULT_CONFIG: baudRate must be a number, got string. Fix: export const DEFAULT_CONFIG = { baudRate: 9600, ... } // number, not stringDevelopment Mode Hints: When loading local drivers via auto-detection, invalid configurations trigger detailed fix instructions to help driver developers.
Configuration Safety: Both
DEFAULT_CONFIGandSUPPORTED_CONFIGare validated:- Type checking (baudRate must be number, not string)
- Array validation (validBaudRates must be an array)
- Range validation (validAddressRange must be [min, max])
Merged Validation: After applying defaults, the CLI validates that
DEFAULT_CONFIGvalues comply withSUPPORTED_CONFIGconstraints. This catches broken third-party driver defaults:Error: Invalid baud rate 38400. This driver supports: 9600, 14400, 19200 (default: 9600)
Show Driver Defaults:
Use the show-defaults command to inspect driver configuration before use:
# Show defaults from installed driver
ya-modbus show-defaults --driver @ya-modbus/driver-xymd1
# Show defaults from local development driver (auto-detects from cwd)
cd packages/my-driver
ya-modbus show-defaults
# JSON output for tooling
ya-modbus show-defaults --driver @ya-modbus/driver-xymd1 --format jsonOutput:
Driver Defaults
===============
DEFAULT_CONFIG:
baudRate: 9600
parity: "even"
dataBits: 8
stopBits: 1
defaultAddress: 1
SUPPORTED_CONFIG:
validBaudRates: [9600,14400,19200]
validParity: ["even","none"]
validDataBits: [8]
validStopBits: [1]
validAddressRange: [1,247]List Supported Devices (Multi-Device Drivers):
Some drivers support multiple device variants (e.g., an energy meter family driver supporting OR-WE-514, OR-WE-516, etc.). Use list-devices to see available devices:
# List devices from installed driver
ya-modbus list-devices --driver ya-modbus-driver-orno-we
# List devices from local development driver (auto-detects from cwd)
cd packages/my-driver
ya-modbus list-devices
# JSON output for tooling
ya-modbus list-devices --driver ya-modbus-driver-orno-we --format jsonOutput:
Supported Devices
┌────────────┬──────────────┬───────────┬─────────────┬─────────────────────────┐
│ Device │ Manufacturer │ Model │ Config │ Description │
├────────────┼──────────────┼───────────┼─────────────┼─────────────────────────┤
│ or-we-514 │ ORNO │ OR-WE-514 │ 9600 8E1 │ Single-phase meter │
│ or-we-516 │ ORNO │ OR-WE-516 │ 9600 8E1 │ Three-phase meter │
└────────────┴──────────────┴───────────┴─────────────┴─────────────────────────┘
Total: 2 device(s)For single-device drivers, the command indicates there is no DEVICES registry:
This driver does not export a DEVICES registry.
It is a single-device driver.
Default config: 9600 8E1Using Multi-Device Drivers:
When using a multi-device driver, specify the device with --device:
# Read from a specific device variant
ya-modbus read \
--driver ya-modbus-driver-orno-we \
--device or-we-514 \
--port /dev/ttyUSB0 \
--data-point voltage
# The --device option applies device-specific defaults and validation
ya-modbus write \
--driver ya-modbus-driver-orno-we \
--device or-we-516 \
--port /dev/ttyUSB0 \
--data-point relay_state \
--value 1If --device is omitted with a multi-device driver, the driver-level defaults are used. If --device is specified with a single-device driver, a warning is shown and the option is ignored.
Best Practices:
- Test with
show-defaults: Before using a third-party driver, inspect its configuration - Validate in development: Run
ya-modbus show-defaultsfrom your driver directory to validate configuration - Read error messages: The CLI provides specific fix instructions for configuration errors
- Use first-party drivers: Official drivers undergo rigorous validation
Examples
Read temperature from XY-MD1 sensor
# Auto-detect driver (from driver package directory) - uses driver defaults
cd packages/driver-xymd1
npx ya-modbus read \
--port /dev/ttyUSB0 \
--data-point temperature humidity \
--format tableOutput:
Data Point Value Unit
────────────────────────────────
Temperature 24.5 °C
Humidity 65.2 %
Performance:
Response time: 45ms
Operations: 2
Errors: 0Write and verify setpoint
# Uses driver defaults for baud rate, parity, etc.
ya-modbus write \
--driver @ya-modbus/driver-xymd1 \
--port /dev/ttyUSB0 \
--data-point device_address \
--value 5 \
--yes \
--verifyTest TCP connection
ya-modbus read \
--host 192.168.1.100 \
--tcp-port 502 \
--slave-id 1 \
--driver @ya-modbus/driver-xymd1 \
--all \
--format jsonDevelopment
Running Tests
npm testBuilding
npm run buildWatch Mode
npm run devTroubleshooting
Permission Denied (Linux)
Add your user to the dialout group:
sudo usermod -a -G dialout $USER
# Log out and log back inDriver Not Found
Ensure the driver package is installed:
npm install @ya-modbus/driver-xymd1Or use auto-detect mode from the driver package directory.
Timeout Errors
- Check physical connection (RS-485 termination, wiring)
- Verify slave ID is correct
- Try slower baud rate (e.g., 4800)
- Increase timeout:
--timeout 2000
