morkai / h5.modbus

Implementation of the MODBUS IP/ASCII/RTU master and slave over TCP/UDP/Serial for Node.js.
https://miracle.systems/p/h5.modbus
MIT License
28 stars 21 forks source link

Example for slave #17

Closed yarosdev closed 7 years ago

yarosdev commented 7 years ago

How to send request to the client?

I have following code:

listener.on('client', function(client){
    // how to send request?
});

const slave = new modbus.Slave({
    listener: listener,
    transport: transport,
    requestHandler: handleRequest
});

I'll be very thankful!

morkai commented 7 years ago

Option requestHandler must be specified and be a function(number unit, Request request, function(any) respond). For example:

function handleRequest(unit, request, respond)
{
  if (isValidRequest(unit, request))
  {
    respond(new Buffer([1, 2, 3, 4]));
  }
  else
  {
    respond(ExceptionCode.IllegalDataAddress);
  }
}

respond() takes a single argument that can be one of:

See examples\slave.js for a full example.

yarosdev commented 7 years ago

What about transactions if it is tcp/ip?

morkai commented 7 years ago

Use TcpListener and IpTransport.

yarosdev commented 7 years ago

That's clear I mean executing concurrent transactions.

morkai commented 7 years ago

The respond() callback is unique to each request. If you receive 10 requests, the requestHandler will be called 10 times, each with different request and respond.

yarosdev commented 7 years ago

Thank you a lot! And last one question. Am I correct? To send command to the client I should send it in the request handler by calling a respond function?

morkai commented 7 years ago

Yes, you must call respond() to send a response to a request.

yarosdev commented 7 years ago

So, is modbus.Slave for emulating modbus device?

morkai commented 7 years ago

Yes, modbus.Slave=server and modbus.Master=client.