Search in sources :

Example 11 with PlcConnectionException

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

the class PlcEntityInterceptor method writeAllFields.

static void writeAllFields(Object proxy, PlcDriverManager driverManager, String address, AliasRegistry registry, Map<String, Instant> lastWritten) 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("Writing 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
        PlcWriteRequest.Builder requestBuilder = connection.writeRequestBuilder();
        Arrays.stream(entityClass.getDeclaredFields()).filter(field -> field.isAnnotationPresent(PlcField.class)).filter(field -> needsToBeSynced(lastWritten, field)).forEach(field -> requestBuilder.addItem(getFqn(field), OpmUtils.getOrResolveAddress(registry, field.getAnnotation(PlcField.class).value()), getFromField(field, proxy)));
        PlcWriteRequest request = requestBuilder.build();
        LOGGER.trace("Request for write of {} was build and is {}", entityClass, request);
        PlcWriteResponse response = getPlcWriteResponse(request);
        // Fill all requested fields
        for (String fieldName : response.getFieldNames()) {
            // Fill into Cache
            lastWritten.put(fieldName, Instant.now());
        }
    } 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) 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 12 with PlcConnectionException

use of org.apache.plc4x.java.api.exceptions.PlcConnectionException 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 13 with PlcConnectionException

use of org.apache.plc4x.java.api.exceptions.PlcConnectionException 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 14 with PlcConnectionException

use of org.apache.plc4x.java.api.exceptions.PlcConnectionException 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)

Example 15 with PlcConnectionException

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

the class DefaultNettyPlcConnection method connect.

@Override
public void connect() throws PlcConnectionException {
    try {
        // As we don't just want to wait till the connection is established,
        // define a future we can use to signal back that the s7 session is
        // finished initializing.
        CompletableFuture<Void> sessionSetupCompleteFuture = new CompletableFuture<>();
        CompletableFuture<Configuration> sessionDiscoveredCompleteFuture = new CompletableFuture<>();
        if (channelFactory == null) {
            throw new PlcConnectionException("No channel factory provided");
        }
        // Inject the configuration
        ConfigurationFactory.configure(configuration, channelFactory);
        // Have the channel factory create a new channel instance.
        if (awaitSessionDiscoverComplete) {
            channel = channelFactory.createChannel(getChannelHandler(sessionSetupCompleteFuture, sessionDisconnectCompleteFuture, sessionDiscoveredCompleteFuture));
            channel.closeFuture().addListener(future -> {
                if (!sessionDiscoveredCompleteFuture.isDone()) {
                    // Do Nothing
                    try {
                        sessionDiscoveredCompleteFuture.complete(null);
                    } catch (Exception e) {
                    // Do Nothing
                    }
                }
            });
            channel.pipeline().fireUserEventTriggered(new DiscoverEvent());
            // Wait till the connection is established.
            sessionDiscoveredCompleteFuture.get();
        }
        channel = channelFactory.createChannel(getChannelHandler(sessionSetupCompleteFuture, sessionDisconnectCompleteFuture, sessionDiscoveredCompleteFuture));
        channel.closeFuture().addListener(future -> {
            if (!sessionSetupCompleteFuture.isDone()) {
                sessionSetupCompleteFuture.completeExceptionally(new PlcIoException("Connection terminated by remote"));
            }
        });
        // Send an event to the pipeline telling the Protocol filters what's going on.
        sendChannelCreatedEvent();
        // Wait till the connection is established.
        if (awaitSessionSetupComplete) {
            sessionSetupCompleteFuture.get();
        }
        // Set the connection to "connected"
        connected = true;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new PlcConnectionException(e);
    } catch (ExecutionException e) {
        throw new PlcConnectionException(e);
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Configuration(org.apache.plc4x.java.spi.configuration.Configuration) PlcIoException(org.apache.plc4x.java.api.exceptions.PlcIoException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) ExecutionException(java.util.concurrent.ExecutionException) PlcIoException(org.apache.plc4x.java.api.exceptions.PlcIoException) ExecutionException(java.util.concurrent.ExecutionException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException)

Aggregations

PlcConnectionException (org.apache.plc4x.java.api.exceptions.PlcConnectionException)36 PlcConnection (org.apache.plc4x.java.api.PlcConnection)21 ExecutionException (java.util.concurrent.ExecutionException)11 PlcDriverManager (org.apache.plc4x.java.PlcDriverManager)11 PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)10 TimeoutException (java.util.concurrent.TimeoutException)8 Test (org.junit.jupiter.api.Test)8 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 BigInteger (java.math.BigInteger)5 UnknownHostException (java.net.UnknownHostException)4 Arrays (java.util.Arrays)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 Matcher (java.util.regex.Matcher)4 PlcReadResponse (org.apache.plc4x.java.api.messages.PlcReadResponse)4 Channel (io.netty.channel.Channel)3 BigDecimal (java.math.BigDecimal)3 LocalDate (java.time.LocalDate)3 LocalDateTime (java.time.LocalDateTime)3 LocalTime (java.time.LocalTime)3