Cloud-Automation / node-modbus

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

Add Modbus UDP #249

Closed Ekristoffe closed 4 years ago

Ekristoffe commented 4 years ago

Hello, in some case we need to use Modbus over UDP connection (it work exactly like the Modbus TCP but using UDP. Is it possible to also have a Modbus UDP function ? Thanks

alexbuczynsky commented 4 years ago

I did some research and found that nodejs does already provide a generic udp socket see dgram docs

The issue is that the UDP socket is missing the following methods that we use: https://github.com/Cloud-Automation/node-modbus/blob/1bd34c125d59413f59bb7a38f7a5c8f5c695aa10/src/tcp-client-request-handler.ts#L40-L41

https://github.com/Cloud-Automation/node-modbus/blob/1bd34c125d59413f59bb7a38f7a5c8f5c695aa10/src/modbus-client.ts#L70

In order to make the UDP socket work, we would need to either create a wrapper around the UDP socket to act as an adapter that implements the methods of the tcp socket.

The other option is our library would need a new request handler specifically designed for UDP clients.

Ekristoffe commented 4 years ago

Hello, If I understand right, In the net.Socket you use the following event:

Event: 'connect'
Added in: v0.1.90
Emitted when a socket connection is successfully established. 
See net.createConnection().
Event: 'close'
Added in: v0.1.90
hadError <boolean> true if the socket had a transmission error.
Emitted once the socket is fully closed. 
The argument hadError is a boolean which says if the socket was 
closed due to a transmission error.
Event: 'data'
Added in: v0.1.90
<Buffer> | <string>
Emitted when data is received. 
The argument data will be a Buffer or String. Encoding of data is 
set by socket.setEncoding().

The data will be lost if there is no listener when a Socket emits 
a 'data' event.

And in the dgram.Socket i think we can use:

Event: 'connect'
Added in: v12.0.0
The 'connect' event is emitted after a socket is associated to 
a remote address as a result of a successful connect() call.
Event: 'close'
Added in: v0.1.99
The 'close' event is emitted after a socket is closed with close(). 
Once triggered, no new 'message' events will be emitted on this socket.

but instead of 'data' we can use 'message' in UDP:

Event: 'message'
Added in: v0.1.99
The 'message' event is emitted when a new datagram is available on a socket. 
The event handler function is passed two arguments: msg and rinfo.

msg <Buffer> The message.
rinfo <Object> Remote address information.

address <string> The sender address.
family <string> The address family ('IPv4' or 'IPv6').
port <number> The sender port.
size <number> The message size.

I don't know really the extend of modifications needed for this ... and I am totally a newbie in JavaScript (sorry).

Ekristoffe commented 4 years ago

hello just so say i haven't forgot it and i will see what I can do for this.