Java与opc通信之三 - s7协议(s7connector)

1、引入依赖

<dependency>
            <groupId>com.github.s7connector</groupId>
            <artifactId>s7connector</artifactId>
            <version>2.1</version>
        </dependency>

2、获取S7Connector连接,读取opc数据

public static S7Connector initConnect(){
        //PLC地址 二标段
        //String ipAddress = "xxx";
        //PLC地址 一标段
        String ipAddress = "xxx";
        //默认端口
        //int port = 102;
        int rack=0;
        int slot=3;
        int timeout=10000;
        S7Connector s7connector=
                S7ConnectorFactory
                        .buildTCPConnector()
                        .withHost(ipAddress)
                        //.withPort(port) //optional
                        //.withRack(rack) //optional
                        //.withSlot(slot) //optional
                        .withTimeout(timeout) //连接超时时间
                        .build();
        S7Serializer s7Serializer2L = S7SerializerFactory.buildSerializer(s7connector);
        return s7connector;

    }

public static void testReadPlcRealData() {

        S7Connector s7Connector = initConnect();
        //第一个参数:DaveArea.DB 表示读取PLC的地址区域为DB
        //第二个参数:DB块地址,若plc中是DB1000,则填1000
        //第三个参数:数据长度
        //第四个参数:偏移量
        //byte [] bytes = ByteBuffer.allocate(8).putDouble(1729.1729).array();
        //byte [] bytes = { 64, -101, 4, -79, 12, -78, -107, -22 };
        //System.out.println();

        byte[] getBytes = s7Connector.read(DaveArea.DB, 4, 4, 64);
        //byte[] getBytes = s7Connector.read(DaveArea.DB, 4, 4, 104);
        Float getValue = ByteBuffer.wrap(getBytes).getFloat();
        System.out.println("getFloatData:"+getValue);
        try {
            s7Connector.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
View Code
posted @ 2023-01-29 10:45  Caesar_the_great  阅读(1373)  评论(0编辑  收藏  举报