You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by hu...@apache.org on 2020/12/23 17:16:13 UTC

[plc4x] 01/02: Initial

This is an automated email from the ASF dual-hosted git repository.

hutcheb pushed a commit to branch feature/native_opua_client
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 670db4864f95806bc5075b69655c796e4615109e
Author: hutcheb <be...@gmail.com>
AuthorDate: Wed Dec 23 11:21:45 2020 -0500

    Initial
---
 .../resources/templates/java/pojo-template.ftlh    |   4 +-
 plc4j/drivers/opcua/pom.xml                        |  28 ++++++
 .../apache/plc4x/java/opcua/OpcuaPlcDriver.java    |  95 +++++++++++++++----
 .../java/opcua/config/OpcuaConfiguration.java      |  41 ++++++++
 .../java/opcua/protocol/OpcuaProtocolLogic.java    | 104 +++++++++++++++++++++
 .../plc4x/java/spi/generation/WriteBuffer.java     |   7 ++
 .../src/main/resources/protocols/opcua/opcua.mspec |  35 ++++++-
 7 files changed, 291 insertions(+), 23 deletions(-)

diff --git a/build-utils/language-java/src/main/resources/templates/java/pojo-template.ftlh b/build-utils/language-java/src/main/resources/templates/java/pojo-template.ftlh
index 7e1dd9f..a1647cf 100644
--- a/build-utils/language-java/src/main/resources/templates/java/pojo-template.ftlh
+++ b/build-utils/language-java/src/main/resources/templates/java/pojo-template.ftlh
@@ -95,7 +95,7 @@ public<#if helper.isDiscriminatedParentTypeDefinition()> abstract</#if> class ${
         <#if !helper.isNonDiscriminatorField(discriminatorName)>
     @JsonIgnore
     public ${helper.getLanguageTypeNameForTypeReference(helper.getDiscriminatorTypes()[discriminatorName])} get${discriminatorName?cap_first}() {
-        return <#if discriminatorValue??>${discriminatorValue}<#else>${helper.getNullValueForTypeReference(helper.getDiscriminatorTypes()[discriminatorName])}</#if>;
+        return <#if discriminatorValue??>${helper.escapeValue(helper.getDiscriminatorTypes()[discriminatorName],discriminatorValue)}<#else>${helper.getNullValueForTypeReference(helper.getDiscriminatorTypes()[discriminatorName])}</#if>;
     }
         </#if>
     </#list>
@@ -357,4 +357,4 @@ public<#if helper.isDiscriminatedParentTypeDefinition()> abstract</#if> class ${
     }
 
 }
-</#outputformat>
\ No newline at end of file
+</#outputformat>
diff --git a/plc4j/drivers/opcua/pom.xml b/plc4j/drivers/opcua/pom.xml
index 9a92469..665ba90 100644
--- a/plc4j/drivers/opcua/pom.xml
+++ b/plc4j/drivers/opcua/pom.xml
@@ -103,6 +103,8 @@
         <artifactId>maven-dependency-plugin</artifactId>
         <configuration>
           <usedDependencies combine.children="append">
+              <usedDependency>org.apache.plc4x:plc4j-transport-serial</usedDependency>
+              <usedDependency>org.apache.plc4x:plc4j-transport-raw-socket</usedDependency>
             <usedDependency>org.apache.plc4x:plc4x-build-utils-language-java</usedDependency>
             <usedDependency>org.apache.plc4x:plc4x-protocols-opcua</usedDependency>
           </usedDependencies>
@@ -112,6 +114,28 @@
   </build>
 
   <dependencies>
+      <dependency>
+        <groupId>io.netty</groupId>
+        <artifactId>netty-buffer</artifactId>
+      </dependency>
+
+      <dependency>
+        <groupId>org.apache.plc4x</groupId>
+        <artifactId>plc4j-transport-tcp</artifactId>
+        <version>0.8.0-SNAPSHOT</version>
+      </dependency>
+      <dependency>
+        <groupId>org.apache.plc4x</groupId>
+        <artifactId>plc4j-transport-serial</artifactId>
+        <version>0.8.0-SNAPSHOT</version>
+      </dependency>
+      <dependency>
+        <groupId>org.apache.plc4x</groupId>
+        <artifactId>plc4j-transport-raw-socket</artifactId>
+        <version>0.8.0-SNAPSHOT</version>
+      </dependency>
+
+
     <dependency>
       <groupId>org.apache.plc4x</groupId>
       <artifactId>plc4j-api</artifactId>
@@ -175,6 +199,10 @@
     <type>test-jar</type>
     <scope>test</scope>
   </dependency>
+  <dependency>
+    <groupId>com.fasterxml.jackson.core</groupId>
+    <artifactId>jackson-annotations</artifactId>
+  </dependency>
   </dependencies>
 
   <dependencyManagement>
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java
index 4403142..c38a148 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java
@@ -24,13 +24,28 @@ import org.apache.plc4x.java.api.authentication.PlcAuthentication;
 import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
 import org.apache.plc4x.java.opcua.connection.OpcuaConnectionFactory;
 import org.apache.plc4x.java.api.PlcDriver;
-import org.apache.plc4x.java.opcua.protocol.OpcuaField;
+import org.apache.plc4x.java.opcua.protocol.*;
+import org.apache.plc4x.java.opcua.config.*;
+import org.apache.plc4x.java.opcua.readwrite.*;
+import org.apache.plc4x.java.opcua.readwrite.io.*;
+import org.apache.plc4x.java.opcua.readwrite.types.*;
+import org.apache.plc4x.java.spi.connection.GeneratedDriverBase;
+import org.apache.plc4x.java.spi.values.IEC61131ValueHandler;
+import org.apache.plc4x.java.api.value.PlcValueHandler;
+import org.apache.plc4x.java.spi.configuration.Configuration;
+import org.apache.plc4x.java.spi.connection.GeneratedDriverBase;
+import org.apache.plc4x.java.spi.connection.ProtocolStackConfigurer;
+import org.apache.plc4x.java.spi.connection.SingleProtocolStackConfigurer;
+import org.apache.plc4x.java.spi.optimizer.BaseOptimizer;
+import org.apache.plc4x.java.spi.optimizer.SingleFieldOptimizer;
+import io.netty.buffer.ByteBuf;
 
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import java.util.function.ToIntFunction;
 
 /**
  * Implementation of the OPC UA protocol, based on:
@@ -38,7 +53,7 @@ import java.util.regex.Pattern;
  *
  * Created by Matthias Milan Strljic on 10.05.2019
  */
-public class OpcuaPlcDriver implements PlcDriver {
+public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
 
 
     public static final Pattern INET_ADDRESS_PATTERN = Pattern.compile("(:(?<transport>tcp))?://(?<host>[\\w.-]+)(:(?<port>\\d*))?");
@@ -55,33 +70,73 @@ public class OpcuaPlcDriver implements PlcDriver {
 
     @Override
     public String getProtocolName() {
-        return "OPC UA (TCP)";
+        return "Opcua";
     }
 
     @Override
-    public PlcConnection getConnection(String url) throws PlcConnectionException {
-        Matcher matcher = OPCUA_URI_PATTERN.matcher(url);
+    protected Class<? extends Configuration> getConfigurationType() {
+        return OpcuaConfiguration.class;
+    }
 
-        if (!matcher.matches()) {
-            throw new PlcConnectionException(
-                "Connection url doesn't match the format 'opcua:{type}//{host|port}'");
-        }
+    @Override
+    protected String getDefaultTransport() {
+        return "tcp";
+    }
+
+    /**
+     * Modbus doesn't have a login procedure, so there is no need to wait for a login to finish.
+     * @return false
+     */
+    @Override
+    protected boolean awaitSetupComplete() {
+        return true;
+    }
 
-        String host = matcher.group("host");
-        String portString = matcher.group("port");
-        Integer port = StringUtils.isNotBlank(portString) ? Integer.parseInt(portString) : null;
-        String params = matcher.group("params") != null ? matcher.group("params").substring(1) : "";
+    @Override
+    protected boolean canRead() {
+        return true;
+    }
 
-        try {
-            return opcuaConnectionFactory.opcuaTcpPlcConnectionOf(InetAddress.getByName(host), port, params, requestTimeout);
-        } catch (UnknownHostException e) {
-            throw new PlcConnectionException(e);
-        }
+    @Override
+    protected boolean canWrite() {
+        return true;
     }
 
     @Override
-    public PlcConnection getConnection(String url, PlcAuthentication authentication) throws PlcConnectionException {
-        throw new PlcConnectionException("opcua does not support Auth at this state");
+    protected BaseOptimizer getOptimizer() {
+        return new SingleFieldOptimizer();
+    }
+
+    @Override
+    protected OpcuaPlcFieldHandler getFieldHandler() {
+        return new OpcuaPlcFieldHandler();
+    }
+
+    @Override
+    protected PlcValueHandler getValueHandler() {
+        return new IEC61131ValueHandler();
+    }
+
+    @Override
+    protected ProtocolStackConfigurer<OpcuaAPU> getStackConfigurer() {
+        return SingleProtocolStackConfigurer.builder(OpcuaAPU.class, OpcuaAPUIO.class)
+            .withProtocol(OpcuaProtocolLogic.class)
+            .withPacketSizeEstimator(ByteLengthEstimator.class)
+            // Every incoming message is to be treated as a response.
+            .withParserArgs(true)
+            .littleEndian()
+            .build();
+    }
+
+    /** Estimate the Length of a Packet */
+    public static class ByteLengthEstimator implements ToIntFunction<ByteBuf> {
+        @Override
+        public int applyAsInt(ByteBuf byteBuf) {
+            if (byteBuf.readableBytes() >= 6) {
+                return byteBuf.getUnsignedShort(byteBuf.readerIndex() + 256) + 6;
+            }
+            return -1;
+        }
     }
 
     @Override
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java
new file mode 100644
index 0000000..bff0452
--- /dev/null
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java
@@ -0,0 +1,41 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.java.opcua.config;
+
+
+import org.apache.plc4x.java.spi.configuration.Configuration;
+import org.apache.plc4x.java.spi.configuration.annotations.ConfigurationParameter;
+import org.apache.plc4x.java.spi.configuration.annotations.defaults.IntDefaultValue;
+import org.apache.plc4x.java.transport.tcp.TcpTransportConfiguration;
+
+public class OpcuaConfiguration implements Configuration, TcpTransportConfiguration {
+
+
+    @Override
+    public int getDefaultPort() {
+        return 12687;
+    }
+
+    @Override
+    public String toString() {
+        return "Configuration{" +
+            '}';
+    }
+
+}
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java
new file mode 100644
index 0000000..8447e4b
--- /dev/null
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.plc4x.java.opcua.protocol;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import org.apache.plc4x.java.api.exceptions.PlcProtocolException;
+import org.apache.plc4x.java.api.exceptions.PlcRuntimeException;
+import org.apache.plc4x.java.api.messages.PlcReadRequest;
+import org.apache.plc4x.java.api.messages.PlcReadResponse;
+import org.apache.plc4x.java.api.messages.PlcResponse;
+import org.apache.plc4x.java.api.messages.PlcWriteRequest;
+import org.apache.plc4x.java.api.messages.PlcWriteResponse;
+import org.apache.plc4x.java.api.model.PlcField;
+import org.apache.plc4x.java.api.types.PlcResponseCode;
+import org.apache.plc4x.java.spi.values.PlcNull;
+import org.apache.plc4x.java.api.value.PlcValue;
+import org.apache.plc4x.java.spi.values.IEC61131ValueHandler;
+import org.apache.plc4x.java.opcua.readwrite.*;
+import org.apache.plc4x.java.opcua.readwrite.io.*;
+import org.apache.plc4x.java.opcua.readwrite.types.*;
+import org.apache.plc4x.java.spi.ConversationContext;
+import org.apache.plc4x.java.spi.Plc4xProtocolBase;
+import org.apache.plc4x.java.spi.context.DriverContext;
+import org.apache.plc4x.java.spi.generation.ParseException;
+import org.apache.plc4x.java.spi.generation.ReadBuffer;
+import org.apache.plc4x.java.spi.generation.WriteBuffer;
+import org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest;
+import org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse;
+import org.apache.plc4x.java.spi.messages.DefaultPlcWriteRequest;
+import org.apache.plc4x.java.spi.messages.DefaultPlcWriteResponse;
+import org.apache.plc4x.java.spi.messages.utils.ResponseItem;
+import org.apache.plc4x.java.spi.transaction.RequestTransactionManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.UnsupportedEncodingException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.IntStream;
+import java.nio.charset.StandardCharsets;
+
+/**
+ * The S7 Protocol states that there can not be more then {min(maxAmqCaller, maxAmqCallee} "ongoing" requests.
+ * So we need to limit those.
+ * Thus, each request goes to a Work Queue and this Queue ensures, that only 3 are open at the same time.
+ */
+public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(OpcuaProtocolLogic.class);
+    public static final Duration REQUEST_TIMEOUT = Duration.ofMillis(10000);
+
+    private final AtomicInteger tpduGenerator = new AtomicInteger(10);
+    private RequestTransactionManager tm;
+
+    @Override
+    public void close(ConversationContext<OpcuaAPU> context) {
+        // Nothing to do here ...
+    }
+
+    @Override
+    public void onConnect(ConversationContext<OpcuaAPU> context) {
+        // Only the TCP transport supports login.
+        LOGGER.info("Opcua Driver running in ACTIVE mode.");
+        // Open the session on ISO Transport Protocol first.
+
+        OpcUAMessageHelloRequest hello = null;
+        //try {
+            hello = new OpcUAMessageHelloRequest("F", 63, 0, 65535, 65535, 2097152, 64,  new String("opc.tcp://127.0.0.1:12687/plc4x"));
+        //} catch (UnsupportedEncodingException e) {
+        //    LOGGER.info("Excpetion Occurred.");
+        //}
+
+        context.sendRequest(new OpcuaAPU(hello))
+            .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
+            .check(p -> p.getMessage() instanceof OpcUAMessageHelloResponse)
+            .unwrap(p -> (OpcUAMessageHelloResponse) p.getMessage())
+            .handle(opcuaMessageHelloResponse -> {
+                LOGGER.debug("Got Hello Response Connection Response");
+            });
+    }
+
+}
diff --git a/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/generation/WriteBuffer.java b/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/generation/WriteBuffer.java
index 9891f64..79285ea 100644
--- a/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/generation/WriteBuffer.java
+++ b/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/generation/WriteBuffer.java
@@ -191,6 +191,10 @@ public class WriteBuffer {
     }
 
     public void writeInt(int bitLength, int value) throws ParseException {
+        System.out.println(bitLength);
+        System.out.println(value);
+        System.out.println(getData().length);
+        System.out.println(getPos());
         if(bitLength <= 0) {
             throw new ParseException("int must contain at least 1 bit");
         }
@@ -256,7 +260,10 @@ public class WriteBuffer {
     public void writeString(int bitLength, String encoding, String value) throws ParseException {
         final byte[] bytes = value.getBytes(Charset.forName(encoding));
         try {
+            int count = 0;
             for (byte aByte : bytes) {
+                System.out.println(count);
+                count += 1;
                 bo.writeByte(false, 8, aByte);
             }
         } catch (IOException e) {
diff --git a/protocols/opcua/src/main/resources/protocols/opcua/opcua.mspec b/protocols/opcua/src/main/resources/protocols/opcua/opcua.mspec
index b715a6a..96b521b 100644
--- a/protocols/opcua/src/main/resources/protocols/opcua/opcua.mspec
+++ b/protocols/opcua/src/main/resources/protocols/opcua/opcua.mspec
@@ -17,7 +17,40 @@
 // under the License.
 //
 
-// Remark: The different fields are encoded in Big-endian.
+// Remark: The different fields are encoded in Little-endian.
+
+[type 'OpcuaAPU' [bit 'response']
+    [simple         MessagePDU   'message' ['response']]
+]
+
+[discriminatedType 'MessagePDU' [bit 'response']
+    [discriminator string 24          'messageType']
+    [typeSwitch 'messageType','response'
+        // HEL Request
+        ['HEL','false'     OpcUAMessageHelloRequest
+            [simple          string 8            'chunk']
+            [simple          int 32              'messageSize']
+            [simple          int 32             'version']
+            [simple          int 32             'receiveBufferSize']
+            [simple          int 32             'sendBufferSize']
+            [simple          int 32             'maxMessageSize']
+            [simple          int 32             'maxChunkCount']
+            [simple          string 256         'endpoint']
+        ]
+        // HEL Response
+        ['HEL','true'     OpcUAMessageHelloResponse
+            [simple          string 1            'chunk']
+            [simple          int 32             'messageSize']
+            [simple          int 32             'version']
+            [simple          int 32             'receiveBufferSize']
+            [simple          int 32             'sendBufferSize']
+            [simple          int 32             'maxMessageSize']
+            [simple          int 32             'maxChunkCount']
+        ]
+    ]
+]
+
+
 
 [enum string 'OpcuaDataType'
     ['IEC61131_NULL' NULL ]