Cloud-Automation / node-modbus

Modbus TCP Client/Server implementation for Node.JS
467 stars 174 forks source link

Send custom response to client #273

Closed SmartMCBV closed 4 years ago

SmartMCBV commented 4 years ago

Hello,

I think I finally found agood NPM to achieve my goal. My node app should open a Modbus TCP/IP server and listen to clients requesting data. I succeed in setting up the server and connecting to it with a client remotely. Now the next thing I do is use the Read Holding Registers function to request multiple registers from the server by the client. I figured that the preReadHoldingRegisters event is showing me which address and how many registers a client requests. What I want to do is give him a response in this event, so a client can request for example register number 5 and 6 and give him the response 100 and 50. This values I want to get from my Cloud API later on, so I do not want to store data on the modbus server, just want to get it and put it into the response for a client requesting it.

I assume this is not hard, but I cannot find any docs showing how to.

Thank you, Roel.

stefanpoeter commented 4 years ago

Hey @SmartMCBV,

you cannot issue a custom response but you can alter the buffer at the requested address in the pre handler. The data from the buffer will then be send with the response. In the post handler you can rest the buffer values.

SmartMCBV commented 4 years ago

Thanks Stefan, That can work yes, is there any example of this, showing how to read some values to the buffer based on the register address? Thanks.

stefanpoeter commented 4 years ago

Unfortunately not. Look at the basic server example. There you find the buffer. The buffer offset is simply the modbus address in the read holding request times two.

SmartMCBV commented 4 years ago

Hi Stefan,

I think I found it, looks like this is the way:

server.on('preReadHoldingRegisters', (request, cb) => { server.holding.writeUInt16BE(0x0002, request._body._start) // Writing 2 to register number as requested. })

Thanks!

stefanpoeter commented 4 years ago

This is the way :-)