node.jsnpmmodbus

Nodejs - How to act as modbus rtu server


I'm trying to set up a listener that accepts modbus RTU polls.

I have found a lot of modbus related npm library but they are all related to polling from other modbus slave, or act as modbus TCP server. I need to simulate the modbus slave, not the poller (act as modbus RTU server)

Edit: I found this library https://github.com/Cloud-Automation/node-modbus

There is a modbus-rtu-server.js file in the source, so I have been trying to use this. However, I'm having trouble understand and use the library without documentation. Here's what I have tried:

const modbus = require('jsmodbus')
const SerialPort = require('serialport')
const options = {
    baudRate: 9600
}
const socket = new SerialPort("/dev/ttyUSB0", options)
const server = new modbus.server.RTU(socket)
server.on('connect', function (client) {
    console.log(client);
});

This is what I have so far, but the "connect" event never happened, what am I doing wrong?


Solution

  • The server is just waiting for a client to connect. For the connect event to happen you have to start a query from a client. That means you need to have a second serial port connected to your /dev/ttyUSB0 and initiate a Modbus query from it. For that you can use the same library or any other tool like modpoll or QModMaster.

    You also need to develop a little bit your server, because right now it does not have any registers defined, so it won't be much use.

    Look at the TCP examples, in particular the SimpleServer. As you can see there, you need to define the Modbus registers or coils on your server, something like:

    server.on('readCoils', function (request, response, send) {
    /* Implement your own */
    
    response.body.coils[0] = true
    response.body.coils[1] = false
    
    send(response)
    })