Search in sources :

Example 76 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class ManualTest method run.

public void run() throws Exception {
    try (PlcConnection plcConnection = new PlcDriverManager().getConnection(connectionString)) {
        System.out.println("Reading all types in separate requests");
        // Run all entries separately:
        for (TestCase testCase : testCases) {
            String fieldName = testCase.address;
            // Prepare the read-request
            final PlcReadRequest readRequest = plcConnection.readRequestBuilder().addItem(fieldName, testCase.address).build();
            // Execute the read request
            final PlcReadResponse readResponse = readRequest.execute().get();
            // Check the result
            Assertions.assertEquals(1, readResponse.getFieldNames().size(), fieldName);
            Assertions.assertEquals(fieldName, readResponse.getFieldNames().iterator().next(), fieldName);
            Assertions.assertEquals(PlcResponseCode.OK, readResponse.getResponseCode(fieldName), fieldName);
            Assertions.assertNotNull(readResponse.getPlcValue(fieldName), fieldName);
            if (readResponse.getPlcValue(fieldName) instanceof PlcList) {
                PlcList plcList = (PlcList) readResponse.getPlcValue(fieldName);
                if (testCase.expectedReadValue instanceof List) {
                    List<Object> expectedValues = (List<Object>) testCase.expectedReadValue;
                    for (int j = 0; j < expectedValues.size(); j++) {
                        Assertions.assertEquals(expectedValues.get(j), plcList.getIndex(j).getObject(), fieldName + "[" + j + "]");
                    }
                } else {
                    Assertions.fail("Got a list of values, but only expected one.");
                }
            } else {
                Assertions.assertEquals(testCase.expectedReadValue.toString(), readResponse.getPlcValue(fieldName).getObject().toString(), fieldName);
            }
        }
        System.out.println("Success");
        // Read all items in one big request.
        // Shuffle the list of test cases and run the test 10 times.
        System.out.println("Reading all items together in random order");
        for (int i = 0; i < 100; i++) {
            System.out.println(" - run number " + i + " of " + 100);
            final List<TestCase> shuffledTestcases = new ArrayList<>(testCases);
            Collections.shuffle(shuffledTestcases);
            StringBuilder sb = new StringBuilder();
            for (TestCase testCase : shuffledTestcases) {
                sb.append(testCase.address).append(", ");
            }
            System.out.println("       using order: " + sb.toString());
            final PlcReadRequest.Builder builder = plcConnection.readRequestBuilder();
            for (TestCase testCase : shuffledTestcases) {
                String fieldName = testCase.address;
                builder.addItem(fieldName, testCase.address);
            }
            final PlcReadRequest readRequest = builder.build();
            // Execute the read request
            final PlcReadResponse readResponse = readRequest.execute().get();
            // Check the result
            Assertions.assertEquals(shuffledTestcases.size(), readResponse.getFieldNames().size());
            for (TestCase testCase : shuffledTestcases) {
                String fieldName = testCase.address;
                Assertions.assertEquals(PlcResponseCode.OK, readResponse.getResponseCode(fieldName));
                Assertions.assertNotNull(readResponse.getPlcValue(fieldName));
                if (readResponse.getPlcValue(fieldName) instanceof PlcList) {
                    PlcList plcList = (PlcList) readResponse.getPlcValue(fieldName);
                    List<Object> expectedValues = (List<Object>) testCase.expectedReadValue;
                    for (int j = 0; j < expectedValues.size(); j++) {
                        Assertions.assertEquals(expectedValues.get(j), plcList.getIndex(j).getObject());
                    }
                } else {
                    Assertions.assertEquals(testCase.expectedReadValue.toString(), readResponse.getPlcValue(fieldName).getObject().toString());
                }
            }
        }
        System.out.println("Success");
    } catch (Exception e) {
        Assertions.fail(e);
    }
}
Also used : ArrayList(java.util.ArrayList) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcList(org.apache.plc4x.java.spi.values.PlcList) PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) PlcList(org.apache.plc4x.java.spi.values.PlcList) List(java.util.List) ArrayList(java.util.ArrayList) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager)

Example 77 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class Testcase method run.

public void run() throws DriverTestsuiteException {
    assert driverTestsuite != null;
    LOGGER.info("Starting testcase: {}", name);
    final PlcConnection plcConnection = connectionManager.getConnection(driverTestsuite.getDriverTestsuiteConfiguration().getDriverName(), driverTestsuite.getDriverTestsuiteConfiguration().getDriverParameters());
    final Plc4xEmbeddedChannel embeddedChannel = connectionManager.getEmbeddedChannel(plcConnection);
    final ByteOrder byteOrder = driverTestsuite.getDriverTestsuiteConfiguration().getByteOrder();
    // Be sure this is reset, just in case a previous testcase failed.
    synchronizer.responseFuture = null;
    if (!driverTestsuite.getSetupSteps().isEmpty()) {
        LOGGER.info("Running setup steps");
        for (TestStep setupStep : driverTestsuite.getSetupSteps()) {
            setupStep.execute(plcConnection, embeddedChannel, byteOrder);
        }
        LOGGER.info("Finished setup steps");
    }
    LOGGER.info("Running test steps");
    for (TestStep step : steps) {
        step.execute(plcConnection, embeddedChannel, byteOrder);
    }
    LOGGER.info("Finished test steps");
    if (!driverTestsuite.getTeardownSteps().isEmpty()) {
        LOGGER.info("Running teardown steps");
        for (TestStep teardownStep : driverTestsuite.getTeardownSteps()) {
            teardownStep.execute(plcConnection, embeddedChannel, byteOrder);
        }
        LOGGER.info("Finished teardown steps");
    }
    try {
        plcConnection.close();
    } catch (Exception e) {
        LOGGER.warn("Error closing connection", e);
    }
    LOGGER.info("Finished testcase: {}", driverTestsuite.getName());
}
Also used : ByteOrder(org.apache.plc4x.java.spi.generation.ByteOrder) PlcConnection(org.apache.plc4x.java.api.PlcConnection) Plc4xEmbeddedChannel(io.netty.channel.embedded.Plc4xEmbeddedChannel) DriverTestsuiteException(org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException)

Example 78 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class Plc4xServerAdapter method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof Plc4xMessage) {
        final Plc4xMessage plc4xMessage = (Plc4xMessage) msg;
        switch(plc4xMessage.getRequestType()) {
            case CONNECT_REQUEST:
                {
                    Plc4xConnectRequest request = (Plc4xConnectRequest) plc4xMessage;
                    try (final PlcConnection ignored = driverManager.getConnection(request.getConnectionString())) {
                        // connection.ping().get();
                        final int connectionId = connectionIdGenerator.getAndIncrement();
                        connectionUrls.put(connectionId, request.getConnectionString());
                        Plc4xConnectResponse response = new Plc4xConnectResponse(request.getRequestId(), connectionId, Plc4xResponseCode.OK);
                        ctx.writeAndFlush(response);
                    } catch (Exception e) {
                        Plc4xConnectResponse response = new Plc4xConnectResponse(request.getRequestId(), 0, Plc4xResponseCode.INVALID_ADDRESS);
                        ctx.writeAndFlush(response);
                    }
                    break;
                }
            case READ_REQUEST:
                {
                    final Plc4xReadRequest request = (Plc4xReadRequest) plc4xMessage;
                    String connectionUrl = connectionUrls.get(request.getConnectionId());
                    try (final PlcConnection connection = driverManager.getConnection(connectionUrl)) {
                        // Build a read request for all fields in the request.
                        final PlcReadRequest.Builder builder = connection.readRequestBuilder();
                        for (Plc4xFieldRequest requestField : request.getFields()) {
                            builder.addItem(requestField.getField().getName(), requestField.getField().getFieldQuery());
                        }
                        final PlcReadRequest rr = builder.build();
                        // Execute the query.
                        // (It has to be synchronously when working with the connection cache)
                        final PlcReadResponse apiReadResponse = rr.execute().get();
                        // Create the response.
                        List<Plc4xFieldValueResponse> fields = new ArrayList<>(apiReadResponse.getFieldNames().size());
                        for (Plc4xFieldRequest plc4xRequestField : request.getFields()) {
                            final PlcResponseCode responseCode = apiReadResponse.getResponseCode(plc4xRequestField.getField().getName());
                            Plc4xResponseCode resCode;
                            Plc4xValueType valueType;
                            PlcValue value;
                            if (responseCode == PlcResponseCode.OK) {
                                resCode = Plc4xResponseCode.OK;
                                value = apiReadResponse.getPlcValue(plc4xRequestField.getField().getName());
                                final String valueTypeName = value.getClass().getSimpleName();
                                // Cut off the "Plc" prefix to get the name of the PlcValueType.
                                valueType = Plc4xValueType.valueOf(valueTypeName.substring(3));
                            } else {
                                resCode = Plc4xResponseCode.INVALID_ADDRESS;
                                value = null;
                                valueType = Plc4xValueType.NULL;
                            }
                            fields.add(new Plc4xFieldValueResponse(plc4xRequestField.getField(), resCode, valueType, value));
                        }
                        Plc4xReadResponse response = new Plc4xReadResponse(request.getRequestId(), request.getConnectionId(), Plc4xResponseCode.OK, fields);
                        // Send the response.
                        ctx.writeAndFlush(response);
                    } catch (Exception e) {
                        logger.error("Error executing request", e);
                        Plc4xReadResponse response = new Plc4xReadResponse(request.getRequestId(), request.getConnectionId(), Plc4xResponseCode.INVALID_ADDRESS, Collections.emptyList());
                        ctx.writeAndFlush(response);
                    }
                    break;
                }
            case WRITE_REQUEST:
                final Plc4xWriteRequest plc4xWriteRequest = (Plc4xWriteRequest) plc4xMessage;
                String connectionUrl = connectionUrls.get(plc4xWriteRequest.getConnectionId());
                try (final PlcConnection connection = driverManager.getConnection(connectionUrl)) {
                    // Build a write request for all fields in the request.
                    final PlcWriteRequest.Builder builder = connection.writeRequestBuilder();
                    for (Plc4xFieldValueRequest plc4xRequestField : plc4xWriteRequest.getFields()) {
                        builder.addItem(plc4xRequestField.getField().getName(), plc4xRequestField.getField().getFieldQuery(), plc4xRequestField.getValue().getObject());
                    }
                    final PlcWriteRequest apiWriteRequest = builder.build();
                    // Execute the query
                    // (It has to be synchronously when working with the connection cache)
                    final PlcWriteResponse apiWriteResponse = apiWriteRequest.execute().get();
                    // Create the response.
                    List<Plc4xFieldResponse> plc4xFields = new ArrayList<>(apiWriteResponse.getFieldNames().size());
                    for (Plc4xFieldValueRequest plc4xRequestField : plc4xWriteRequest.getFields()) {
                        final PlcResponseCode apiResponseCode = apiWriteResponse.getResponseCode(plc4xRequestField.getField().getName());
                        Plc4xResponseCode resCode;
                        if (apiResponseCode == PlcResponseCode.OK) {
                            resCode = Plc4xResponseCode.OK;
                        } else {
                            resCode = Plc4xResponseCode.INVALID_ADDRESS;
                        }
                        plc4xFields.add(new Plc4xFieldResponse(plc4xRequestField.getField(), resCode));
                    }
                    Plc4xWriteResponse plc4xWriteResponse = new Plc4xWriteResponse(plc4xWriteRequest.getRequestId(), plc4xWriteRequest.getConnectionId(), Plc4xResponseCode.OK, plc4xFields);
                    // Send the response.
                    ctx.writeAndFlush(plc4xWriteResponse);
                } catch (Exception e) {
                    logger.error("Error executing request", e);
                    Plc4xWriteResponse response = new Plc4xWriteResponse(plc4xWriteRequest.getRequestId(), plc4xWriteRequest.getConnectionId(), Plc4xResponseCode.INVALID_ADDRESS, Collections.emptyList());
                    ctx.writeAndFlush(response);
                }
                break;
        }
    }
}
Also used : ArrayList(java.util.ArrayList) PlcWriteResponse(org.apache.plc4x.java.api.messages.PlcWriteResponse) PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) PlcWriteRequest(org.apache.plc4x.java.api.messages.PlcWriteRequest) ArrayList(java.util.ArrayList) List(java.util.List) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) PlcValue(org.apache.plc4x.java.api.value.PlcValue) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest)

Example 79 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class TriggeredScraperTask method run.

@Override
public void run() {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Check condition for task of job {} for connection {}", jobName, connectionAlias);
    }
    if (this.triggerHandler.checkTrigger()) {
        // Does a single fetch only when trigger is valid
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Trigger for job {} and device {} is met ... scraping desired data", jobName, connectionAlias);
        }
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Start new scrape of task of job {} for connection {}", jobName, connectionAlias);
        }
        requestCounter.incrementAndGet();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        PlcConnection connection = null;
        try {
            String info = "";
            if (LOGGER.isTraceEnabled()) {
                info = String.format("acquiring data collecting connection to (%s,%s)", connectionAlias, jobName);
                LOGGER.trace("acquiring data collecting connection to ({},{})", connectionAlias, jobName);
            }
            connection = TriggeredScraperImpl.getPlcConnection(driverManager, connectionString, executorService, requestTimeoutMs, info);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Connection to {} established: {}", connectionString, connection);
            }
            PlcReadResponse plcReadResponse;
            try {
                PlcReadRequest.Builder readRequestBuilder = connection.readRequestBuilder();
                for (Map.Entry<String, String> entry : fields.entrySet()) {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("Requesting: {} -> {}", entry.getKey(), entry.getValue());
                    }
                    readRequestBuilder.addItem(entry.getKey(), entry.getValue());
                }
                // build and send request and store result in read response
                plcReadResponse = readRequestBuilder.build().execute().get(requestTimeoutMs, TimeUnit.MILLISECONDS);
            } catch (ExecutionException e) {
                // Handle execution exception
                handleException(e);
                return;
            }
            // Add statistics
            LOGGER.debug("Performing statistics");
            stopWatch.stop();
            latencyStatistics.addValue(stopWatch.getNanoTime());
            failedStatistics.addValue(0.0);
            successCounter.incrementAndGet();
            // Validate response
            validateResponse(plcReadResponse);
            // Handle response (Async)
            CompletableFuture.runAsync(() -> resultHandler.handle(jobName, connectionAlias, TriggeredScraperImpl.convertPlcResponseToMap(plcReadResponse)), executorService);
        } catch (Exception e) {
            LOGGER.warn("Exception during scraping of Job {}, Connection-Alias {}: Error-message: {} - for stack-trace change logging to DEBUG", jobName, connectionAlias, e.getCause());
            handleException(e);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                    LOGGER.warn("Error on closing connection", e);
                }
            }
        }
    }
}
Also used : PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map) PlcConnection(org.apache.plc4x.java.api.PlcConnection) ScraperException(org.apache.plc4x.java.scraper.exception.ScraperException) ExecutionException(java.util.concurrent.ExecutionException) StopWatch(org.apache.commons.lang3.time.StopWatch)

Example 80 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class PlcConnectionAdapter method newSupplier.

Supplier<PlcReadResponse> newSupplier(PlcReadRequest readRequest) {
    return new Supplier<PlcReadResponse>() {

        private static final long serialVersionUID = 1L;

        @Override
        public PlcReadResponse get() {
            PlcConnection connection = null;
            try {
                connection = getConnection();
                LocalDateTime start = LocalDateTime.now();
                PlcReadResponse plcReadResponse = readRequest.execute().get();
                LocalDateTime end = LocalDateTime.now();
                if (logger.isTraceEnabled()) {
                    long diff = ChronoUnit.MILLIS.between(start, end);
                    logger.trace("Processed request in " + diff + "ms");
                }
                return plcReadResponse;
            } catch (Exception e) {
                logger.error("reading from plc device {} {} failed", connection, readRequest, e);
                return null;
            }
        }
    };
}
Also used : LocalDateTime(java.time.LocalDateTime) PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) Supplier(org.apache.edgent.function.Supplier) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcException(org.apache.plc4x.java.api.exceptions.PlcException)

Aggregations

PlcConnection (org.apache.plc4x.java.api.PlcConnection)80 PlcDriverManager (org.apache.plc4x.java.PlcDriverManager)36 PlcConnectionException (org.apache.plc4x.java.api.exceptions.PlcConnectionException)30 PlcReadResponse (org.apache.plc4x.java.api.messages.PlcReadResponse)23 Test (org.junit.jupiter.api.Test)22 PlcReadRequest (org.apache.plc4x.java.api.messages.PlcReadRequest)20 ExecutionException (java.util.concurrent.ExecutionException)18 PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)12 TimeoutException (java.util.concurrent.TimeoutException)9 BigInteger (java.math.BigInteger)8 PlcSubscriptionResponse (org.apache.plc4x.java.api.messages.PlcSubscriptionResponse)8 PlcWriteRequest (org.apache.plc4x.java.api.messages.PlcWriteRequest)8 Map (java.util.Map)7 HashMap (java.util.HashMap)6 MockConnection (org.apache.plc4x.java.mock.connection.MockConnection)6 CompletableFuture (java.util.concurrent.CompletableFuture)5 Condition (org.assertj.core.api.Condition)5 Disabled (org.junit.jupiter.api.Disabled)5 Field (java.lang.reflect.Field)4 LocalDateTime (java.time.LocalDateTime)4