- 连接modbus
其中的Modbus.setAutoIncrementTransacationId(true);是指设置自动事务递增的标志,确保每个请求事务标识不同,避免冲突和混淆。
2.读取寄存器地址的数据
@Override
public Map<String, Object> readData() {
String ipAddress = "127.0.0.1";
ModbusMaster master = null;
try {
master = connectModbus.getMaster(ipAddress);
//连接modbus
if (!master.isConnected()){
master.connect();
}
//读取modbus地址内容
int[] registers = master.readHoldingRegisters(1, 100, 2);
HashMap<String, Object> map = new HashMap<>();
map.put("V100",registers[0]);
map.put("V101",registers[1]);
return map;
} catch (UnknownHostException | ModbusIOException | ModbusProtocolException | ModbusNumberException e) {
e.printStackTrace();
HashMap<String, Object> map = new HashMap<>();
map.put("result",e.getMessage());
return map;
}finally {
try {
master.disconnect();
} catch (ModbusIOException e) {
e.printStackTrace();
}
}
}
3.写入寄存器地址数据
//写入
@Override
public void writeData() {
String ipAddress = "127.0.0.1";
ModbusMaster master = null;
try {
master = connectModbus.getMaster(ipAddress);
if (!master.isConnected()){
master.connect();
}
//写入单个地址
master.writeSingleRegister(1,10,15);
master.writeSingleRegister(1,11,58);
//写入多个地址
int array[] = StringToAscll("B85479635");
master.writeMultipleRegisters(1,20,array);
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (master != null){
master.disconnect();
}
} catch (ModbusIOException e) {
e.printStackTrace();
}
}
}
//其中num可能是字符所以要转自动换成ascll码
private int[] StringToAscll(String num) {
int[] array = new int[num.length()];
for (int i = 0; i < num.length(); i++) {
array[i] = num.charAt(i);
}
return array;
}