写一个MODBUS-TCP的java示例代码
时间: 2024-02-22 19:58:22 浏览: 77
好的,以下是一个简单的MODBUS-TCP的java示例代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class ModbusTCPExample {
// Modbus TCP通信参数
private static final int SERVER_PORT = 502;
private static final InetAddress SERVER_ADDRESS = InetAddress.getByName("127.0.0.1");
// Modbus TCP指令
private static final byte[] READ_COILS = { 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x01, 0x01, 0x00, 0x00, 0x00, 0x08 };
private static final byte[] READ_INPUTS = { 0x00, 0x02, 0x00, 0x00, 0x00, 0x06, 0x01, 0x02, 0x00, 0x00, 0x00, 0x08 };
private static final byte[] READ_HOLDING_REGISTERS = { 0x00, 0x03, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x00, 0x00, 0x08 };
private static final byte[] READ_INPUT_REGISTERS = { 0x00, 0x04, 0x00, 0x00, 0x00, 0x06, 0x01, 0x04, 0x00, 0x00, 0x00, 0x08 };
private static final byte[] WRITE_SINGLE_COIL = { 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x01, 0x05, 0x00, (byte) 0xFF, 0x00, 0x00 };
private static final byte[] WRITE_SINGLE_REGISTER = { 0x00, 0x06, 0x00, 0x00, 0x00, 0x06, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00 };
public static void main(String[] args) {
// 建立Socket连接
try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT)) {
// 获取输入输出流
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// 读取线圈状态
byte[] response = ModbusTCPUtils.sendRequest(READ_COILS, in, out);
boolean[] coils = ModbusTCPUtils.parseCoils(response, READ_COILS.length);
// 读取输入状态
response = ModbusTCPUtils.sendRequest(READ_INPUTS, in, out);
boolean[] inputs = ModbusTCPUtils.parseInputs(response, READ_INPUTS.length);
// 读取保持寄存器
response = ModbusTCPUtils.sendRequest(READ_HOLDING_REGISTERS, in, out);
int[] holdingRegisters = ModbusTCPUtils.parseRegisters(response, READ_HOLDING_REGISTERS.length / 2);
// 读取输入寄存器
response = ModbusTCPUtils.sendRequest(READ_INPUT_REGISTERS, in, out);
int[] inputRegisters = ModbusTCPUtils.parseRegisters(response, READ_INPUT_REGISTERS.length / 2);
// 写入单个线圈
response = ModbusTCPUtils.sendRequest(WRITE_SINGLE_COIL, in, out);
// 写入单个保持寄存器
response = ModbusTCPUtils.sendRequest(WRITE_SINGLE_REGISTER, in, out);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个示例代码中,我们使用了ModbusTCPUtils类来发送请求和解析响应。SEND_COILS、SEND_INPUTS、SEND_HOLDING_REGISTERS和SEND_INPUT_REGISTERS分别代表读取线圈、输入状态、保持寄存器和输入寄存器的指令。WRITE_SINGLE_COIL和WRITE_SINGLE_REGISTER分别代表写入单个线圈和保持寄存器的指令。
阅读全文