Skip to content

Using j2mod to read from a Slave

Steve O'Hara edited this page Apr 29, 2018 · 2 revisions

The methods described in this page use the TCP master (ModbusTCPMaster) but they are exactly the same for UDP and Serial connections. 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 but 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.

Simple

This approach takes advantage of the Facade package classes to encapsulate the down and dirty detail of creating a connection and 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 connect
  • Call any or all of the readXXXX methods
  • Disconnect from the slave disconnect()

Connect

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)

Read Coil

// master.readCoils(<coil ref>, <count>);           // Uses a UNIT ID of 1
master.readCoils(<unit id>, <coil ref>, <count>);

Read Discretes

// master.readInputDiscretes(<discrete ref>, <count>);  // Uses a UNIT ID of 1
master.readInputDiscretes(<unit id>, <discrete ref>, <count>);

Read Input Registers

// master.readInputInputRegisters(<discrete ref>, <count>); // Uses a UNIT ID of 1
master.readInputInputRegisters(<unit id>, <discrete ref>, <count>);

Read Holding Registers

// master.readMultipleRegisters(<discrete ref>, <count>);  // Uses a UNIT ID of 1
master.readMultipleRegisters(<unit id>, <discrete ref>, <count>);

Disconnect

if (master != null) {
    master.disconnect();
}

Less Simple

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