Modbus TCP in Java
 {
try {
// Create a TCP connection
InetAddress address = InetAddress.getByName("192.168.1.1");
TCPMasterConnection connection = new TCPMasterConnection(address);
connection.setPort(502);
connection.connect();
// Create a Modbus request
ReadMultipleRegistersRequest request = new ReadMultipleRegistersRequest(1, 4);
// Create a Modbus transaction
ModbusTCPTransaction transaction = new ModbusTCPTransaction(connection);
transaction.setRequest(request);
// Execute the transaction
transaction.execute();
// Get the response
ReadMultipleRegistersResponse response = (ReadMultipleRegistersResponse) transaction.getResponse();
// Print the values of the registers
for (int i = 0; i < response.getWordCount(); i++) {
int value = response.getRegisterValue(i);
System.out.println("Register " + (i + 1) + ": " + value);
}
// Close the connection
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the above code, we first create a TCP connection to the Modbus TCP server using the server's IP address and port number. Then, we create a ReadMultipleRegistersRequest
object to specify the starting address and number of registers we want to read.
Next, we create a ModbusTCPTransaction
object and set the request. We then execute the transaction to send the request to the server and receive the response.
Finally, we retrieve the values of the registers from the response and print them.
Conclusion
In this article, we have explored how to implement Modbus TCP communication in Java using the jamod library. We have also provided a code example that demonstrates how to read the values of multiple registers from a Modbus TCP server.
Modbus TCP is widely used in industrial automation systems and being able to communicate with Modbus devices using Java can be beneficial for developing control and monitoring applications.
Remember to include the necessary error handling and security measures when implementing Modbus TCP communication in your projects.