Cloud-Automation / node-modbus

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

Feature idea: also allow callbacks for coils/discrete/holding/input server options #206

Closed martijnthe closed 6 years ago

martijnthe commented 6 years ago

@stefanpoeter: in my use case I'd like to provide the value(s) for coils/discrete/holding/input the moment the request is made.

I'm thinking of enabling this by extending the options object that gets passed into the ModbusServer constructor to (TypeScript notation):

interface ModbusServerOptions {
  coils?: Buffer | () => Buffer;
  discrete?: Buffer | () => Buffer;
  holding?: Buffer | () => Buffer;
  input?: Buffer | () => Buffer;
}

Thoughts?

martijnthe commented 6 years ago

One thing I completely missed in my proposal is that this does not really work for dealing with writes.

I also noticed there's code that emits an event on the server in case coils/discrete/holding/input does not exist. Unfortunately, when using that, the listener has to build the response data himself (duplicating a lot of code from src/modbus-server-response-handler.js).

How about adding (optional) high-level callbacks to the ModbusServer options for each of the Modbus "functions"? This would supercede the misc. events that are currently emitted that I mentioned before.

Thoughts?

stefanpoeter commented 6 years ago

You can do what you want by manipulating the memory that is requested with the pre/post events (for example preReadHoldingRegisters). This will work because the server is single threaded. The missing events for coils/discrete/inputs are added easily.

To be a bit more specific, when the server receives a readHoldingRegisters it emits a preReadHoldingRegisters event then reads the data from the holding buffer and then emits a postReadHoldingRegisters event. This way you can archieve what you want.

If this solutions does not satisfy you then write your own request and responseHandler and pass them into the modbus server.