汇川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);


posted @   南翔技校毕业后  阅读(167)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
点击右上角即可分享
微信分享提示