汇川PLC(INOVANCE)数据采集
模拟工具
汇川PLC采用的MODBUS协议,该协议有主从机的概念,工具模拟的是从机。
pom文件
<dependency>
<groupId>com.infiniteautomation</groupId>
<artifactId>modbus4j</artifactId>
<version>3.0.3</version>
</dependency>
获取master
public static ModbusMaster getMaster(String host) {
if (!masters.containsKey(host)) {
try {
IpParameters params = new IpParameters();
params.setHost(host);
params.setPort(502);
ModbusMaster master = modbusFactory.createTcpMaster(params, true);// TCP 协议
master.init();
masters.put(host, master);
} catch (ModbusInitException ex) {
if (!ex.getMessage().equals("java.net.SocketTimeoutException: connect timed out")) {
ex.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return masters.get(host);
}
读数据
//ModbusMaster
ModbusMaster[] master = {getMaster(target.getNodeIp())};
//获取数据
String value = master[0].getValue(new NumericLocator(1, 3, address, type)).toString();
写数据
//ModbusMaster
ModbusMaster master = getMaster(target.getNodeIp());
//设置数据
master.setValue(getNumberFormat(target), value);