Search in sources :

Example 16 with PlcRuntimeException

use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.

the class PlcEntityInterceptor method refetchAllFields.

/**
 * Renews all values of all Fields that are annotated with {@link PlcEntity}.
 *
 * @param proxy         Object to refresh the fields on.
 * @param driverManager Driver Manager to use
 * @param registry      AliasRegistry to use
 * @param lastFetched
 * @throws OPMException on various errors.
 */
// Nested try blocks readability is okay, move to other method makes it imho worse
@SuppressWarnings("squid:S1141")
static void refetchAllFields(Object proxy, PlcDriverManager driverManager, String address, AliasRegistry registry, Map<String, Instant> lastFetched) throws OPMException {
    // Don't log o here as this would cause a second request against a plc so don't touch it, or if you log be aware of that
    Class<?> entityClass = proxy.getClass().getSuperclass();
    LOGGER.trace("Refetching all fields on proxy object of class {}", entityClass);
    PlcEntity plcEntity = entityClass.getAnnotation(PlcEntity.class);
    if (plcEntity == null) {
        throw new OPMException("Non PlcEntity supplied");
    }
    // Check if all fields are valid
    for (Field field : entityClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(PlcField.class)) {
            OpmUtils.getOrResolveAddress(registry, field.getAnnotation(PlcField.class).value());
        }
    }
    try (PlcConnection connection = driverManager.getConnection(address)) {
        // Catch the exception, if no reader present (see below)
        // Build the query
        PlcReadRequest.Builder requestBuilder = connection.readRequestBuilder();
        Arrays.stream(entityClass.getDeclaredFields()).filter(field -> field.isAnnotationPresent(PlcField.class)).filter(field -> needsToBeSynced(lastFetched, field)).forEach(field -> requestBuilder.addItem(getFqn(field), OpmUtils.getOrResolveAddress(registry, field.getAnnotation(PlcField.class).value())));
        PlcReadRequest request = requestBuilder.build();
        LOGGER.trace("Request for refetch of {} was build and is {}", entityClass, request);
        PlcReadResponse response = getPlcReadResponse(request);
        // Fill all requested fields
        for (String fieldName : response.getFieldNames()) {
            // Fill into Cache
            lastFetched.put(fieldName, Instant.now());
            LOGGER.trace("Value for field {}  is {}", fieldName, response.getObject(fieldName));
            String clazzFieldName = StringUtils.substringAfterLast(fieldName, ".");
            try {
                setField(entityClass, proxy, response, clazzFieldName, fieldName);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                throw new PlcRuntimeException(e);
            }
        }
    } catch (PlcConnectionException e) {
        throw new OPMException("Problem during processing", e);
    } catch (Exception e) {
        throw new OPMException("Unexpected error during processing", e);
    }
}
Also used : PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) Arrays(java.util.Arrays) PlcConnection(org.apache.plc4x.java.api.PlcConnection) LoggerFactory(org.slf4j.LoggerFactory) LocalDateTime(java.time.LocalDateTime) TimeoutException(java.util.concurrent.TimeoutException) net.bytebuddy.implementation.bind.annotation(net.bytebuddy.implementation.bind.annotation) ArrayUtils(org.apache.commons.lang3.ArrayUtils) Callable(java.util.concurrent.Callable) StringUtils(org.apache.commons.lang3.StringUtils) BigDecimal(java.math.BigDecimal) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) Map(java.util.Map) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) LocalTime(java.time.LocalTime) BigInteger(java.math.BigInteger) Method(java.lang.reflect.Method) Logger(org.slf4j.Logger) Field(java.lang.reflect.Field) Instant(java.time.Instant) Configuration(org.apache.commons.configuration2.Configuration) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Validate(org.apache.commons.lang3.Validate) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) ChronoUnit(java.time.temporal.ChronoUnit) SystemConfiguration(org.apache.commons.configuration2.SystemConfiguration) LocalDate(java.time.LocalDate) org.apache.plc4x.java.api.messages(org.apache.plc4x.java.api.messages) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcConnection(org.apache.plc4x.java.api.PlcConnection) TimeoutException(java.util.concurrent.TimeoutException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) ExecutionException(java.util.concurrent.ExecutionException) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) Field(java.lang.reflect.Field) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException)

Example 17 with PlcRuntimeException

use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.

the class PlcEntityInterceptor method setForField.

private static void setForField(Field field, Object proxy, Object value) {
    try {
        field.setAccessible(true);
        field.set(proxy, value);
    } catch (IllegalAccessException e) {
        throw new PlcRuntimeException(e);
    }
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException)

Example 18 with PlcRuntimeException

use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.

the class ManualS7PlcDriverMT method runSingleRequest.

private double runSingleRequest(PlcDriverManager plcDriverManager) {
    long start = System.nanoTime();
    try (PlcConnection connection = plcDriverManager.getConnection(CONN_STRING)) {
        System.out.println("Connection: " + connection);
        CompletableFuture<? extends PlcReadResponse> future = connection.readRequestBuilder().addItem("distance", FIELD_STRING).build().execute();
        PlcReadResponse response = future.get(10, TimeUnit.SECONDS);
    } catch (Exception e) {
        throw new PlcRuntimeException(e);
    }
    long end = System.nanoTime();
    return (double) end - start;
}
Also used : PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException)

Example 19 with PlcRuntimeException

use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.

the class TriggeredScraperImpl method getPlcConnection.

/**
 * acquires a plc connection from connection pool
 * @param plcDriverManager  Driver manager handling connection and pools
 * @param connectionString  Connection string as defined in the regarding implementation of {@link PlcDriver}
 * @param executorService   ExecuterService holding a pool as threads handling requests and stuff
 * @param requestTimeoutMs  maximum awaiting for the the future to return a result
 * @param info              additional info for trace reasons
 * @return the {@link PlcConnection} used for acquiring data from PLC endpoint
 * @throws InterruptedException something went wrong
 * @throws ExecutionException something went wrong
 * @throws TimeoutException something went wrong
 */
public static PlcConnection getPlcConnection(PlcDriverManager plcDriverManager, String connectionString, ExecutorService executorService, long requestTimeoutMs, String info) throws InterruptedException, ExecutionException, TimeoutException {
    if (!info.isEmpty() && LOGGER.isTraceEnabled()) {
        LOGGER.trace("Additional Info from caller {}", info);
    }
    CompletableFuture<PlcConnection> future = CompletableFuture.supplyAsync(() -> {
        try {
            return plcDriverManager.getConnection(connectionString);
        } catch (PlcConnectionException e) {
            LOGGER.warn("Unable to instantiate connection to " + connectionString, e);
            throw new PlcRuntimeException(e);
        } catch (Exception e) {
            LOGGER.warn("Unable to instantiate connection to " + connectionString, e);
            throw new PlcRuntimeException(e);
        }
    }, executorService);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("try to get a connection to {}", connectionString);
    }
    PlcConnection plcConnection = null;
    try {
        plcConnection = future.get(requestTimeoutMs, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        LOGGER.trace("Additional Info from caller {}", info, e);
        throw e;
    }
    return plcConnection;
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) PlcConnection(org.apache.plc4x.java.api.PlcConnection) ScraperException(org.apache.plc4x.java.scraper.exception.ScraperException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException)

Example 20 with PlcRuntimeException

use of org.apache.plc4x.java.api.exceptions.PlcRuntimeException in project plc4x by apache.

the class ScraperTaskImpl method run.

@Override
public void run() {
    // Does a single fetch
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Start new scrape of task of job {} for connection {}", jobName, connectionAlias);
    }
    requestCounter.incrementAndGet();
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    PlcConnection connection = null;
    try {
        CompletableFuture<PlcConnection> future = CompletableFuture.supplyAsync(() -> {
            try {
                return driverManager.getConnection(connectionString);
            } catch (PlcConnectionException e) {
                LOGGER.warn("Unable to instantiate connection to " + connectionString, e);
                throw new PlcRuntimeException(e);
            }
        }, handlerService);
        connection = future.get(10 * requestTimeoutMs, TimeUnit.MILLISECONDS);
        LOGGER.debug("Connection to {} established: {}", connectionString, connection);
        PlcReadResponse plcReadResponse;
        try {
            // build read request
            PlcReadRequest.Builder readRequestBuilder = connection.readRequestBuilder();
            // add fields to be acquired to builder
            fields.forEach((alias, qry) -> {
                LOGGER.trace("Requesting: {} -> {}", alias, qry);
                readRequestBuilder.addItem(alias, qry);
            });
            plcReadResponse = readRequestBuilder.build().execute().get(requestTimeoutMs, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            // Handle execution exception
            handleException(e);
            return;
        }
        LOGGER.debug("Performing statistics");
        // Add some 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, transformResponseToMap(plcReadResponse)), handlerService);
    } catch (Exception e) {
        LOGGER.warn("Exception during scraping of Job {}, Connection-Alias {}: Error-message: {} - for stack-trace change logging to DEBUG", jobName, connectionAlias, e.getMessage());
        handleException(e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                LOGGER.warn("Error on closing connection", e);
            }
        }
    }
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcReadResponse(org.apache.plc4x.java.api.messages.PlcReadResponse) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) ExecutionException(java.util.concurrent.ExecutionException) PlcConnection(org.apache.plc4x.java.api.PlcConnection) ExecutionException(java.util.concurrent.ExecutionException) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) StopWatch(org.apache.commons.lang3.time.StopWatch)

Aggregations

PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)95 BigInteger (java.math.BigInteger)17 CompletableFuture (java.util.concurrent.CompletableFuture)14 PlcResponseCode (org.apache.plc4x.java.api.types.PlcResponseCode)14 PlcValue (org.apache.plc4x.java.api.value.PlcValue)14 ResponseItem (org.apache.plc4x.java.spi.messages.utils.ResponseItem)14 Duration (java.time.Duration)13 PlcField (org.apache.plc4x.java.api.model.PlcField)13 PlcConnectionException (org.apache.plc4x.java.api.exceptions.PlcConnectionException)10 HasConfiguration (org.apache.plc4x.java.spi.configuration.HasConfiguration)10 ParseException (org.apache.plc4x.java.spi.generation.ParseException)10 RequestTransactionManager (org.apache.plc4x.java.spi.transaction.RequestTransactionManager)10 Collections (java.util.Collections)9 DefaultPlcReadRequest (org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest)9 DefaultPlcWriteRequest (org.apache.plc4x.java.spi.messages.DefaultPlcWriteRequest)9 IOException (java.io.IOException)8 org.apache.plc4x.java.modbus.readwrite (org.apache.plc4x.java.modbus.readwrite)8 DefaultPlcReadResponse (org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse)8 ModbusField (org.apache.plc4x.java.modbus.base.field.ModbusField)7 PlcList (org.apache.plc4x.java.spi.values.PlcList)7