赞
踩
J2Mod是一个Java编写的Modbus通信库,可以用于实现Modbus RTU服务器。以下是一个简单的示例,演示如何使用J2Mod库创建一个Modbus RTU服务器:
如果使用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 0
- SimpleProcessImage spi = new SimpleProcessImage();
- spi.addDigitalOut(new SimpleDigitalOut(true)); // Coil at address 0
- spi.addDigitalIn(new SimpleDigitalIn(false)); // Input at address 1
-
- // Set up the serial parameters
- SerialParameters 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 port
- SerialPort serialPort = SerialPortFactory.create(serialParameters);
- serialPort.open();
-
- // Set the serial port for ModbusCoupler
- ModbusCoupler.getReference().setMaster(false);
- ModbusCoupler.getReference().setUnitID(1);
- ModbusCoupler.getReference().setProcessImage(spi);
- ModbusCoupler.getReference().setSerialPort(serialPort);
-
- // Start the Modbus RTU server
- ModbusCoupler.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();
- }
- }
- }
j2mod完整案例开源项目https://gitee.com/mzmedia/mz-media
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/225901
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。