• Stars
    star
    541
  • Rank 82,114 (Top 2 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created about 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A pure JavaScript implemetation of MODBUS-RTU (and TCP) for NodeJS

modbus-serial

A pure JavaScript implementation of MODBUS-RTU (Serial and TCP) for NodeJS.

NPM download NPM version Build Status

Modbus is a serial communications protocol, first used in 1979. Modbus is simple and robust, openly published, royalty-free and easy to deploy and maintain.

This package makes Modbus calls and serve fun and easy.



Install

npm install modbus-serial

try these options on npm install to build, if you have problems to install

--unsafe-perm --build-from-source

What can I do with this module ?

This class makes it fun and easy to communicate with electronic devices such as irrigation controllers, protocol droids and robots. It talks with devices that use a serial line (e.g. RS485, RS232). Many industrial electronic devices implement modbus. Arduino can also talk modbus and you can control your projects and robots using modbus.

Arduino libraries for modbus slave:

Arduino sketch for irrigation timer with modbus support:

Node Modbus-WebSocket bridge:

Compatibility

Version of NodeJS:

This module has not been tested on every single version of NodeJS. For best results you should stick to LTS versions, which are denoted by even major version numbers e.g. 4.x, 6.x, 8.x.

These classes are implemented:
Class Function
FC1 "Read Coil Status" readCoils(coil, len)
FC2 "Read Input Status" readDiscreteInputs(addr, arg)
FC3 "Read Holding Registers" readHoldingRegisters(addr, len)
FC4 "Read Input Registers" readInputRegisters(addr, len)
FC5 "Force Single Coil" writeCoil(coil, binary) //NOT setCoil
FC6 "Preset Single Register" writeRegister(addr, value)
FC15 "Force Multiple Coil" writeCoils(addr, valueAry)
FC16 "Preset Multiple Registers" writeRegisters(addr, valueAry)
FC43/14 "Read Device Identification" (supported ports: TCP, RTU) readDeviceIdentification(id, obj)
Client Serial:
  • modbus-RTU (SerialPort): Over serial line [require node serialport].
  • modbus-RTU (RTUBufferedPort): Over buffered serial line [require node serialport].
  • modbus-ASCII (AsciiPort): Over serial line [require node serialport].
Client TCP:
  • modbus-TCP (TcpPort): Over TCP/IP line.
  • modbus-RTU (UdpPort): Over C701 server, commercial UDP to serial bridge.
  • modbus-RTU (TcpRTUBufferedPort): Over TCP/IP line, TCP/IP serial RTU buffered device.
  • modbus-RTU (TelnetPort): Over Telnet server, TCP/IP serial bridge.
Server
  • modbus-TCP (ServerTCP): Over TCP/IP line.

Examples

Read and Write
// create an empty modbus client
const ModbusRTU = require("modbus-serial");
const client = new ModbusRTU();

// open connection to a serial port
client.connectRTUBuffered("/dev/ttyUSB0", { baudRate: 9600 }, write);

function write() {
    client.setID(1);

    // write the values 0, 0xffff to registers starting at address 5
    // on device number 1.
    client.writeRegisters(5, [0 , 0xffff])
        .then(read);
}

function read() {
    // read the 2 registers starting at address 5
    // on device number 1.
    client.readHoldingRegisters(5, 2)
        .then(console.log);
}

Read on multiple slaves
const ModbusRTU = require("modbus-serial");
// create an empty modbus client
const client = new ModbusRTU();
// open connection to a serial port
client.connectRTUBuffered("/dev/ttyS0", { baudRate: 9600 });
// set timeout, if slave did not reply back
client.setTimeout(500);

// list of meter's id
const metersIdList = [10, 11, 12, 13, 14];

const getMetersValue = async (meters) => {
    try{
        // get value of all meters
        for(let meter of meters) {
            // output value to console
            console.log(await getMeterValue(meter));
            // wait 100ms before get another device
            await sleep(100);
	}
    } catch(e){
        // if error, handle them here (it should not)
        console.log(e)
    } finally {
        // after get all data from slave, repeat it again
        setImmediate(() => {
            getMetersValue(metersIdList);
        })
    }
}

const getMeterValue = async (id) => {
    try {
        // set ID of slave
        await client.setID(id);
        // read the 1 registers starting at address 0 (first register)
        let val =  await client.readInputRegisters(0, 1);
        // return the value
        return val.data[0];
    } catch(e){
        // if error return -1
        return -1
    }
}

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));


// start get value
getMetersValue(metersIdList);

Logger Serial
// create an empty modbus client
const ModbusRTU = require("modbus-serial");
const client = new ModbusRTU();

// open connection to a serial port
client.connectRTUBuffered("/dev/ttyUSB0", { baudRate: 9600 });
client.setID(1);

// read the values of 10 registers starting at address 0
// on device number 1. and log the values to the console.
setInterval(function() {
    client.readHoldingRegisters(0, 10, function(err, data) {
        console.log(data.data);
    });
}, 1000);

Logger TCP
// create an empty modbus client
const ModbusRTU = require("modbus-serial");
const client = new ModbusRTU();

// open connection to a tcp line
client.connectTCP("127.0.0.1", { port: 8502 });
client.setID(1);

// read the values of 10 registers starting at address 0
// on device number 1. and log the values to the console.
setInterval(function() {
    client.readHoldingRegisters(0, 10, function(err, data) {
        console.log(data.data);
    });
}, 1000);

Logger UDP
// create an empty modbus client
const ModbusRTU = require("modbus-serial");
const client = new ModbusRTU();

// open connection to a udp line
client.connectUDP("127.0.0.1", { port: 8502 });
client.setID(1);

// read the values of 10 registers starting at address 0
// on device number 1. and log the values to the console.
setInterval(function() {
    client.readHoldingRegisters(0, 10, function(err, data) {
        console.log(data.data);
    });
}, 1000);

ModbusTCP Server
// create an empty modbus client
const ModbusRTU = require("modbus-serial");
const vector = {
    getInputRegister: function(addr, unitID) {
        // Synchronous handling
        return addr;
    },
    getHoldingRegister: function(addr, unitID, callback) {
        // Asynchronous handling (with callback)
        setTimeout(function() {
            // callback = function(err, value)
            callback(null, addr + 8000);
        }, 10);
    },
    getCoil: function(addr, unitID) {
        // Asynchronous handling (with Promises, async/await supported)
        return new Promise(function(resolve) {
            setTimeout(function() {
                resolve((addr % 2) === 0);
            }, 10);
        });
    },
    setRegister: function(addr, value, unitID) {
        // Asynchronous handling supported also here
        console.log("set register", addr, value, unitID);
        return;
    },
    setCoil: function(addr, value, unitID) {
        // Asynchronous handling supported also here
        console.log("set coil", addr, value, unitID);
        return;
    },
    readDeviceIdentification: function(addr) {
        return {
            0x00: "MyVendorName",
            0x01: "MyProductCode",
            0x02: "MyMajorMinorRevision",
            0x05: "MyModelName",
            0x97: "MyExtendedObject1",
            0xAB: "MyExtendedObject2"
        };
    }
};

// set the server to answer for modbus requests
console.log("ModbusTCP listening on modbus://0.0.0.0:8502");
const serverTCP = new ModbusRTU.ServerTCP(vector, { host: "0.0.0.0", port: 8502, debug: true, unitID: 1 });

serverTCP.on("socketError", function(err){
    // Handle socket error if needed, can be ignored
    console.error(err);
});

Read and Write Modbus ASCII
// create an empty modbus client
const Modbus = require("modbus-serial");
const client = new Modbus();

// open connection to a serial port
client.connectAsciiSerial(
    "/dev/ttyUSB0", 
    {
        baudRate: 9600,
        startOfSlaveFrameChar: 0x3A  // optional: slave frame delimiter
    }, 
    write);

function write() {
    client.setID(1);

    // write the values 0, 0xffff to registers starting at address 5
    // on device number 1.
    client.writeRegisters(5, [0 , 0xffff])
        .then(read);
}

function read() {
    // read the 2 registers starting at address 5
    // on device number 1.
    client.readHoldingRegisters(5, 2)
        .then(console.log);
}

to get more see Examples

Serial connection

node-modbus-serial use node-serialport for serial communication, for serial port options settings it passes to serial port the openOptions object, default serial port settings are 9600,8,n,1.

client.connectRTUBuffered("/dev/ttyUSB0", { baudRate: 9600, parity: 'even' });

More Repositories

1

ArduinoModbusSlave

Modbus slave library for Arduino
C++
195
star
2

tree-search-language

Tree Search Language (TSL) is a wonderful search langauge.
Go
57
star
3

node-modbus-ws

NodeJS Modbus to WebSocket bridge
JavaScript
50
star
4

kubectl-sql

kubectl-sql is a kubectl plugin that use SQL like language to query the Kubernetes cluster manager
Go
50
star
5

observer

Golang event emitter and listener with builtin file watcher package.
Go
34
star
6

ArduinoModbusSlaveTCP

Modbus slave library for ESP8266-Arduino
C++
19
star
7

gokitty

Small, fast and cute URL router and dispatcher for golang.
Go
7
star
8

libhdate-js

A pure javascript (partial) implementation of libhdate
JavaScript
5
star
9

hebocr-testing

Hebrew OCR (optical character recognition) library, testing branch.
Python
5
star
10

hebocr

Hebrew OCR (optical character recognition) library.
C
5
star
11

ttkyaml

Class for constructing ttk user interfaces dynamically from yaml file
Python
4
star
12

django-mro

Django application for MRO (Maintenance, Repair, and Operations)
Python
4
star
13

okd-installer-hacks

hacks to install okd using installer
Shell
4
star
14

arduino-irrigation-timer

Arduino irrigation timer (24 hour) with Modbus serial communication.
Arduino
3
star
15

libhdate-old

libhdate fork
Shell
3
star
16

libhdate-glib

LibHdate Gobject bindings
Vala
3
star
17

miq-scripts

Shell
3
star
18

node-modbus-cli

A Modbus client writen in JavaScrip
JavaScript
3
star
19

phone-holder-scad

Cell phone holder design using OpenSCAD
OpenSCAD
2
star
20

libhdate-php

A pure php (partial) implementation of libhdate
PHP
2
star
21

cagraph

A PyGTK Cairo chart widget
Python
2
star
22

crdtoapi

Use kubernetes CRD definitions to create OpenAPI schema file
JavaScript
1
star
23

hawkular-client-cli

Hawkular client command line
Python
1
star
24

simple-odspy

Simple pure python spreadsheet class
Python
1
star
25

pi-oven-scripts

Raspberry PI scripts used for home oven control.
Python
1
star
26

pi-gate-scripts

Raspberry PI scripts used for home automation gate control.
Python
1
star
27

snapchat-killer

Taking opencv haar classifier to a test drive
Python
1
star