jsmodbus Documentation

repository·v4.0-dev·Indexed 19 days ago

https://github.com/cloud-automation/node-modbus

An implementation of the Serial/TCP Modbus protocol for Node.js (version 4.1.0). It provides a client and server implementation for Modbus TCP and RTU, supporting function codes 1-6, 15, 16, and 43/14. The library includes a CLI tool for performing TCP read operations (Coils, Discrete Inputs, Holding Registers, and Input Registers) and a RequestFactory for generating Modbus request bodies.

Tokens
10.1K
Snippets
38
Records
45
Agent score
67%

What's inside jsmodbus

  1. Install jsmodbus

    v4.0-dev

    You can install jsmodbus as a local dependency for your project or globally to use its Command Line Interface (CLI).

    # Install as a local dependency
    npm install jsmodbus
    
    # Install globally to use the CLI
    npm install -g jsmodbus
  2. Understand the ModbusRequestBody abstraction

    v4.0-dev

    The ModbusRequestBody is an abstract base class used to represent different types of Modbus requests. You should not instantiate this class directly; instead, use the specific request body implementations provided by the library (e.g., for reading coils or writing registers).

    Key properties and methods available on all request body instances:

    • fc: Returns the FunctionCode associated with the request.
    • createPayload(): Returns a Buffer representing the byte-level payload of the request.
    • byteCount: Returns the number of bytes in the request payload.
    • name: Returns the ModbusRequestTypeName identifying the request type.
    • count: Returns the quantity of items (registers, coils, etc.) being addressed.
    • isException: A boolean indicating if the request is an exception request.
    // Note: ModbusRequestBody is abstract and cannot be instantiated directly.
    // Use specific implementations like ReadHoldingRegisters instead.
  3. Understand the ModbusAbstractRequest interface

    v4.0-dev

    The ModbusAbstractRequest is an abstract base class used to define the structure of Modbus requests. While you typically use concrete implementations provided by the library, understanding this interface is useful when implementing custom request types.

    Key properties available on a request include:

    • body: The Modbus function code and its specific parameters (of type ModbusRequestBody).
    • unitId, slaveId, and address: These are aliases for the same value representing the target device ID (type number).
    • byteCount: The calculated number of bytes in the request payload.
    • createPayload(): An abstract method that returns a Buffer representing the serialized Modbus request.
  4. Use the jsmodbus CLI to read Modbus data

    v4.0-dev

    The jsmodbus CLI allows you to perform Modbus TCP read operations directly from the terminal. You can read Coils, Discrete Inputs, Holding Registers, or Input Registers by specifying the host, unit ID, and a range of addresses.

    Command Syntax

    jsmodbus <command> <host> <unitId> <range> [options]

    Commands

    • fc01: Read Coils
    • fc02: Read Discrete Inputs
    • fc03: Read Holding Registers
    • fc04: Read Input Registers

    Arguments

    • <host>: The IP address or hostname of the Modbus server.
    • <unitId>: The Modbus Unit ID (integer).
    • <range>: The address range to read, formatted as start:end (e.g., 0:10).

    Options

    • -p, --port <port>: Modbus Port (defaults to 502).
    • -r, --repeat <time>: Repeat the request at the specified interval in milliseconds.
    • -b, --buffer: Print the output as a Buffer instead of an array.
    • -t, --timeout <timeout>: Connection timeout in milliseconds (defaults to 2000).
    • -bm, --benchmark: Show timestamp benchmark information (transfer and wait times).
    # Example: Read holding registers from 0 to 10 on host 127.0.0.1, port 502, repeating every 1000ms
    jsmodbus fc03 127.0.0.1 1 0:10 --port 502 --repeat 1000
  5. Debug jsmodbus output

    v4.0-dev

    The library uses the debug module for internal logging. To view debugging information, set the DEBUG environment variable. To see all debug output, use *.

    export DEBUG=*
  6. Create a Modbus TCP Server

    v4.0-dev

    To implement a Modbus TCP server, wrap a standard Node.js net.Server instance with modbus.server.TCP.

    const modbus = require('jsmodbus')
    const net = require('net')
    const netServer = new net.Server()
    const server = new modbus.server.TCP(netServer)
    
    netServer.listen(502)
  7. Create a Modbus TCP Client

    v4.0-dev

    To create a TCP client, instantiate Modbus.client.TCP by passing a Node.js net.Socket instance and a unitId.

    const Modbus = require('jsmodbus')
    const net = require('net')
    const socket = new net.Socket()
    const unitId = 1 // Replace with your unit ID
    const client = new Modbus.client.TCP(socket, unitId)
    
    const options = {
      'host' : '127.0.0.1',
      'port' : 502
    }
    
    socket.connect(options)
  8. Create a Modbus RTU Client

    v4.0-dev

    To create an RTU client, instantiate Modbus.client.RTU by passing a serialport instance and an address.

    const Modbus = require('jsmodbus')
    const SerialPort = require('serialport')
    
    const options = {
      baudRate: 57600
    }
    
    const address = 1 // Replace with your unit address
    const socket = new SerialPort("/dev/tty-usbserial1", options)
    const client = new Modbus.client.RTU(socket, address)
  9. Read Coils using the Client API

    v4.0-dev

    The client API uses Promises for Modbus operations. When calling readCoils(offset, count), the response object contains the data in resp.response.body.coils (an Array) and resp.response.body.payload (a Buffer).

    // Assuming socket and client are already initialized
    // For serialport, use socket.on('open', ...) instead of 'connect'
    socket.on('connect', function () {
      client.readCoils(0, 13).then(function (resp) {
        // resp structure: { response : [TCP|RTU]Response, request: [TCP|RTU]Request }
        // Data location: resp.response.body.coils (Array) or resp.response.body.payload (Buffer)
        console.log(resp);
      }, console.error);
    });
    
    socket.connect(options);
  10. Access Modbus Codes, Errors, and Requests

    v4.0-dev

    The library exports several namespaces to help with protocol handling and debugging:

    • codes: Modbus exception and function codes.
    • errors: Error objects thrown by the library.
    • requests: Available Modbus request types, including UserRequest.
    • responses: Modbus response types.
    • limits: Protocol-specific constants and limits.