Search in sources :

Example 1 with PlcConnectionException

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

the class Plc4xCommunication method setValue.

public void setValue(String tag, String value, String connectionString) {
    PlcConnection connection = null;
    try {
        connection = driverManager.getConnection(connectionString);
        if (connection.isConnected() == false) {
            logger.debug("getConnection() returned a connection that isn't connected");
            connection.connect();
        }
    } catch (PlcConnectionException e) {
        logger.warn("Failed" + e);
    }
    if (!connection.getMetadata().canWrite()) {
        logger.error("This connection doesn't support writing.");
        try {
            connection.close();
        } catch (Exception e) {
            logger.warn("Closing connection failed with error " + e);
        }
        return;
    }
    // Create a new read request:
    // - Give the single item requested an alias name
    final PlcWriteRequest.Builder builder = connection.writeRequestBuilder();
    // If an array value is passed instead of a single value then convert to a String array
    if ((value.charAt(0) == '[') && (value.charAt(value.length() - 1) == ']')) {
        String[] values = value.substring(1, value.length() - 1).split(",");
        logger.info("Adding Tag " + Arrays.toString(values));
        builder.addItem(tag, tag, values);
    } else {
        builder.addItem(tag, tag, value);
    }
    PlcWriteRequest writeRequest = builder.build();
    try {
        writeRequest.execute().get();
    } catch (InterruptedException | ExecutionException e) {
        logger.warn("Failed" + e);
    }
    try {
        connection.close();
    } catch (Exception e) {
        logger.warn("Closing Connection Failed with error " + e);
    }
    return;
}
Also used : PlcWriteRequest(org.apache.plc4x.java.api.messages.PlcWriteRequest) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) ExecutionException(java.util.concurrent.ExecutionException) 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)

Example 2 with PlcConnectionException

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

the class Plc4xNamespace method addConfiguredNodes.

private void addConfiguredNodes(UaFolderNode rootNode, DeviceConfiguration c) {
    final List<Tag> tags = c.getTags();
    final String connectionString = c.getConnectionString();
    for (int i = 0; i < tags.size(); i++) {
        logger.info("Adding Tag " + tags.get(i).getAlias() + " - " + tags.get(i).getAddress());
        String name = tags.get(i).getAlias();
        final String tag = tags.get(i).getAddress();
        Class datatype = null;
        NodeId typeId = Identifiers.String;
        UaVariableNode node = null;
        Variant variant = null;
        try {
            datatype = plc4xServer.getField(tag, connectionString).getDefaultJavaType();
            final int length = plc4xServer.getField(tag, connectionString).getNumberOfElements();
            typeId = Plc4xCommunication.getNodeId(plc4xServer.getField(tag, connectionString).getPlcDataType());
            if (length > 1) {
                node = new UaVariableNode.UaVariableNodeBuilder(getNodeContext()).setNodeId(newNodeId(name)).setAccessLevel(AccessLevel.READ_WRITE).setUserAccessLevel(AccessLevel.READ_WRITE).setBrowseName(newQualifiedName(name)).setDisplayName(LocalizedText.english(name)).setDataType(typeId).setTypeDefinition(Identifiers.BaseDataVariableType).setValueRank(ValueRank.OneDimension.getValue()).setArrayDimensions(new UInteger[] { uint(length) }).build();
                Object array = Array.newInstance(datatype, length);
                for (int j = 0; j < length; j++) {
                    Array.set(array, j, false);
                }
                variant = new Variant(array);
            } else {
                node = new UaVariableNode.UaVariableNodeBuilder(getNodeContext()).setNodeId(newNodeId(name)).setAccessLevel(AccessLevel.READ_WRITE).setUserAccessLevel(AccessLevel.READ_WRITE).setBrowseName(newQualifiedName(name)).setDisplayName(LocalizedText.english(name)).setDataType(typeId).setTypeDefinition(Identifiers.BaseDataVariableType).build();
                variant = new Variant(0);
            }
            node.setValue(new DataValue(variant));
            node.getFilterChain().addLast(AttributeFilters.getValue(ctx -> plc4xServer.getValue(ctx, tag, connectionString)));
            node.getFilterChain().addLast(AttributeFilters.setValue((ctx, value) -> {
                if (length > 1) {
                    plc4xServer.setValue(tag, Arrays.toString((Object[]) value.getValue().getValue()), connectionString);
                } else {
                    plc4xServer.setValue(tag, value.getValue().getValue().toString(), connectionString);
                }
            }));
        } catch (PlcConnectionException e) {
            logger.info("Couldn't find data type");
            System.exit(1);
        }
        getNodeManager().addNode(node);
        rootNode.addOrganizes(node);
    }
}
Also used : Arrays(java.util.Arrays) Array(java.lang.reflect.Array) DataValue(org.eclipse.milo.opcua.stack.core.types.builtin.DataValue) DataItem(org.eclipse.milo.opcua.sdk.server.api.DataItem) LoggerFactory(org.slf4j.LoggerFactory) ManagedNamespaceWithLifecycle(org.eclipse.milo.opcua.sdk.server.api.ManagedNamespaceWithLifecycle) UaFolderNode(org.eclipse.milo.opcua.sdk.server.nodes.UaFolderNode) ValueRank(org.eclipse.milo.opcua.sdk.core.ValueRank) AccessLevel(org.eclipse.milo.opcua.sdk.core.AccessLevel) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) Tag(org.apache.plc4x.java.opcuaserver.configuration.Tag) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) AttributeFilters(org.eclipse.milo.opcua.sdk.server.nodes.filters.AttributeFilters) PooledPlcDriverManager(org.apache.plc4x.java.utils.connectionpool.PooledPlcDriverManager) Reference(org.eclipse.milo.opcua.sdk.core.Reference) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) Logger(org.slf4j.Logger) UaVariableNode(org.eclipse.milo.opcua.sdk.server.nodes.UaVariableNode) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) LocalizedText(org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText) SubscriptionModel(org.eclipse.milo.opcua.sdk.server.util.SubscriptionModel) OpcUaServer(org.eclipse.milo.opcua.sdk.server.OpcUaServer) MonitoredItem(org.eclipse.milo.opcua.sdk.server.api.MonitoredItem) List(java.util.List) Configuration(org.apache.plc4x.java.opcuaserver.configuration.Configuration) Variant(org.eclipse.milo.opcua.stack.core.types.builtin.Variant) DeviceConfiguration(org.apache.plc4x.java.opcuaserver.configuration.DeviceConfiguration) DataTypeDictionaryManager(org.eclipse.milo.opcua.sdk.server.dtd.DataTypeDictionaryManager) Identifiers(org.eclipse.milo.opcua.stack.core.Identifiers) DataValue(org.eclipse.milo.opcua.stack.core.types.builtin.DataValue) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) Variant(org.eclipse.milo.opcua.stack.core.types.builtin.Variant) UaVariableNode(org.eclipse.milo.opcua.sdk.server.nodes.UaVariableNode) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) Tag(org.apache.plc4x.java.opcuaserver.configuration.Tag) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException)

Example 3 with PlcConnectionException

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

the class OpcuaPlcDriver method getConnection.

@Override
public PlcConnection getConnection(String connectionString) throws PlcConnectionException {
    // Split up the connection string into it's individual segments.
    Matcher matcher = URI_PATTERN.matcher(connectionString);
    if (!matcher.matches()) {
        throw new PlcConnectionException("Connection string doesn't match the format '{protocol-code}:({transport-code})?//{transport-host}(:{transport-port})(/{transport-endpoint})(?{parameter-string)?'");
    }
    final String protocolCode = matcher.group("protocolCode");
    final String transportCode = (matcher.group("transportCode") != null) ? matcher.group("transportCode") : getDefaultTransport();
    final String transportHost = matcher.group("transportHost");
    final String transportPort = matcher.group("transportPort");
    final String transportEndpoint = matcher.group("transportEndpoint");
    final String paramString = matcher.group("paramString");
    // Check if the protocol code matches this driver.
    if (!protocolCode.equals(getProtocolCode())) {
        // Actually this shouldn't happen as the DriverManager should have not used this driver in the first place.
        throw new PlcConnectionException("This driver is not suited to handle this connection string");
    }
    // Create the configuration object.
    OpcuaConfiguration configuration = (OpcuaConfiguration) new ConfigurationFactory().createConfiguration(getConfigurationType(), paramString);
    if (configuration == null) {
        throw new PlcConnectionException("Unsupported configuration");
    }
    configuration.setTransportCode(transportCode);
    configuration.setHost(transportHost);
    configuration.setPort(transportPort);
    configuration.setTransportEndpoint(transportEndpoint);
    configuration.setEndpoint("opc." + transportCode + "://" + transportHost + ":" + transportPort + "" + transportEndpoint);
    // Try to find a transport in order to create a communication channel.
    Transport transport = null;
    ServiceLoader<Transport> transportLoader = ServiceLoader.load(Transport.class, Thread.currentThread().getContextClassLoader());
    for (Transport curTransport : transportLoader) {
        if (curTransport.getTransportCode().equals(transportCode)) {
            transport = curTransport;
            break;
        }
    }
    if (transport == null) {
        throw new PlcConnectionException("Unsupported transport " + transportCode);
    }
    // Inject the configuration into the transport.
    configure(configuration, transport);
    // Create an instance of the communication channel which the driver should use.
    ChannelFactory channelFactory = transport.createChannelFactory(transportHost + ":" + transportPort);
    if (channelFactory == null) {
        throw new PlcConnectionException("Unable to get channel factory from url " + transportHost + ":" + transportPort);
    }
    configure(configuration, channelFactory);
    // Give drivers the option to customize the channel.
    initializePipeline(channelFactory);
    // Make the "await setup complete" overridable via system property.
    boolean awaitSetupComplete = awaitSetupComplete();
    if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE) != null) {
        awaitSetupComplete = Boolean.parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE));
    }
    // Make the "await disconnect complete" overridable via system property.
    boolean awaitDisconnectComplete = awaitDisconnectComplete();
    if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE) != null) {
        awaitDisconnectComplete = Boolean.parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE));
    }
    if (configuration.getSecurityPolicy() != null && !(configuration.getSecurityPolicy().equals("None"))) {
        try {
            configuration.openKeyStore();
        } catch (Exception e) {
            throw new PlcConnectionException("Unable to open keystore, please confirm you have the correct permissions");
        }
    }
    this.isEncrypted = configuration.isEncrypted();
    // Make the "await disconnect complete" overridable via system property.
    boolean awaitDiscoverComplete = awaitDiscoverComplete();
    if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCOVER_COMPLETE) != null) {
        awaitDiscoverComplete = Boolean.parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCOVER_COMPLETE));
    }
    return new DefaultNettyPlcConnection(canRead(), canWrite(), canSubscribe(), getFieldHandler(), getValueHandler(), configuration, channelFactory, awaitSetupComplete, awaitDisconnectComplete, awaitDiscoverComplete, getStackConfigurer(), getOptimizer());
}
Also used : Matcher(java.util.regex.Matcher) ConfigurationFactory(org.apache.plc4x.java.spi.configuration.ConfigurationFactory) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) Transport(org.apache.plc4x.java.spi.transport.Transport) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException)

Example 4 with PlcConnectionException

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

the class OpcuaConfiguration method openKeyStore.

public void openKeyStore() throws Exception {
    this.isEncrypted = true;
    File securityTempDir = new File(certDirectory, "security");
    if (!securityTempDir.exists() && !securityTempDir.mkdirs()) {
        throw new PlcConnectionException("Unable to create directory please confirm folder permissions on " + certDirectory);
    }
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    File serverKeyStore = securityTempDir.toPath().resolve(keyStoreFile).toFile();
    File pkiDir = FileSystems.getDefault().getPath(certDirectory).resolve("pki").toFile();
    if (!serverKeyStore.exists()) {
        ckp = CertificateGenerator.generateCertificate();
        LOGGER.info("Creating new KeyStore at {}", serverKeyStore);
        keyStore.load(null, keyStorePassword.toCharArray());
        keyStore.setKeyEntry("plc4x-certificate-alias", ckp.getKeyPair().getPrivate(), keyStorePassword.toCharArray(), new X509Certificate[] { ckp.getCertificate() });
        keyStore.store(new FileOutputStream(serverKeyStore), keyStorePassword.toCharArray());
    } else {
        LOGGER.info("Loading KeyStore at {}", serverKeyStore);
        keyStore.load(new FileInputStream(serverKeyStore), keyStorePassword.toCharArray());
        String alias = keyStore.aliases().nextElement();
        KeyPair kp = new KeyPair(keyStore.getCertificate(alias).getPublicKey(), (PrivateKey) keyStore.getKey(alias, keyStorePassword.toCharArray()));
        ckp = new CertificateKeyPair(kp, (X509Certificate) keyStore.getCertificate(alias));
    }
}
Also used : CertificateKeyPair(org.apache.plc4x.java.opcua.context.CertificateKeyPair) CertificateKeyPair(org.apache.plc4x.java.opcua.context.CertificateKeyPair) FileOutputStream(java.io.FileOutputStream) PascalByteString(org.apache.plc4x.java.opcua.readwrite.PascalByteString) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) File(java.io.File) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate)

Example 5 with PlcConnectionException

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

the class OpcuaPlcDriverTest method connectionWithDiscoveryParam.

@Test
public void connectionWithDiscoveryParam() {
    connectionStringValidSet.forEach(connectionAddress -> {
        discoveryParamValidSet.forEach(discoveryParam -> {
            String connectionString = connectionAddress + paramSectionDivider + discoveryParam;
            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 connectionWithDiscoveryParam while connecting Test EXCEPTION: " + e.getMessage());
            } catch (Exception e) {
                fail("Exception during connectionWithDiscoveryParam 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)

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