要在Java中使用Modbus4J庫實現Modbus TCP通信,首先需要在項目中引入Modbus4J庫。可以通過Maven或Gradle等構建工具來添加依賴。
接下來,可以按照以下步驟來使用Modbus4J庫實現Modbus TCP通信:
ModbusFactory modbusFactory = new ModbusFactory();
ModbusMaster modbusMaster = modbusFactory.createTcpMaster(
new InetSocketAddress("192.168.1.1", 502)
);
modbusMaster.init();
ReadInputRegistersRequest request = new ReadInputRegistersRequest(0, 10);
ReadInputRegistersResponse response = (ReadInputRegistersResponse) modbusMaster.send(request);
if (response.isException()) {
System.out.println("Exception response: " + response.getExceptionMessage());
} else {
int[] values = response.getShortData();
for (int value : values) {
System.out.println("Value: " + value);
}
}
WriteSingleRegisterRequest request = new WriteSingleRegisterRequest(0, 1234);
WriteSingleRegisterResponse response = (WriteSingleRegisterResponse) modbusMaster.send(request);
if (response.isException()) {
System.out.println("Exception response: " + response.getExceptionMessage());
} else {
System.out.println("Write successful");
}
modbusMaster.destroy();
以上是使用Modbus4J庫實現Modbus TCP通信的簡單示例。根據實際需求,可以根據Modbus協議的要求進行更多的讀寫操作。