plc4x使用

连接缓存 Connection Cache

引入maven依赖

<dependency>

      <groupId>org.apache.plc4x</groupId>

      <artifactId>plc4j-connection-cache</artifactId>

      <version>0.12.0</version>

    </dependency>

配置

PlcConnectionManager connectionManager = CachedPlcConnectionManager.getBuilder()

            .withMaxLeaseTime(Duration.ofSeconds(10))

            .withMaxWaitTime(Duration.ofMinutes(1))

            .build();

例子:

public static void main(String[] args) throws Exception {

        PlcConnectionManager connectionManager = CachedPlcConnectionManager.getBuilder().build();

        for (int i = 0; i < 10000; i++) {

            try(PlcConnection connection = connectionManager.getConnection("s7://192.168.1.192")) {

                if (connection.isConnected()){

                    PlcReadRequest.Builder builder = connection.readRequestBuilder();

                    builder.addTagAddress("PollingValue", "%DB1:4.0:BOOL");

                    PlcReadRequest readRequest = builder.build();

                    PlcReadResponse syncResponse = readRequest.execute().get(2000, TimeUnit.MILLISECONDS);

                    printResponse(syncResponse);

                } else {

                    logger.info("PLC is not connected, let's try again to connect");

                    connection.connect();

                }

            } catch (PlcConnectionException e){

                logger.error("Connection exception in trying to connect", e);

            } catch (CancellationException e){

                logger.error("Polling Thread canceled", e);

            } catch (IllegalStateException e){

                logger.error("Error in Netty state machine", e);

            } catch (ExecutionException e){

                logger.error("Interrupted Exception fired", e);

            } catch (TimeoutException e) {

                logger.error("Timeout exception fired", e);

            }

            TimeUnit.MILLISECONDS.sleep(100);

        }

        System.exit(0);

    }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容