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);
}
}
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);
}
}
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;
}
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);
}
}
}
}
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);
}
}
Aggregations