Search in sources :

Example 6 with PlcConnectionException

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

the class OpcuaPlcDriverTest method connectionNoParams.

@Test
public void connectionNoParams() {
    connectionStringValidSet.forEach(connectionString -> {
        try {
            PlcConnection opcuaConnection = new PlcDriverManager().getConnection(connectionString);
            Condition<PlcConnection> is_connected = new Condition<>(PlcConnection::isConnected, "is connected");
            assertThat(opcuaConnection).is(is_connected);
            opcuaConnection.close();
            assertThat(opcuaConnection).isNot(is_connected);
        } catch (PlcConnectionException e) {
            fail("Exception during connectionNoParams while connecting Test EXCEPTION: " + e.getMessage());
        } catch (Exception e) {
            fail("Exception during connectionNoParams while closing Test EXCEPTION: " + e.getMessage());
        }
    });
}
Also used : Condition(org.assertj.core.api.Condition) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection) ExecutionException(java.util.concurrent.ExecutionException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException)

Example 7 with PlcConnectionException

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

the class SimulatedDriver method getConnection.

@Override
public PlcConnection getConnection(String url) throws PlcConnectionException {
    // TODO: perform further checks
    String deviceName = url.substring(getProtocolCode().length() + 1);
    if (deviceName.isEmpty()) {
        throw new PlcConnectionException("Invalid URL: no device name given.");
    }
    SimulatedDevice device = new SimulatedDevice(deviceName);
    return new SimulatedConnection(device);
}
Also used : SimulatedConnection(org.apache.plc4x.java.simulated.connection.SimulatedConnection) SimulatedDevice(org.apache.plc4x.java.simulated.connection.SimulatedDevice) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException)

Example 8 with PlcConnectionException

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

the class WaterTankService method connectToDevice.

protected void connectToDevice() {
    try {
        // Connect to the device
        connection = new PlcDriverManager().getConnection(connectionString);
        // Check if subscriptions are supported by this connection.
        if (!connection.getMetadata().canSubscribe()) {
            throw new PlcRuntimeException("This driver doesn't support subscribing");
        }
        // Prepare a subscription request.
        final PlcSubscriptionRequest subscriptionRequest = connection.subscriptionRequestBuilder().addChangeOfStateField(WATER_LEVEL, addressStringWaterLevel).build();
        // Execute the request.
        PlcSubscriptionResponse syncResponse = subscriptionRequest.execute().get();
        // Attach handlers for the incoming data.
        for (String subscriptionName : syncResponse.getFieldNames()) {
            final PlcSubscriptionHandle subscriptionHandle = syncResponse.getSubscriptionHandle(subscriptionName);
            subscriptionHandle.register(new WaterLevelHandler());
        }
    } catch (PlcConnectionException e) {
        throw new PlcRuntimeException("Error connecting to device", e);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new PlcRuntimeException("Error subscribing for data", e);
    } catch (ExecutionException e) {
        throw new PlcRuntimeException("Error subscribing for data", e);
    }
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcSubscriptionRequest(org.apache.plc4x.java.api.messages.PlcSubscriptionRequest) PlcSubscriptionResponse(org.apache.plc4x.java.api.messages.PlcSubscriptionResponse) PlcSubscriptionHandle(org.apache.plc4x.java.api.model.PlcSubscriptionHandle) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) ExecutionException(java.util.concurrent.ExecutionException) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager)

Example 9 with PlcConnectionException

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

the class PlcEntityManagerComplexTest method getPlcEntityManager.

private PlcEntityManager getPlcEntityManager(final Map<String, PlcValue> responses) throws PlcConnectionException {
    driverManager = Mockito.mock(PlcDriverManager.class);
    PlcDriverManager mock = driverManager;
    PlcConnection connection = Mockito.mock(PlcConnection.class);
    when(mock.getConnection(ArgumentMatchers.anyString())).thenReturn(connection);
    when(connection.getMetadata()).thenReturn(new PlcConnectionMetadata() {

        @Override
        public boolean canRead() {
            return true;
        }

        @Override
        public boolean canWrite() {
            return true;
        }

        @Override
        public boolean canSubscribe() {
            return true;
        }
    });
    PlcReader reader = readRequest -> {
        Map<String, ResponseItem<PlcValue>> map = readRequest.getFieldNames().stream().collect(Collectors.toMap(Function.identity(), s -> new ResponseItem<>(PlcResponseCode.OK, Objects.requireNonNull(responses.get(s), s + " not found"))));
        return CompletableFuture.completedFuture(new DefaultPlcReadResponse(readRequest, map));
    };
    when(connection.readRequestBuilder()).then(invocation -> new DefaultPlcReadRequest.Builder(reader, getFieldHandler()));
    PlcWriter writer = writeRequest -> {
        Map<String, PlcResponseCode> map = writeRequest.getFieldNames().stream().collect(Collectors.toMap(Function.identity(), s -> PlcResponseCode.OK));
        return CompletableFuture.completedFuture(new DefaultPlcWriteResponse(writeRequest, map));
    };
    when(connection.writeRequestBuilder()).then(invocation -> new DefaultPlcWriteRequest.Builder(writer, getFieldHandler(), getValueHandler()));
    return new PlcEntityManager(mock);
}
Also used : PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) org.apache.plc4x.java.api.value(org.apache.plc4x.java.api.value) Arrays(java.util.Arrays) ArgumentMatchers(org.mockito.ArgumentMatchers) PlcConnection(org.apache.plc4x.java.api.PlcConnection) LocalDateTime(java.time.LocalDateTime) WithAssertions(org.assertj.core.api.WithAssertions) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Disabled(org.junit.jupiter.api.Disabled) Function(java.util.function.Function) DefaultPlcReadResponse(org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse) PlcFieldHandler(org.apache.plc4x.java.spi.connection.PlcFieldHandler) PlcInvalidFieldException(org.apache.plc4x.java.api.exceptions.PlcInvalidFieldException) PlcDINT(org.apache.plc4x.java.spi.values.PlcDINT) BigDecimal(java.math.BigDecimal) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) Map(java.util.Map) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) LocalTime(java.time.LocalTime) FieldUtils(org.apache.commons.lang3.reflect.FieldUtils) BigInteger(java.math.BigInteger) PlcLINT(org.apache.plc4x.java.spi.values.PlcLINT) PlcConnectionMetadata(org.apache.plc4x.java.api.metadata.PlcConnectionMetadata) PlcReader(org.apache.plc4x.java.spi.messages.PlcReader) Mockito.when(org.mockito.Mockito.when) Collectors(java.util.stream.Collectors) IEC61131ValueHandler(org.apache.plc4x.java.spi.values.IEC61131ValueHandler) Test(org.junit.jupiter.api.Test) Objects(java.util.Objects) Mockito(org.mockito.Mockito) PlcWriter(org.apache.plc4x.java.spi.messages.PlcWriter) LocalDate(java.time.LocalDate) Assertions(org.junit.jupiter.api.Assertions) DefaultPlcWriteRequest(org.apache.plc4x.java.spi.messages.DefaultPlcWriteRequest) DefaultPlcReadRequest(org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest) ResponseItem(org.apache.plc4x.java.spi.messages.utils.ResponseItem) PlcWriter(org.apache.plc4x.java.spi.messages.PlcWriter) DefaultPlcWriteRequest(org.apache.plc4x.java.spi.messages.DefaultPlcWriteRequest) PlcConnection(org.apache.plc4x.java.api.PlcConnection) DefaultPlcWriteResponse(org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse) PlcConnectionMetadata(org.apache.plc4x.java.api.metadata.PlcConnectionMetadata) DefaultPlcReadRequest(org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest) DefaultPlcReadResponse(org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) HashMap(java.util.HashMap) Map(java.util.Map) PlcReader(org.apache.plc4x.java.spi.messages.PlcReader)

Example 10 with PlcConnectionException

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

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