use of org.apache.plc4x.java.api.PlcConnection 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;
}
use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.
the class ScraperTest method real_stuff.
@Test
@Disabled
void real_stuff() throws InterruptedException {
PlcDriverManager driverManager = new PooledPlcDriverManager(pooledPlcConnectionFactory -> {
GenericKeyedObjectPoolConfig<PlcConnection> config = new GenericKeyedObjectPoolConfig<>();
config.setJmxEnabled(true);
config.setMaxWaitMillis(-1);
config.setMaxTotal(3);
config.setMinIdlePerKey(0);
config.setBlockWhenExhausted(true);
config.setTestOnBorrow(true);
config.setTestOnReturn(true);
return new GenericKeyedObjectPool<>(pooledPlcConnectionFactory, config);
});
Scraper scraper = new ScraperImpl((j, a, m) -> {
}, driverManager, Arrays.asList(new ScrapeJobImpl("job1", 10, Collections.singletonMap("tim", CONN_STRING_TIM), Collections.singletonMap("distance", FIELD_STRING_TIM)), new ScrapeJobImpl("job2", 10, Collections.singletonMap("chris", CONN_STRING_CH), Collections.singletonMap("counter", FIELD_STRING_CH))));
Thread.sleep(30_000_000);
}
use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.
the class CachedDriverManager method getConnection_.
/**
* Private Impl.
*/
private synchronized PlcConnection getConnection_(String url) throws PlcConnectionException {
logger.trace("Current State {}", this.state.get());
switch(state.get()) {
case AVAILABLE:
logger.debug("Connection was requested and is available, thus, returning Chached Connection for usage");
setState(ConnectionState.BORROWED);
this.numberOfBorrows.incrementAndGet();
this.borrowedConnection = new CachedPlcConnection(this, activeConnection);
// Set the Borrwed Counter
startWatchdog(this.borrowedConnection);
return this.borrowedConnection;
case DISCONNECTED:
logger.debug("Connection was requested but no connection is active, trying to establish a Connection");
// Initialize Connection
setState(ConnectionState.CONNECTING);
this.numberOfConnects.incrementAndGet();
// Start Connection in Background
CompletableFuture.runAsync(() -> {
logger.debug("Starting to establish Connection");
try {
PlcConnection connection = this.connectionFactory.create();
logger.debug("Connection successfully established");
synchronized (this) {
this.activeConnection = connection;
setState(ConnectionState.AVAILABLE);
// Now See if there is someone waiting in the line
checkQueue();
logger.trace("Inline queue check succeeded");
}
} catch (Exception e) {
logger.warn("Unable to establish connection to PLC {}", url, e);
setState(ConnectionState.DISCONNECTED);
}
});
this.numberOfRejections.incrementAndGet();
throw new PlcConnectionException("No Connection Available, Starting Connection");
case CONNECTING:
// We cannot give a Connection
logger.debug("Connection was requsted, but currently establishing one, so none available");
this.numberOfRejections.incrementAndGet();
throw new PlcConnectionException("No Connection Available, Currently Connecting");
case BORROWED:
// We cannot give a Connection
logger.debug("Connection was requsted, but Connection currently is borrowed, so none available");
this.numberOfRejections.incrementAndGet();
throw new PlcConnectionException("No Connection Available, its in Use");
}
throw new IllegalStateException();
}
use of org.apache.plc4x.java.api.PlcConnection 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.PlcConnection 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);
}
}
}
}
Aggregations