Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

modbus-stream

node-modbus9.5kMIT0.46.0TypeScript support: included

Build Status Package Version

modbus, serial, rtu, ascii, tcp, stream

readme

Modbus Stream

Build Status Package Version

This is a NodeJS module to help you process modbus data. It uses pdu to build the core PDU and then uses transports to extend the rest.

Features

  • <input checked="" disabled="" type="checkbox"> Support almost every standard function code
  • <input checked="" disabled="" type="checkbox"> Support standard exceptions
  • <input checked="" disabled="" type="checkbox"> Support transports
    • <input checked="" disabled="" type="checkbox"> TCP
    • <input checked="" disabled="" type="checkbox"> RTU
    • <input checked="" disabled="" type="checkbox"> ASCII
  • <input checked="" disabled="" type="checkbox"> Support drivers
    • <input checked="" disabled="" type="checkbox"> TCP
    • <input checked="" disabled="" type="checkbox"> UDP
    • <input checked="" disabled="" type="checkbox"> Serial (RS232, RS485)

Example

This is my current test.js file. It creates a client and a server network socket and the server requests coils as soon as the client connects.

var modbus = require("modbus-stream");

modbus.tcp.server({ debug: "server" }, (connection) => {
    connection.readCoils({ address: 5, quantity: 8 }, (err, info) => {
        console.log("response", info.response.data);
    });
}).listen(12345, () => {
    modbus.tcp.connect(12345, { debug: "client" }, (err, connection) => {
        connection.on("read-coils", (request, reply) => {
            reply(null, [ 1, 0, 1, 0, 1, 1, 0, 1 ]);
        });
    });
});

Usage

Connection

To connect to a modbus device over TCP, use:

var modbus = require("modbus-stream");

modbus.tcp.connect(502, "134.2.56.231", { debug: "automaton-2454" }, (err, connection) => {
    // do something with connection
});

To listen for connections over TCP, use:

var modbus = require("modbus-stream");

modbus.tcp.server({ debug: "server" }, (connection) => {
    // do something with connection
}).listen(502, () => {
    // ready
});

To connecto to a modbus device over a serial port, use:

var modbus = require("modbus-stream");

modbus.serial.connect("/dev/ttyS123", { debug: "automaton-123" }, (err, connection) => {
    // do something with connection
});

Requests

After having a connection, you can send requests and listen for responses.

modbus.serial.connect("/dev/ttyS123", { debug: "automaton-123" }, (err, connection) => {
    if (err) throw err;

    connection.readCoils({ address: 52, quantity: 8, extra: { unitId: 25 } }, (err, res) => {
        if (err) throw err;

        console.log(res); // response
    })
});

Every method accepts an object options which have defaults parameters (like address = 0) and a callback, in case you want to see the response from the remote device. Here is a list of supported function codes and the corresponding methods:

Base Reads

  • readCoils (address = 0, quantity = 1)
  • readDiscreteInputs (address = 0, quantity = 1)
  • readHoldingRegisters (address = 0, quantity = 1)
  • readInputRegisters (address = 0, quantity = 1)

Base Writes

  • writeSingleCoil (address = 0, value = 0)
  • writeSingleRegister (address = 0, value = <Buffer 0x00 0x00>)
  • writeMultipleCoils (address = 0, values = [])
  • writeMultipleRegisters (address = 0, values = [ <Buffer 0x00 0x00> ])

File Records

  • readFileRecord (requests = [])
  • writeFileRecord (requests = [])

FIFO

  • readFifoQueue (address = 0)

Advanced

  • maskWriteRegister (address = 0, andmask = 0xFFFF, ormask = 0x0000)
  • readWriteMultipleRegisters (read_address = 0, read_quantity = 1, write_address = 0, values = [ <Buffer 0x00 0x00> ])
  • readDeviceIdentification (type = "BasicDeviceIdentification", id = "ProductName")
  • readExceptionStatus ()
  • getCommEventCounter ()
  • getCommEventLog ()

For more information on these methods, look at the pdu repository which is used to build the packets.

Responses

To respond to remote requests, listen for events.

modbus.serial.connect("/dev/ttyS123", {
    // except "debug", everything else is the default for serial
    baudRate : 9600,
    dataBits : 8,
    stopBits : 1,
    parity   : "none",
    debug    : "automaton-123"
}, (err, connection) => {
    if (err) throw err;

    connection.events.on("read-coils", (req, reply) => {
        console.log(req); // request

        // ...
        return reply(null, [ data ]);
    })
});

Events

There are events propagated from the transports up to the stream. You should bind some event listener just in case the connection or serial device errors or just closes. Remember that in NodeJS, an emitted error event without a listener will cause the process to throw an uncaughtException.

Transport Closed (close)

This event is emitted when the serialport module emits a close event or when a socket emits an end event.

Transport Error (error)

This event if something happens to the underlying stream, like a ECONNRESET or something similar.

changelog

0.46.0 - 16 Feb 2021

  • changes serial driver to only load serialport when invoked

0.45.0 - 16 Feb 2021

  • changes serialport dependency to be an optional one
  • deps:

0.44.0 - 14 Feb 2019

0.43.0 - 14 Feb 2019

  • changes example to show how to define unitId
  • corrects contradiction in README example
  • disables debug
  • deps:
    • dtslint@^0.4.2

0.42.0 - 2 Nov 2018

0.41.0 - 27 Jul 2018

  • transport:
    • serial:
      • fixes not being able to define slaveId (#20)
  • deps:

0.40.1 - 9 May 2018

0.40.0 - 1 Mar 2018

  • transport:
    • serial:
      • adds 'mode' option to be able to select 'ascii' instead of the common serial (RTU)

0.39.0 - 27 Oct 2017

  • transport:
    • expose stream in events

0.38.0 - 19 Sep 2017

  • tcp:
    • add a connection timeout option, connectTimeout (default=10s) (@jhillacre)
  • ci:
    • drop node 0.x, adds v8 (I still make efforts to it works on 0.x)

0.37.0 - 15 Sep 2017

  • transport:
    • serial:
      • allow default slaveId to be passed in constructor
    • tcp:
      • allow default unitId to be passed in constructor (fixes #8)
  • deps:

0.36.0 - 21 Jul 2017

  • tcp: fixes #7

0.35.0 - 20 Jul 2017

  • transport:
    • allow multiple retry timers, allowing tcp to requests to go simultaneously (#6)
  • test:
    • change quirks to split each transport and avoid confusion
    • avoids using reserved word package (fixes #5)

0.34.0 - 6 Jul 2017

  • serial:
    • allow to pass any option that you can use in serialport
    • avoid clearing buffer if it's already cleared

0.33.0 - 4 Jul 2017

  • transport:
    • pass options also to transport to be able to set options there
  • serial:
    • adds maxDataInterval (in ms) between received data blocks

0.32.0 - 4 Jul 2017

  • serial:
    • allow option crc=false to be able to send raw data
    • fixes dropping data with less than 4 bytes

0.31.0 - 4 Jul 2017

  • serial:
    • allow to pass lock option

0.30.0 - 4 Jul 2017

  • tcp:
    • handle packages concatenated in one data event

0.29.0 - 4 Jul 2017

  • tcp:
    • fixes previous commit not properly handling exceptions as it should

0.28.0 - 4 Jul 2017

  • tcp:
    • fixes callbacks not working for exception responses

0.27.0 - 3 Jul 2017

  • transport:
    • adds support for a mutex

0.26.0 - 3 Jul 2017

  • transport:
    • exposes close event
  • readme:
    • adds events section

0.25.0 - 30 Jun 2017

  • transport:
    • propagate error event from stream (#4)
    • store closed state and avoid send data to a closed stream (#4)

0.24.0 - 27 Jun 2017

  • tcp:
    • ensure tcp properly splits packages that come together
  • test:
    • adds quirk tests, fixes double callback invocation
  • deps:

0.23.0 - 26 Jun 2017

  • transport:
    • fixes tcp not clearing before new retries

0.22.0 - 26 Jun 2017

0.21.0 - 26 Jun 2017

  • transport:
    • tcp callback now matches transaction+unit+fcode
    • fixes utf8 non visible whitespace

0.20.0 - 23 Jun 2017

0.19.0 - 22 Jun 2017

  • stream:
    • adds option debuginvert to invert the arrows in incoming/outgoing debug lines
    • adds option debugdate that when passed false will not print date in debug lines
  • transport:
    • fixes replies with unknown function codes
  • deps:

0.18.0 - 20 Jun 2017

  • udp:
    • initial support
  • test:
    • adds node v5, disable node v8 for now, adds node_modules to cache

0.17.0 - 14 Jun 2017

  • transport:
    • tcp:
      • fixes calling socket.close() instead of socket.end()
  • modbus:
    • pass all options to tcp transport (fixes #3)

0.16.0 - 12 Jun 2017

  • transport:
    • serial:
      • adds support for data coming in parts (checking CRC match)

0.15.0 - 8 Jun 2017

  • transport:
    • fixes timeout error returned not having a proper code
    • tcp:
      • return a proper code when not being able to connect to remote host/port
    • serial:
      • return a proper code when not being able to open port
  • stream:
    • add iso date to debug lines
  • test:
    • adds node v8
  • deps:

0.14.4 - 19 May 2017

0.14.3 - 19 May 2017

0.14.2 - 11 May 2017

0.14.1 - 27 Apr 2017

0.14.0 - 20 Apr 2017

0.13.0 - 13 Apr 2017

  • transport:
    • ascii:
      • check slave id response match
    • serial:
      • check slave id response match

0.12.0 - 13 Apr 2017

  • transport:
    • changes beforewrite/afterwrite to beforerequest/afterrequest

0.11.0 - 13 Apr 2017

0.10.0 - 13 Apr 2017

  • serial:
    • adds support for serialport from 1.7.1 and above
  • transport:
    • only stop retry timer if transport unwrap returns ok
    • serial:
      • avoid errors when receiving data with less than 3 bytes

0.9.0 - 13 Apr 2017

  • transport:
    • fixes static method prepare()
    • fixes transport send using prototype.apply instead of prototype.call
  • stream:
    • fixes typo of addres

0.8.0 - 13 Apr 2017

  • node:
    • updates code to work properly on 0.10
  • readme:
    • removes v6 reference since now it should work from 0.10 onwards

0.7.0 - 13 Apr 2017

  • node:
    • adds support for at least v0.10
  • transports:
    • return an error (GatewayTargetDeviceFailedToRespond) after retries run out
    • adds support for beforewrite and afterwrite
    • tcp:
      • adds default retry timeout to 30 seconds
  • deps:

0.6.0 - 12 Apr 2017

  • modbus:
    • adds serial options for retrying
    • expose stream and pdu (modbus-pdu module)
  • stream:
    • wrap data when using write() directly
  • transport:
    • support request codes that pdu does not know
  • deps:

0.5.0 - 31 Mar 2017

  • initial stable version
  • transports:
    • ascii
    • serial
    • tcp
  • drivers:
    • rtu
    • tcp