import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.ModbusCoupler;
import net.wimpi.modbus.io.ModbusTCPListener;
import net.wimpi.modbus.procimg.*;
import net.wimpi.modbus.util.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ModbusTCPServerExample {
public static void main(String[] args) {
try {
// 创建一个实现了ModbusSlave接口的SimpleProcessImage
SimpleProcessImage spi = new SimpleProcessImage();
spi.addDigitalOut(new SimpleDigitalOut(true));
spi.addDigitalIn(new SimpleDigitalIn(false));
spi.addInputRegister(new SimpleInputRegister(45));
spi.addRegister(new SimpleRegister(251));
ModbusCoupler.getReference().setProcessImage(spi);
ModbusCoupler.getReference().setMaster(false);
ModbusCoupler.getReference().setUnitID(1);
// 获取本地IP地址
InetAddress addr = InetAddress.getLocalHost();
String ipAddress = addr.getHostAddress();
// 创建ModbusTCPListener对象,监听指定端口
ModbusTCPListener listener = new ModbusTCPListener(1);
listener.setAddress(addr);
listener.open();
// 打印服务器信息
System.out.println("Modbus TCP server running at " + ipAddress + ":" + Modbus.DEFAULT_PORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This example code creates a simple Modbus TCP server that uses a SimpleProcessImage that implements the Modbus Slave interface to store data. SimpleProcessImage includes a digital output, a digital input, an input register, and a hold register. In the main function, first create a SimpleProcessImage, and then set it as the process image for Modbus Couple. Then, set the master/slave mode of the Modbus Coupler to slave mode and set the unit ID to 1. Next, obtain the local IP address and use the Modbus TCP Listener object to listen on the default port (502). Finally, print the server information.
Leave a Reply