工厂中通讯模块大多数都用modbus或者opcua与plc建立通讯,实现工厂设备的控制及数据采集等
现面展示的 modbus 代码实现需要引入的jar文件已将上面的数据封装解析,避免人为操作麻烦
点击获取 依赖包文件 提取码 7gnz
点击获取 modbus测试工具 提取码 nm7j
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.msg.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.Arrays;
public class ModbusMasterWrapper {
private static final Logger log = LoggerFactory.getLogger(ModbusMasterWrapper.class);
private String hostIp;
private int hostPort;
private int slaveId;
private ModbusMaster modbusMaster;
private boolean connected;
public ModbusMasterWrapper(String hostIp, int port, int slaveId) {
this.hostIp = hostIp;
this.hostPort = port;
this.slaveId = slaveId;
log.info("hostIp: {}, port: {}, slaveId: {}", hostIp, port, slaveId);
}
public boolean connect() {
disconnect();
try {
IpParameters ipParameters = new IpParameters();
ipParameters.setHost(hostIp);
ipParameters.setPort(hostPort);
log.info("connect: ip: {}, port: {}", this.hostIp, this.hostPort);
modbusMaster = new ModbusFactory().createTcpMaster(ipParameters, true);
modbusMaster.setTimeout(10000);
modbusMaster.init();
connected = true;
} catch (ModbusInitException ex) {
log.error("connect error, try to disconnect...", ex);
disconnect();
}
return isConnected();
}
private void disconnect() {
if (modbusMaster != null) {
modbusMaster.destroy();
}
connected = false;
log.info("disconnect");
}
private boolean isConnected() {
return connected;
}
/**
* 读取单个线圈(01功能码)
* @param startOffset 读取地址
*/
public Boolean readCoils(int startOffset) throws ModbusTransportException {
ReadCoilsRequest request = new ReadCoilsRequest(slaveId,startOffset,1);
ReadCoilsResponse response = (ReadCoilsResponse) modbusMaster.send(request);
if (response!= null && response.isException()) {
throw new ModbusTransportException(response.getExceptionMessage());
} else if(response!= null){
return response.getBooleanData()[0];
}
connected = false;
return null;
}
/**
* 写入单个地址
* @param startOffset 写入地址
* @param value 写入值
*/
public void writeCoils(int startOffset,boolean value) throws ModbusTransportException {
WriteCoilRequest request = new WriteCoilRequest(slaveId,startOffset,value);
WriteCoilResponse response = (WriteCoilResponse) modbusMaster.send(request);
if (response!= null && response.isException()) {
throw new ModbusTransportException(response.getExceptionMessage());
}
}
/**
* 写多个线圈(01功能码)
* @param startOffset 写入开始地址
* @param value 写入值集合
* @throws ModbusTransportException
*/
public void writeCoilsMultiple(int startOffset,boolean[] value) throws ModbusTransportException {
WriteCoilsRequest request = new WriteCoilsRequest(slaveId,startOffset,value);
WriteCoilsResponse response = (WriteCoilsResponse) modbusMaster.send(request);
if (response!= null && response.isException()) {
throw new ModbusTransportException(response.getExceptionMessage());
}
}
/**
* 读取单个离散线圈(02功能码)
* @param startOffset 读取地址
*/
public Boolean readDiscrete(int startOffset) throws ModbusTransportException {
ReadDiscreteInputsRequest request = new ReadDiscreteInputsRequest(slaveId,startOffset,1);
ReadDiscreteInputsResponse response = (ReadDiscreteInputsResponse) modbusMaster.send(request);
if (response!= null && response.isException()) {
throw new ModbusTransportException(response.getExceptionMessage());
} else if(response!= null){
return response.getBooleanData()[0];
}
connected = false;
return null;
}
/**
* 读取单个保持寄存器(03功能码)
* @param startOffset 读取地址
*/
public Short readHoldingRegisterValue(int startOffset) throws ModbusTransportException {
ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(slaveId, startOffset, 1);
log.info("Reading Holding Register, startAddress: {}", startOffset);
ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse)modbusMaster.send(request);
if (response != null && response.isException()) {
log.error("Modbus execution failed: \nslaveId: {}, startAddress: {}", slaveId, startOffset);
return null;
} else if (response != null && response.getShortData().length > 0) {
return response.getShortData()[0];
}
connected = false;
return null;
}
public Integer readHoldingRegisterIntValue(int startOffset) throws ModbusTransportException {
ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(slaveId, startOffset, 2);
ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse)modbusMaster.send(request);
if (response != null && response.isException()) {
return null;
} else if (response != null && response.getData().length > 0) {
byte[] bytes = response.getData();
return ByteBuffer.wrap(bytes).getInt();
}
connected = false;
return null;
}
/**
* 读取多个保持寄存器(03功能码)
* @param startOffset 开始读取位置
* @param numberOfRegisters 读取个数
*/
public short[] readHoldingRegisterValues(int startOffset, int numberOfRegisters) throws ModbusTransportException {
ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(slaveId, startOffset, numberOfRegisters);
log.info("Reading Holding Registers, startAddress: {}, len: {}", startOffset, numberOfRegisters);
ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse)modbusMaster.send(request);
if (response != null && response.isException()) {
log.error("Modbus execution failed: \nslaveId: {}, startAddress: {}, len: {}", slaveId, startOffset, numberOfRegisters);
return null;
} else if (response != null) {
return response.getShortData();
}
connected = false;
return null;
}
/**
* 写入保持寄存器多个值(03功能码)
* @param startOffset 写入开始地址
* @param values 写入多个数据集合
*/
public void writeRegisterValues(int startOffset, short[] values) throws ModbusTransportException {
WriteRegistersRequest request = new WriteRegistersRequest(slaveId, startOffset, values);
log.info(String.format("WRITE Holding Register, startOffset: %d, values: %s",
startOffset, Arrays.toString(values)));
WriteRegistersResponse response = (WriteRegistersResponse) modbusMaster.send(request);
if (response!= null && response.isException()) {
throw new ModbusTransportException(response.getExceptionMessage());
}
}
/**
* 写入保持寄存器(03功能码)
* @param startOffset 写入地址
* @param value 写入值
*/
public void writeRegisterValue(int startOffset, short value) throws ModbusTransportException {
WriteRegistersRequest request = new WriteRegistersRequest(slaveId, startOffset, new short[]{value});
log.info(String.format("Writing Holding Register, startAddress: %d, value: %d", startOffset, value));
WriteRegistersResponse response = (WriteRegistersResponse) modbusMaster.send(request);
if (response!= null && response.isException()) {
throw new ModbusTransportException(response.getExceptionMessage());
}
}
/**
* 读取输入寄存器(04功能码)
* @param startOffset 读取地址
*/
public Short readInput(int startOffset) throws ModbusTransportException {
ReadInputRegistersRequest request = new ReadInputRegistersRequest(slaveId,startOffset,1);
ReadInputRegistersResponse response = (ReadInputRegistersResponse) modbusMaster.send(request);
if (response!= null && response.isException()) {
throw new ModbusTransportException(response.getExceptionMessage());
} else if(response!= null){
return response.getShortData()[0];
}
connected = false;
return null;
}
}