Search in sources :

Example 16 with PlcConnection

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

the class PooledDriverManagerTest method getCachedDriverManager.

@Test
void getCachedDriverManager() throws PlcConnectionException {
    CachedDriverManager mock = Mockito.mock(CachedDriverManager.class, Mockito.RETURNS_DEEP_STUBS);
    PooledDriverManager driverManager = new PooledDriverManager(key -> mock);
    assertThat(driverManager.getCachedManagers().size()).isEqualTo(0);
    PlcConnection connection = driverManager.getConnection("abc");
    assertThat(driverManager.getCachedManagers()).containsValue(mock).containsKey("abc").hasSize(1);
    verify(mock, times(1)).getConnection("abc");
}
Also used : PlcConnection(org.apache.plc4x.java.api.PlcConnection) Test(org.junit.jupiter.api.Test)

Example 17 with PlcConnection

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

the class PooledPlcDriverManager method getStatistics.

// TODO: maybe export to jmx // generic poolKey has builtin jmx too
public Map<String, Number> getStatistics() {
    HashMap<String, Number> statistics = new HashMap<>();
    statistics.put("numActive", keyedObjectPool.getNumActive());
    statistics.put("numIdle", keyedObjectPool.getNumIdle());
    if (keyedObjectPool instanceof GenericKeyedObjectPool) {
        GenericKeyedObjectPool<PoolKey, PlcConnection> genericKeyedObjectPool = (GenericKeyedObjectPool<PoolKey, PlcConnection>) this.keyedObjectPool;
        // Thats pretty ugly and we really should't do that...
        try {
            Map poolMap = (Map) FieldUtils.getField(GenericKeyedObjectPool.class, "poolMap", true).get(this.keyedObjectPool);
            statistics.put("pools.count", poolMap.size());
        } catch (IllegalAccessException e) {
            throw new PlcRuntimeException(e);
        }
        Map<String, Integer> numActivePerKey = genericKeyedObjectPool.getNumActivePerKey();
        for (Map.Entry<String, Integer> entry : numActivePerKey.entrySet()) {
            statistics.put(entry.getKey() + ".numActive", entry.getValue());
        }
    }
    return statistics;
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) HashMap(java.util.HashMap) GenericKeyedObjectPool(org.apache.commons.pool2.impl.GenericKeyedObjectPool) PlcConnection(org.apache.plc4x.java.api.PlcConnection) HashMap(java.util.HashMap) Map(java.util.Map)

Example 18 with PlcConnection

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

the class PooledPlcDriverManagerTest method cleanupOfBrokenConnections.

@Test
void cleanupOfBrokenConnections() throws Exception {
    AtomicBoolean failNow = new AtomicBoolean(false);
    when(plcDriver.getConnection(anyString())).then(invocationOnMock -> {
        DummyPlcConnection dummyPlcConnection = spy(new DummyPlcConnection(invocationOnMock.getArgument(0)));
        // we fake an connection which breaks at this call
        doAnswer(invocation -> {
            if (failNow.get()) {
                throw new PlcConnectionException("blub");
            }
            return invocation.callRealMethod();
        }).when(dummyPlcConnection).connect();
        return dummyPlcConnection;
    });
    assertThat(SUT.getStatistics()).containsOnly(entry("pools.count", 0), entry("numActive", 0), entry("numIdle", 0));
    PlcConnection connection = SUT.getConnection("dummydummy:breakIt");
    assertThat(SUT.getStatistics()).containsOnly(entry("pools.count", 1), entry("numActive", 1), entry("numIdle", 0), entry("PoolKey{url='dummydummy:breakIt'}.numActive", 1));
    failNow.set(true);
    try {
        connection.connect();
        fail("This should throw an exception");
    } catch (Exception e) {
        // TODO: currently UndeclaredThrowableException is the top one which should be InvocationTargetException
        // assertThat(e).isInstanceOf(InvocationTargetException.class);
        assertThat(e).hasRootCauseInstanceOf(PlcConnectionException.class);
    }
    // Faulty connection should have been discarded
    assertThat(SUT.getStatistics()).containsOnly(entry("pools.count", 0), entry("numActive", 0), entry("numIdle", 0));
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcUnsupportedOperationException(org.apache.plc4x.java.api.exceptions.PlcUnsupportedOperationException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) Test(org.junit.jupiter.api.Test)

Example 19 with PlcConnection

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

the class ManualPlc4XAdsTest method main.

public static void main(String... args) throws Exception {
    String connectionUrl;
    if (args.length > 0 && "serial".equalsIgnoreCase(args[0])) {
        System.out.println("Using serial");
        connectionUrl = "ads:serial:///dev/ttys003/10.10.64.40.1.1:851/10.10.56.23.1.1:30000";
    } else {
        System.out.println("Using tcp");
        connectionUrl = "ads:tcp://10.10.64.40/10.10.64.40.1.1:851/10.10.56.23.1.1:30000";
    }
    // TODO: temporary workaround
    Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
        System.err.println(t + " - " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    });
    try (PlcConnection plcConnection = new PlcDriverManager().getConnection(connectionUrl)) {
        System.out.println("PlcConnection " + plcConnection);
        PlcReadRequest.Builder readRequestBuilder = plcConnection.readRequestBuilder();
        PlcReadRequest readRequest = readRequestBuilder.addItem("station", "Allgemein_S2.Station:BYTE").build();
        CompletableFuture<? extends PlcReadResponse> response = readRequest.execute();
        PlcReadResponse readResponse = response.get();
        System.out.println("Response " + readResponse);
        Collection<Integer> stations = readResponse.getAllIntegers("station");
        stations.forEach(System.out::println);
        // 2. We build a subscription
        PlcSubscriptionRequest.Builder subscriptionRequestBuilder = plcConnection.subscriptionRequestBuilder();
        PlcSubscriptionRequest subscriptionRequest = subscriptionRequestBuilder.addChangeOfStateField("stationChange", "Allgemein_S2.Station:BYTE").addCyclicField("stationChange2", "Allgemein_S2.Station:BYTE", Duration.ofSeconds(3)).build();
        PlcSubscriptionResponse plcSubscriptionResponse = subscriptionRequest.execute().get();
        List<PlcConsumerRegistration> plcConsumerRegistrations = plcSubscriptionResponse.getSubscriptionHandles().stream().map(plcSubscriptionHandle -> plcSubscriptionHandle.register(plcSubscriptionEvent -> {
            int stationChange = plcSubscriptionEvent.getNumberOfValues("stationChange");
            int stationChange2 = plcSubscriptionEvent.getNumberOfValues("stationChange2");
            System.out.println(String.format("%s: [%d]- StationsNummer: {%d}", plcSubscriptionEvent.getTimestamp(), stationChange + stationChange2, plcSubscriptionEvent.getInteger("stationChange2")));
        })).collect(Collectors.toList());
        // Now we wait a bit
        TimeUnit.SECONDS.sleep(10);
        // we unregister the listener
        plcConsumerRegistrations.forEach(PlcConsumerRegistration::unregister);
        // we unsubscribe at the plc
        PlcUnsubscriptionRequest.Builder unsubscriptionRequestBuilder = plcConnection.unsubscriptionRequestBuilder();
        PlcUnsubscriptionRequest unsubscriptionRequest = unsubscriptionRequestBuilder.addHandles(plcSubscriptionResponse.getSubscriptionHandles()).build();
        CompletableFuture<PlcUnsubscriptionResponse> unsubscriptionResponse = unsubscriptionRequest.execute();
        unsubscriptionResponse.get(5, TimeUnit.SECONDS);
        System.out.println(unsubscriptionResponse);
    }
    System.exit(0);
}
Also used : PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) PlcConnection(org.apache.plc4x.java.api.PlcConnection) Duration(java.time.Duration) Collection(java.util.Collection) CompletableFuture(java.util.concurrent.CompletableFuture) PlcConsumerRegistration(org.apache.plc4x.java.api.model.PlcConsumerRegistration) Collectors(java.util.stream.Collectors) org.apache.plc4x.java.api.messages(org.apache.plc4x.java.api.messages) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcConsumerRegistration(org.apache.plc4x.java.api.model.PlcConsumerRegistration) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager)

Example 20 with PlcConnection

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

the class PassiveBacNetIpDriverManual method main.

public static void main(String[] args) throws Exception {
    final BacNetIpDriver driver = new BacNetIpDriver();
    final PlcConnection connection = driver.getConnection("bacnet-ip:pcap:///Users/christofer.dutz/Projects/Apache/PLC4X-Documents/BacNET/Merck/Captures/BACnet.pcapng?ede-directory-path=/Users/christofer.dutz/Projects/Apache/PLC4X-Documents/BacNET/Merck/EDE-Files");
    connection.connect();
    final PlcSubscriptionResponse subscriptionResponse = connection.subscriptionRequestBuilder().addEventField("Hurz", "*/*/*").build().execute().get();
    subscriptionResponse.getSubscriptionHandle("Hurz").register(plcSubscriptionEvent -> {
        PlcStruct plcStruct = (PlcStruct) ((DefaultPlcSubscriptionEvent) plcSubscriptionEvent).getValues().get("event").getValue();
        System.out.println(plcStruct);
    });
}
Also used : PlcSubscriptionResponse(org.apache.plc4x.java.api.messages.PlcSubscriptionResponse) PlcStruct(org.apache.plc4x.java.spi.values.PlcStruct) PlcConnection(org.apache.plc4x.java.api.PlcConnection)

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