J2Mod是一個Java編寫的Modbus通信庫,可以用于實現Modbus RTU服務器。以下是一個簡單的示例,演示如何使用J2Mod庫創建一個Modbus RTU服務器:
- 添加J2Mod庫依賴項: 首先,確保在項目中包含J2Mod庫。你可以將J2Mod庫添加到項目中,方法取決于你使用的構建工具(比如Maven或Gradle)。
如果使用Maven,可以在pom.xml
文件中添加以下依賴項:
<dependency><groupId>com.ghgande.j2mod</groupId><artifactId>j2mod</artifactId><version>3.1.3</version> <!-- 使用最新版本 -->
</dependency>
如果使用Gradle,可以在build.gradle
文件中添加以下依賴項:
implementation 'com.ghgande.j2mod:j2mod:3.1.3' // 使用最新版本
創建Modbus RTU服務器:
下面是一個簡單的Modbus RTU服務器示例,監聽在COM3串口上,地址為1:
import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.procimg.SimpleDigitalIn;
import com.ghgande.j2mod.modbus.procimg.SimpleDigitalOut;
import com.ghgande.j2mod.modbus.procimg.SimpleProcessImage;
import com.ghgande.j2mod.modbus.serial.SerialParameters;
import com.ghgande.j2mod.modbus.serial.SerialPort;
import com.ghgande.j2mod.modbus.serial.SerialUtils;
import com.ghgande.j2mod.modbus.serial.SerialPortException;
import com.ghgande.j2mod.modbus.serial.SerialPortFactory;
import com.ghgande.j2mod.modbus.ModbusCoupler;public class ModbusRTUServerExample {public static void main(String[] args) {try {// Create a process image with a single coil at address 0SimpleProcessImage spi = new SimpleProcessImage();spi.addDigitalOut(new SimpleDigitalOut(true)); // Coil at address 0spi.addDigitalIn(new SimpleDigitalIn(false)); // Input at address 1// Set up the serial parametersSerialParameters serialParameters = new SerialParameters();serialParameters.setCommPortId("COM3");serialParameters.setBaudRate(SerialPort.BAUD_9600);serialParameters.setDatabits(8);serialParameters.setParity(SerialPort.PARITY_NONE);serialParameters.setStopbits(1);serialParameters.setEncoding(Modbus.SERIAL_ENCODING_RTU);serialParameters.setEcho(false);// Create the Modbus RTU serial portSerialPort serialPort = SerialPortFactory.create(serialParameters);serialPort.open();// Set the serial port for ModbusCouplerModbusCoupler.getReference().setMaster(false);ModbusCoupler.getReference().setUnitID(1);ModbusCoupler.getReference().setProcessImage(spi);ModbusCoupler.getReference().setSerialPort(serialPort);// Start the Modbus RTU serverModbusCoupler.getReference().start();System.out.println("Modbus RTU server is running...");// Wait forever (you can add your own logic here)while (true) {Thread.sleep(1000);}} catch (Exception e) {e.printStackTrace();}}
}
- 請注意,此示例中使用的串口是"COM3",你可能需要根據你的系統配置更改串口。確保你有足夠的權限訪問該串口。