使用Modbus4j+seroUtils读取风速风向仪数据,现有设备IP,端口号,从机地址,寄存器读取开始地址,读取的寄存器数量。没有上述jar包可以自行搜索,网上资源挺多
getValueByTCP 是采用Modbus TCP/IP协议的,getValueByRtu 采用Modbus RTU Over TCP/IP
import com.intelligt.modbus.jlibmodbus.Modbus;
import com.intelligt.modbus.jlibmodbus.master.ModbusMaster;
import com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory;
import com.intelligt.modbus.jlibmodbus.tcp.TcpParameters;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
@Component
public class ModbusUtil {
private static ModbusFactory modbusFactory;
static {
if (modbusFactory == null) {
modbusFactory = new ModbusFactory();
}
}
public Map<Integer, Integer> getValueByTCP(String ip, int port, int slaveId, int offset, int quantity) {
Map<Integer, Integer> resultMap = new HashMap<>(quantity);
try {
TcpParameters tcpParameters = new TcpParameters();
InetAddress address = InetAddress.getByName(ip);
tcpParameters.setHost(address);
tcpParameters.setKeepAlive(true);
tcpParameters.setPort(port);
ModbusMaster master = ModbusMasterFactory.createModbusMasterTCP(tcpParameters);
Modbus.setAutoIncrementTransactionId(true);
try {
if (!master.isConnected()) {
master.connect();
}
int[] registerValues = master.readInputRegisters(slaveId, offset, quantity);
for (int value : registerValues) {
resultMap.put(offset++, value);
}
} catch (Exception e) {
throw new RuntimeException("建立连接失败,环境监测设备不在线");
} finally {
master.disconnect();
}
} catch (Exception e) {
throw new RuntimeException("初始化连接失败,环境监测设备不在线");
}
return resultMap;
}
public static short[] getValueByRtu(String ip, int port, int slaveId, int offset, int quantity){
short[] result = new short[2];
IpParameters params = new IpParameters();
params.setHost(ip);
params.setPort(port);
params.setEncapsulated(true);
com.serotonin.modbus4j.ModbusMaster master = modbusFactory.createTcpMaster(params, true);
try {
master.setTimeout(1000);
master.setRetries(3);
master.init();
try {
ReadHoldingRegistersRequest request = null;
request = new ReadHoldingRegistersRequest(slaveId, offset, quantity);
ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master.send(request);
if (response.isException())
System.out.println("读取风速设备数据失败," + response.getExceptionMessage());
else
result = response.getShortData();
} catch (ModbusTransportException e) {
throw new RuntimeException("读取风速设备数据失败");
}
} catch (ModbusInitException e) {
throw new RuntimeException("建立风速设备连接失败");
}
return result;
}
}
相关文章:Java实现ModbusTCP通信
|