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 2021/05/11 10:18:22 UTC
[plc4x] 01/02: Split a SecureChannel class out to better control
the ordering of messages.
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 15d520ad55c110064bfe0c3d6b8a43c0da8afb89
Author: hutcheb <be...@gmail.com>
AuthorDate: Fri May 7 06:29:45 2021 -0400
Split a SecureChannel class out to better control the ordering of messages.
---
.../plc4x/java/opcua/context/SecureChannel.java | 51 +++-
.../java/opcua/protocol/OpcuaProtocolLogic.java | 290 ++++++++++-----------
.../opcua/protocol/OpcuaSubscriptionHandle.java | 96 +++----
3 files changed, 241 insertions(+), 196 deletions(-)
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/SecureChannel.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/SecureChannel.java
index caedd59..83cf9ba 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/SecureChannel.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/SecureChannel.java
@@ -1,3 +1,22 @@
+/*
+ * 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.context;
import io.netty.util.concurrent.CompleteFuture;
@@ -5,6 +24,8 @@ import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
import org.apache.plc4x.java.api.exceptions.PlcRuntimeException;
+import org.apache.plc4x.java.api.messages.PlcFieldResponse;
+import org.apache.plc4x.java.api.messages.PlcReadResponse;
import org.apache.plc4x.java.opcua.config.OpcuaConfiguration;
import org.apache.plc4x.java.opcua.protocol.OpcuaSubscriptionHandle;
import org.apache.plc4x.java.opcua.readwrite.*;
@@ -17,6 +38,7 @@ 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.DefaultPlcReadResponse;
import org.apache.plc4x.java.spi.transaction.RequestTransactionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -28,7 +50,11 @@ import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.time.Duration;
import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
public class SecureChannel {
@@ -97,6 +123,7 @@ public class SecureChannel {
private RequestTransactionManager tm = new RequestTransactionManager(1);
private NodeIdTypeDefinition authenticationToken = new NodeIdTwoByte((short) 0);
private DriverContext driverContext;
+ ConversationContext<OpcuaAPU> context;
private Boolean isConnected;
@@ -138,10 +165,32 @@ public class SecureChannel {
}
+ public void submit(Consumer<TimeoutException> onTimeout, BiConsumer<OpcuaAPU, Throwable> error, Consumer<OpcuaMessageResponse> consumer, WriteBuffer buffer) {
+ int transactionId = getTransactionIdentifier();
+
+ OpcuaMessageRequest readMessageRequest = new OpcuaMessageRequest(FINAL_CHUNK,
+ channelId.get(),
+ tokenId.get(),
+ transactionId,
+ transactionId,
+ buffer.getData());
+
+ RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
+
+ transaction.submit(() -> context.sendRequest(new OpcuaAPU(readMessageRequest))
+ .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
+ .onTimeout(onTimeout)
+ .onError(error)
+ .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
+ .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
+ .handle(opcuaResponse -> {consumer.accept(opcuaResponse);})
+ );
+ }
+
public void onConnect(ConversationContext<OpcuaAPU> context) {
// Only the TCP transport supports login.
LOGGER.info("Opcua Driver running in ACTIVE mode.");
-
+ this.context = context;
OpcuaHelloRequest hello = new OpcuaHelloRequest(FINAL_CHUNK,
VERSION,
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
index 86c270f..7693cc0 100644
--- 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
@@ -70,6 +70,7 @@ import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
import java.util.function.Consumer;
public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements HasConfiguration<OpcuaConfiguration>, PlcSubscriber {
@@ -146,6 +147,10 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
// Only the TCP transport supports login.
LOGGER.info("Opcua Driver running in ACTIVE mode.");
+ if (this.channel == null) {
+ this.channel = new SecureChannel(driverContext, this.configuration);
+ }
+
this.channel.onConnect(context);
}
@@ -161,18 +166,16 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
@Override
public CompletableFuture<PlcReadResponse> read(PlcReadRequest readRequest) {
LOGGER.trace("Reading Value");
+
CompletableFuture<PlcReadResponse> future = new CompletableFuture<>();
DefaultPlcReadRequest request = (DefaultPlcReadRequest) readRequest;
-
- int requestHandle = getRequestHandle();
-
- RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
- getCurrentDateTime(),
- requestHandle,
+ RequestHeader requestHeader = new RequestHeader(channel.getAuthenticationToken(),
+ SecureChannel.getCurrentDateTime(),
+ channel.getRequestHandle(),
0L,
NULL_STRING,
- REQUEST_TIMEOUT_LONG,
+ SecureChannel.REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
ReadValueId[] readValueArray = new ReadValueId[request.getFieldNames().size()];
@@ -207,41 +210,39 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
null,
opcuaReadRequest);
- int transactionId = getTransactionIdentifier();
-
try {
WriteBuffer buffer = new WriteBuffer(extObject.getLengthInBytes(), true);
ExtensionObjectIO.staticSerialize(buffer, extObject);
- OpcuaMessageRequest readMessageRequest = new OpcuaMessageRequest(FINAL_CHUNK,
- channelId.get(),
- tokenId.get(),
- transactionId,
- transactionId,
- buffer.getData());
-
- RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
- transaction.submit(() -> context.sendRequest(new OpcuaAPU(readMessageRequest))
- .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
- .onTimeout(future::completeExceptionally)
- .onError((p, e) -> future.completeExceptionally(e))
- .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
- .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
- .handle(opcuaResponse -> {
- // Prepare the response.
- PlcReadResponse response = null;
- try {
- response = new DefaultPlcReadResponse(request, readResponse(request.getFieldNames(), ((ReadResponse) ExtensionObjectIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true), false).getBody()).getResults()));
- } catch (ParseException e) {
- e.printStackTrace();
- };
-
- // Pass the response back to the application.
- future.complete(response);
-
- // Finish the request-transaction.
- transaction.endRequest();
- }));
+ /* Functional Consumer example using inner class */
+ Consumer<OpcuaMessageResponse> consumer = opcuaResponse -> {
+ PlcReadResponse response = null;
+ try {
+ response = new DefaultPlcReadResponse(request, readResponse(request.getFieldNames(), ((ReadResponse) ExtensionObjectIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true), false).getBody()).getResults()));
+ } catch (ParseException e) {
+ e.printStackTrace();
+ };
+
+ // Pass the response back to the application.
+ future.complete(response);
+ };
+
+ /* Functional Consumer example using inner class */
+ Consumer<TimeoutException> timeout = t -> {
+
+ // Pass the response back to the application.
+ future.completeExceptionally(t);
+ };
+
+ /* Functional Consumer example using inner class */
+ BiConsumer<OpcuaAPU, Throwable> error = (message, t) -> {
+
+ // Pass the response back to the application.
+ future.completeExceptionally(t);
+ };
+
+ channel.submit(timeout, error, consumer, buffer);
+
} catch (ParseException e) {
LOGGER.error("Unable to serialise the ReadRequest");
}
@@ -687,18 +688,14 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
CompletableFuture<PlcWriteResponse> future = new CompletableFuture<>();
DefaultPlcWriteRequest request = (DefaultPlcWriteRequest) writeRequest;
- int requestHandle = getRequestHandle();
-
- RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
- getCurrentDateTime(),
- requestHandle,
+ RequestHeader requestHeader = new RequestHeader(channel.getAuthenticationToken(),
+ SecureChannel.getCurrentDateTime(),
+ channel.getRequestHandle(),
0L,
NULL_STRING,
- REQUEST_TIMEOUT_LONG,
+ SecureChannel.REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
-
-
WriteValue[] writeValueArray = new WriteValue[request.getFieldNames().size()];
Iterator<String> iterator = request.getFieldNames().iterator();
for (int i = 0; i < request.getFieldNames().size(); i++ ) {
@@ -736,8 +733,6 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
null,
null);
- int transactionId = getTransactionIdentifier();
-
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
null,
@@ -747,37 +742,38 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
WriteBuffer buffer = new WriteBuffer(extObject.getLengthInBytes(), true);
ExtensionObjectIO.staticSerialize(buffer, extObject);
- OpcuaMessageRequest writeMessageRequest = new OpcuaMessageRequest(FINAL_CHUNK,
- channelId.get(),
- tokenId.get(),
- transactionId,
- transactionId,
- buffer.getData());
-
- RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
- transaction.submit(() -> context.sendRequest(new OpcuaAPU(writeMessageRequest))
- .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
- .onTimeout(future::completeExceptionally)
- .onError((p, e) -> future.completeExceptionally(e))
- .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
- .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
- .handle(opcuaResponse -> {
- WriteResponse responseMessage = null;
- try {
- responseMessage = (WriteResponse) ExtensionObjectIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true), false).getBody();
- } catch (ParseException e) {
- e.printStackTrace();
- }
- PlcWriteResponse response = writeResponse(request, responseMessage);
+ /* Functional Consumer example using inner class */
+ Consumer<OpcuaMessageResponse> consumer = opcuaResponse -> {
+ WriteResponse responseMessage = null;
+ try {
+ responseMessage = (WriteResponse) ExtensionObjectIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true), false).getBody();
+ } catch (ParseException e) {
+ e.printStackTrace();
+ }
+ PlcWriteResponse response = writeResponse(request, responseMessage);
+
+ // Pass the response back to the application.
+ future.complete(response);
+ };
+
+ /* Functional Consumer example using inner class */
+ Consumer<TimeoutException> timeout = t -> {
+
+ // Pass the response back to the application.
+ future.completeExceptionally(t);
+ };
+
+ /* Functional Consumer example using inner class */
+ BiConsumer<OpcuaAPU, Throwable> error = (message, t) -> {
+
+ // Pass the response back to the application.
+ future.completeExceptionally(t);
+ };
- // Pass the response back to the application.
- future.complete(response);
+ channel.submit(timeout, error, consumer, buffer);
- // Finish the request-transaction.
- transaction.endRequest();
- }));
} catch (ParseException e) {
- LOGGER.error("Unable to serialize write request");
+ LOGGER.error("Unable to serialise the ReadRequest");
}
return future;
@@ -822,11 +818,11 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
try {
CompletableFuture<CreateSubscriptionResponse> subscription = onSubscribeCreateSubscription(cycleTime);
- CreateSubscriptionResponse response = subscription.get(REQUEST_TIMEOUT_LONG, TimeUnit.MILLISECONDS);
+ CreateSubscriptionResponse response = subscription.get(SecureChannel.REQUEST_TIMEOUT_LONG, TimeUnit.MILLISECONDS);
//Store this somewhere safe
subscriptionId = response.getSubscriptionId();
- subscriptions.put(subscriptionId, new OpcuaSubscriptionHandle(this, subscriptionId, subscriptionRequest.getFieldNames(), cycleTime));
+ subscriptions.put(subscriptionId, new OpcuaSubscriptionHandle(this, channel, subscriptionId, subscriptionRequest.getFieldNames(), cycleTime));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
@@ -920,14 +916,12 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
private CompletableFuture<CreateSubscriptionResponse> onSubscribeCreateSubscription(long cycleTime) {
CompletableFuture<CreateSubscriptionResponse> future = new CompletableFuture<>();
- int requestHandle = getRequestHandle();
-
- RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
- getCurrentDateTime(),
- requestHandle,
+ RequestHeader requestHeader = new RequestHeader(channel.getAuthenticationToken(),
+ SecureChannel.getCurrentDateTime(),
+ channel.getRequestHandle(),
0L,
NULL_STRING,
- REQUEST_TIMEOUT_LONG,
+ SecureChannel.REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
CreateSubscriptionRequest createSubscriptionRequest = new CreateSubscriptionRequest(
@@ -955,53 +949,52 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
WriteBuffer buffer = new WriteBuffer(extObject.getLengthInBytes(), true);
ExtensionObjectIO.staticSerialize(buffer, extObject);
- int transactionId = getTransactionIdentifier();
-
- OpcuaMessageRequest createMessageRequest = new OpcuaMessageRequest(FINAL_CHUNK,
- channelId.get(),
- tokenId.get(),
- transactionId,
- transactionId,
- buffer.getData());
-
- RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
- transaction.submit(() -> context.sendRequest(new OpcuaAPU(createMessageRequest))
- .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
- .onTimeout(future::completeExceptionally)
- .onError((p, e) -> future.completeExceptionally(e))
- .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
- .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
- .handle(opcuaResponse -> {
- CreateSubscriptionResponse responseMessage = null;
- try {
- responseMessage = (CreateSubscriptionResponse) ExtensionObjectIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true), false).getBody();
- } catch (ParseException e) {
- e.printStackTrace();
- }
+ /* Functional Consumer example using inner class */
+ Consumer<OpcuaMessageResponse> consumer = opcuaResponse -> {
+ CreateSubscriptionResponse responseMessage = null;
+ try {
+ responseMessage = (CreateSubscriptionResponse) ExtensionObjectIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true), false).getBody();
+ } catch (ParseException e) {
+ e.printStackTrace();
+ }
+
+ // Pass the response back to the application.
+ future.complete(responseMessage);
+
+ };
- // Pass the response back to the application.
- future.complete(responseMessage);
+ /* Functional Consumer example using inner class */
+ Consumer<TimeoutException> timeout = t -> {
+
+ // Pass the response back to the application.
+ future.completeExceptionally(t);
+ };
+
+ /* Functional Consumer example using inner class */
+ BiConsumer<OpcuaAPU, Throwable> error = (message, t) -> {
+
+ // Pass the response back to the application.
+ future.completeExceptionally(t);
+ };
+
+ channel.submit(timeout, error, consumer, buffer);
- // Finish the request-transaction.
- transaction.endRequest();
- }));
} catch (ParseException e) {
- LOGGER.error("Unable to serialize subscription request");
+ LOGGER.error("Unable to serialise the ReadRequest");
}
+
return future;
}
private CompletableFuture<CreateMonitoredItemsResponse> onSubscribeCreateMonitoredItemsRequest(List<MonitoredItemCreateRequest> requestList, long subscriptionId) {
CompletableFuture<CreateMonitoredItemsResponse> future = new CompletableFuture<>();
- int requestHandle = getRequestHandle();
-
- RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
- getCurrentDateTime(),
- requestHandle,
+ RequestHeader requestHeader = new RequestHeader(channel.getAuthenticationToken(),
+ SecureChannel.getCurrentDateTime(),
+ channel.getRequestHandle(),
0L,
NULL_STRING,
- REQUEST_TIMEOUT_LONG,
+ SecureChannel.REQUEST_TIMEOUT_LONG,
NULL_EXTENSION_OBJECT);
CreateMonitoredItemsRequest createMonitoredItemsRequest = new CreateMonitoredItemsRequest(
@@ -1027,39 +1020,40 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
WriteBuffer buffer = new WriteBuffer(extObject.getLengthInBytes(), true);
ExtensionObjectIO.staticSerialize(buffer, extObject);
- int transactionId = getTransactionIdentifier();
-
- OpcuaMessageRequest createMessageRequest = new OpcuaMessageRequest(FINAL_CHUNK,
- channelId.get(),
- tokenId.get(),
- transactionId,
- transactionId,
- buffer.getData());
-
- RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
- transaction.submit(() -> context.sendRequest(new OpcuaAPU(createMessageRequest))
- .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
- .onTimeout(future::completeExceptionally)
- .onError((p, e) -> future.completeExceptionally(e))
- .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
- .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
- .handle(opcuaResponse -> {
- CreateMonitoredItemsResponse responseMessage = null;
- try {
- responseMessage = (CreateMonitoredItemsResponse) ExtensionObjectIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true), false).getBody();
- } catch (ParseException e) {
- e.printStackTrace();
- }
+ /* Functional Consumer example using inner class */
+ Consumer<OpcuaMessageResponse> consumer = opcuaResponse -> {
+ CreateMonitoredItemsResponse responseMessage = null;
+ try {
+ responseMessage = (CreateMonitoredItemsResponse) ExtensionObjectIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true), false).getBody();
+ } catch (ParseException e) {
+ e.printStackTrace();
+ }
+
+ // Pass the response back to the application.
+ future.complete(responseMessage);
+
+ };
+
+ /* Functional Consumer example using inner class */
+ Consumer<TimeoutException> timeout = t -> {
- // Pass the response back to the application.
- future.complete(responseMessage);
+ // Pass the response back to the application.
+ future.completeExceptionally(t);
+ };
+
+ /* Functional Consumer example using inner class */
+ BiConsumer<OpcuaAPU, Throwable> error = (message, t) -> {
+
+ // Pass the response back to the application.
+ future.completeExceptionally(t);
+ };
+
+ channel.submit(timeout, error, consumer, buffer);
- // Finish the request-transaction.
- transaction.endRequest();
- }));
} catch (ParseException e) {
- LOGGER.error("Unable to serialize subscription request");
+ LOGGER.error("Unable to serialise the ReadRequest");
}
+
return future;
}
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaSubscriptionHandle.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaSubscriptionHandle.java
index 8cf4a01..2100463 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaSubscriptionHandle.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaSubscriptionHandle.java
@@ -24,6 +24,7 @@ import org.apache.plc4x.java.api.model.PlcConsumerRegistration;
import org.apache.plc4x.java.api.model.PlcSubscriptionHandle;
import org.apache.plc4x.java.api.types.PlcResponseCode;
import org.apache.plc4x.java.api.value.PlcValue;
+import org.apache.plc4x.java.opcua.context.SecureChannel;
import org.apache.plc4x.java.opcua.field.OpcuaField;
import org.apache.plc4x.java.opcua.readwrite.*;
import org.apache.plc4x.java.opcua.readwrite.io.ExtensionObjectIO;
@@ -44,9 +45,11 @@ import org.slf4j.LoggerFactory;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
@@ -58,6 +61,7 @@ public class OpcuaSubscriptionHandle extends DefaultPlcSubscriptionHandle {
private Set<Consumer<PlcSubscriptionEvent>> consumers;
private List<String> fieldNames;
private long clientHandle;
+ private SecureChannel channel;
private AtomicBoolean destroy = new AtomicBoolean(false);
private OpcuaProtocolLogic plcSubscriber;
@@ -68,10 +72,11 @@ public class OpcuaSubscriptionHandle extends DefaultPlcSubscriptionHandle {
* @param fieldNames corresponding map key in the PLC4X request/reply map
*
*/
- public OpcuaSubscriptionHandle(OpcuaProtocolLogic plcSubscriber, Long subscriptionId, LinkedHashSet<String> fieldNames, long cycleTime) {
+ public OpcuaSubscriptionHandle(OpcuaProtocolLogic plcSubscriber, SecureChannel channel, Long subscriptionId, LinkedHashSet<String> fieldNames, long cycleTime) {
super(plcSubscriber);
this.consumers = new HashSet<>();
this.fieldNames = new ArrayList<>( fieldNames );
+ this.channel = channel;
this.subscriptionId = subscriptionId;
this.plcSubscriber = plcSubscriber;
this.cycleTime = cycleTime;
@@ -98,14 +103,14 @@ public class OpcuaSubscriptionHandle extends DefaultPlcSubscriptionHandle {
LOGGER.trace("Interrupted Exception");
}
- int requestHandle = sequenceNumber.getAndIncrement();
+ long requestHandle = channel.getRequestHandle();
- RequestHeader requestHeader = new RequestHeader(this.plcSubscriber.getAuthenticationToken(),
- OpcuaProtocolLogic.getCurrentDateTime(),
- requestHandle,
+ RequestHeader requestHeader = new RequestHeader(channel.getAuthenticationToken(),
+ SecureChannel.getCurrentDateTime(),
+ channel.getRequestHandle(),
0L,
OpcuaProtocolLogic.NULL_STRING,
- OpcuaProtocolLogic.REQUEST_TIMEOUT_LONG,
+ SecureChannel.REQUEST_TIMEOUT_LONG,
OpcuaProtocolLogic.NULL_EXTENSION_OBJECT);
SubscriptionAcknowledgement[] acks = null;
@@ -139,52 +144,49 @@ public class OpcuaSubscriptionHandle extends DefaultPlcSubscriptionHandle {
WriteBuffer buffer = new WriteBuffer(extObject.getLengthInBytes(), true);
ExtensionObjectIO.staticSerialize(buffer, extObject);
- int transactionId = this.plcSubscriber.getTransactionIdentifier();
-
- OpcuaMessageRequest createMessageRequest = new OpcuaMessageRequest(OpcuaProtocolLogic.FINAL_CHUNK,
- this.plcSubscriber.getChannelId(),
- this.plcSubscriber.getTokenId(),
- transactionId,
- transactionId,
- buffer.getData());
-
- RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
- outstandingRequests.add((long) requestHandle);
- transaction.submit(() -> this.plcSubscriber.getConversationContext().sendRequest(new OpcuaAPU(createMessageRequest))
- .expectResponse(OpcuaAPU.class, OpcuaProtocolLogic.REQUEST_TIMEOUT)
- .onError((p, e) -> LOGGER.error("Unable to maintain subscription"))
- .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
- .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
- .handle(opcuaResponse -> {
- PublishResponse responseMessage = null;
- try {
- responseMessage = (PublishResponse) ExtensionObjectIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true), false).getBody();
- } catch (ParseException e) {
- e.printStackTrace();
+ /* Functional Consumer example using inner class */
+ Consumer<OpcuaMessageResponse> consumer = opcuaResponse -> {
+ PublishResponse responseMessage = null;
+ try {
+ responseMessage = (PublishResponse) ExtensionObjectIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true), false).getBody();
+ } catch (ParseException e) {
+ e.printStackTrace();
+ }
+ outstandingRequests.remove(((ResponseHeader) responseMessage.getResponseHeader()).getRequestHandle());
+ outstandingAcknowledgements.add(((ResponseHeader) responseMessage.getResponseHeader()).getRequestHandle());
+
+ if (((NotificationMessage) responseMessage.getNotificationMessage()).getNoOfNotificationData() > 0) {
+
+ }
+ for (ExtensionObject notificationMessage : ((NotificationMessage) responseMessage.getNotificationMessage()).getNotificationData()) {
+ ExtensionObjectDefinition notification = notificationMessage.getBody();
+ if (notification instanceof DataChangeNotification) {
+ LOGGER.info("Found a Data Change notification");
+ ExtensionObjectDefinition[] items = ((DataChangeNotification) notification).getMonitoredItems();
+ MonitoredItemNotification[] monitoredItems = Arrays.copyOf(items, items.length, MonitoredItemNotification[].class);
+ onSubscriptionValue(monitoredItems);
+ } else {
+ LOGGER.warn("Unsupported Notification type");
}
- outstandingRequests.remove(((ResponseHeader) responseMessage.getResponseHeader()).getRequestHandle());
- outstandingAcknowledgements.add(((ResponseHeader) responseMessage.getResponseHeader()).getRequestHandle());
+ }
- if (((NotificationMessage) responseMessage.getNotificationMessage()).getNoOfNotificationData() > 0) {
+ // Pass the response back to the application.
- }
- for (ExtensionObject notificationMessage : ((NotificationMessage) responseMessage.getNotificationMessage()).getNotificationData()) {
- ExtensionObjectDefinition notification = notificationMessage.getBody();
- if (notification instanceof DataChangeNotification) {
- LOGGER.info("Found a Data Change notification");
- ExtensionObjectDefinition[] items = ((DataChangeNotification) notification).getMonitoredItems();
- MonitoredItemNotification[] monitoredItems = Arrays.copyOf(items, items.length, MonitoredItemNotification[].class);
- onSubscriptionValue(monitoredItems);
- } else {
- LOGGER.warn("Unsupported Notification type");
- }
- }
+ };
+
+ /* Functional Consumer example using inner class */
+ Consumer<TimeoutException> timeout = t -> {
+
+ };
+
+ /* Functional Consumer example using inner class */
+ BiConsumer<OpcuaAPU, Throwable> error = (message, t) -> {
+
+ };
- // Pass the response back to the application.
+ outstandingRequests.add(requestHandle);
+ channel.submit(timeout, error, consumer, buffer);
- // Finish the request-transaction.
- transaction.endRequest();
- }));
} catch (ParseException e) {
LOGGER.warn("Unable to serialize subscription request");
e.printStackTrace();