-
Notifications
You must be signed in to change notification settings - Fork 111
Using j2mod to read from a Slave
The methods described in this page use the TCP master (ModbusTCPMaster
) but they are exactly the same for UDP and Serial connections. Simple replace the ModbusTCPMaster
with either ModbusUDPMaster
or ModbusSerialMaster
and supply the specific connection details in their respective constructors.
There are two methods for reading data from a Modbus Slave;
- Simple - use the Facade package methods to hide all the moving parts and only supports the major Function Codes
- Less Simple - provide all the components as used by the Simple approach but gives you greater control over the process, connection and the more exotic Function Codes.
This approach takes advantage of the Facade package classes to encapsulate the down and dirty detail of creating a connection and a transaction for each request. It is method thread safe but calls to connect/disconnect cannot be interleaved.
The usage pattern is;
- Create a
ModbusTCPMaster
instance - Connect to the Slave via the
connect
method - Call any or all of the
readXXXX
methods - Disconnect via the
disconnect()
method
ModbusTCPMaster master;
try {
// master = new ModbusTCPMaster(<address>); // Uses port 502 and a timeout of 3000ms
// master = new ModbusTCPMaster(<address>, <port>); // Uses a timeout of 3000ms
master = new ModbusTCPMaster(<address>, <port>, <timeout>);
master.connect();
}
catch (Exception e) {
logger.error("Cannot connect to slave - %s", e.getMessage());
}
<address>
Address of the slave - can be either an IP or hostname
<port>
The port number to connect to on the Slave (default is 502)
<timeout>
The socket timeout in milliseconds for receive (deafult 3000ms)
// master.readCoils(<coil ref>, <count>); // Uses a UNIT ID of 1
master.readCoils(<unit id>, <coil ref>, <count>);
// master.readInputDiscretes(<discrete ref>, <count>); // Uses a UNIT ID of 1
master.readInputDiscretes(<unit id>, <discrete ref>, <count>);
// master.readInputInputRegisters(<discrete ref>, <count>); // Uses a UNIT ID of 1
master.readInputInputRegisters(<unit id>, <discrete ref>, <count>);
// master.readMultipleRegisters(<discrete ref>, <count>); // Uses a UNIT ID of 1
master.readMultipleRegisters(<unit id>, <discrete ref>, <count>);
if (master != null) {
master.disconnect();
}
This method isn't covered here but is included in the test cases and various standalone classes in the Test package. Checkout the code or explore it here