use of org.apache.plc4x.java.opcua.field.OpcuaField in project plc4x by apache.
the class OpcuaOptimizer method processReadRequest.
@Override
protected List<PlcRequest> processReadRequest(PlcReadRequest readRequest, DriverContext driverContext) {
List<PlcRequest> processedRequests = new LinkedList<>();
// List of all items in the current request.
LinkedHashMap<String, PlcField> curFields = new LinkedHashMap<>();
for (String fieldName : readRequest.getFieldNames()) {
OpcuaField field = (OpcuaField) readRequest.getField(fieldName);
curFields.put(fieldName, field);
}
// Create a new PlcReadRequest from the remaining field items.
if (!curFields.isEmpty()) {
processedRequests.add(new DefaultPlcReadRequest(((DefaultPlcReadRequest) readRequest).getReader(), curFields));
}
return processedRequests;
}
use of org.apache.plc4x.java.opcua.field.OpcuaField in project plc4x by apache.
the class OpcuaProtocolLogic method subscribe.
@Override
public CompletableFuture<PlcSubscriptionResponse> subscribe(PlcSubscriptionRequest subscriptionRequest) {
return CompletableFuture.supplyAsync(() -> {
Map<String, ResponseItem<PlcSubscriptionHandle>> values = new HashMap<>();
long subscriptionId;
ArrayList<String> fields = new ArrayList<>(subscriptionRequest.getFieldNames());
long cycleTime = (subscriptionRequest.getField(fields.get(0))).getDuration().orElse(Duration.ofMillis(1000)).toMillis();
try {
CompletableFuture<CreateSubscriptionResponse> subscription = onSubscribeCreateSubscription(cycleTime);
CreateSubscriptionResponse response = subscription.get(SecureChannel.REQUEST_TIMEOUT_LONG, TimeUnit.MILLISECONDS);
subscriptionId = response.getSubscriptionId();
subscriptions.put(subscriptionId, new OpcuaSubscriptionHandle(context, this, channel, subscriptionRequest, subscriptionId, cycleTime));
} catch (Exception e) {
throw new PlcRuntimeException("Unable to subscribe because of: " + e.getMessage());
}
for (String fieldName : subscriptionRequest.getFieldNames()) {
final DefaultPlcSubscriptionField fieldDefaultPlcSubscription = (DefaultPlcSubscriptionField) subscriptionRequest.getField(fieldName);
if (!(fieldDefaultPlcSubscription.getPlcField() instanceof OpcuaField)) {
values.put(fieldName, new ResponseItem<>(PlcResponseCode.INVALID_ADDRESS, null));
} else {
values.put(fieldName, new ResponseItem<>(PlcResponseCode.OK, subscriptions.get(subscriptionId)));
}
}
return new DefaultPlcSubscriptionResponse(subscriptionRequest, values);
});
}
use of org.apache.plc4x.java.opcua.field.OpcuaField in project plc4x by apache.
the class OpcuaSubscriptionHandle method onSubscribeCreateMonitoredItemsRequest.
private CompletableFuture<CreateMonitoredItemsResponse> onSubscribeCreateMonitoredItemsRequest() {
List<ExtensionObjectDefinition> requestList = new ArrayList<>(this.fieldNames.size());
for (int i = 0; i < this.fieldNames.size(); i++) {
final DefaultPlcSubscriptionField fieldDefaultPlcSubscription = (DefaultPlcSubscriptionField) subscriptionRequest.getField(fieldNames.get(i));
NodeId idNode = generateNodeId((OpcuaField) fieldDefaultPlcSubscription.getPlcField());
ReadValueId readValueId = new ReadValueId(idNode, 0xD, OpcuaProtocolLogic.NULL_STRING, new QualifiedName(0, OpcuaProtocolLogic.NULL_STRING));
MonitoringMode monitoringMode;
switch(fieldDefaultPlcSubscription.getPlcSubscriptionType()) {
case CYCLIC:
monitoringMode = MonitoringMode.monitoringModeSampling;
break;
case CHANGE_OF_STATE:
monitoringMode = MonitoringMode.monitoringModeReporting;
break;
case EVENT:
monitoringMode = MonitoringMode.monitoringModeReporting;
break;
default:
monitoringMode = MonitoringMode.monitoringModeReporting;
}
long clientHandle = clientHandles.getAndIncrement();
MonitoringParameters parameters = new MonitoringParameters(clientHandle, // sampling interval
(double) cycleTime, // filter, null means use default
OpcuaProtocolLogic.NULL_EXTENSION_OBJECT, // queue size
1L, // discard oldest
true);
MonitoredItemCreateRequest request = new MonitoredItemCreateRequest(readValueId, monitoringMode, parameters);
requestList.add(request);
}
CompletableFuture<CreateMonitoredItemsResponse> future = new CompletableFuture<>();
RequestHeader requestHeader = new RequestHeader(channel.getAuthenticationToken(), SecureChannel.getCurrentDateTime(), channel.getRequestHandle(), 0L, OpcuaProtocolLogic.NULL_STRING, SecureChannel.REQUEST_TIMEOUT_LONG, OpcuaProtocolLogic.NULL_EXTENSION_OBJECT);
CreateMonitoredItemsRequest createMonitoredItemsRequest = new CreateMonitoredItemsRequest(requestHeader, subscriptionId, TimestampsToReturn.timestampsToReturnBoth, requestList.size(), requestList);
ExpandedNodeId expandedNodeId = new // Namespace Uri Specified
ExpandedNodeId(// Namespace Uri Specified
false, // Server Index Specified
false, new NodeIdFourByte((short) 0, Integer.parseInt(createMonitoredItemsRequest.getIdentifier())), null, null);
ExtensionObject extObject = new ExtensionObject(expandedNodeId, null, createMonitoredItemsRequest, false);
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), ByteOrder.LITTLE_ENDIAN);
extObject.serialize(buffer);
Consumer<byte[]> consumer = opcuaResponse -> {
CreateMonitoredItemsResponse responseMessage = null;
try {
ExtensionObjectDefinition unknownExtensionObject = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, ByteOrder.LITTLE_ENDIAN), false).getBody();
if (unknownExtensionObject instanceof CreateMonitoredItemsResponse) {
responseMessage = (CreateMonitoredItemsResponse) unknownExtensionObject;
} else {
ServiceFault serviceFault = (ServiceFault) unknownExtensionObject;
ResponseHeader header = (ResponseHeader) serviceFault.getResponseHeader();
LOGGER.error("Subscription ServiceFault returned from server with error code, '{}'", header.getServiceResult().toString());
plcSubscriber.onDisconnect(context);
}
} catch (ParseException e) {
LOGGER.error("Unable to parse the returned Subscription response", e);
plcSubscriber.onDisconnect(context);
}
MonitoredItemCreateResult[] array = responseMessage.getResults().toArray(new MonitoredItemCreateResult[0]);
for (int index = 0, arrayLength = array.length; index < arrayLength; index++) {
MonitoredItemCreateResult result = array[index];
if (OpcuaStatusCode.enumForValue(result.getStatusCode().getStatusCode()) != OpcuaStatusCode.Good) {
LOGGER.error("Invalid Field {}, subscription created without this field", fieldNames.get(index));
} else {
LOGGER.debug("Field {} was added to the subscription", fieldNames.get(index));
}
}
future.complete(responseMessage);
};
Consumer<TimeoutException> timeout = e -> {
LOGGER.info("Timeout while sending the Create Monitored Item Subscription Message", e);
plcSubscriber.onDisconnect(context);
};
BiConsumer<OpcuaAPU, Throwable> error = (message, e) -> {
LOGGER.info("Error while sending the Create Monitored Item Subscription Message", e);
plcSubscriber.onDisconnect(context);
};
channel.submit(context, timeout, error, consumer, buffer);
} catch (SerializationException e) {
LOGGER.info("Unable to serialize the Create Monitored Item Subscription Message", e);
plcSubscriber.onDisconnect(context);
}
return future;
}
use of org.apache.plc4x.java.opcua.field.OpcuaField in project plc4x by apache.
the class OpcuaProtocolLogic method read.
@Override
public CompletableFuture<PlcReadResponse> read(PlcReadRequest readRequest) {
LOGGER.trace("Reading Value");
CompletableFuture<PlcReadResponse> future = new CompletableFuture<>();
DefaultPlcReadRequest request = (DefaultPlcReadRequest) readRequest;
RequestHeader requestHeader = new RequestHeader(channel.getAuthenticationToken(), SecureChannel.getCurrentDateTime(), channel.getRequestHandle(), 0L, NULL_STRING, SecureChannel.REQUEST_TIMEOUT_LONG, NULL_EXTENSION_OBJECT);
List<ExtensionObjectDefinition> readValueArray = new ArrayList<>(request.getFieldNames().size());
Iterator<String> iterator = request.getFieldNames().iterator();
for (int i = 0; i < request.getFieldNames().size(); i++) {
String fieldName = iterator.next();
OpcuaField field = (OpcuaField) request.getField(fieldName);
NodeId nodeId = generateNodeId(field);
readValueArray.add(new ReadValueId(nodeId, 0xD, NULL_STRING, new QualifiedName(0, NULL_STRING)));
}
ReadRequest opcuaReadRequest = new ReadRequest(requestHeader, 0.0d, TimestampsToReturn.timestampsToReturnNeither, readValueArray.size(), readValueArray);
ExpandedNodeId expandedNodeId = new // Namespace Uri Specified
ExpandedNodeId(// Namespace Uri Specified
false, // Server Index Specified
false, new NodeIdFourByte((short) 0, Integer.parseInt(opcuaReadRequest.getIdentifier())), null, null);
ExtensionObject extObject = new ExtensionObject(expandedNodeId, null, opcuaReadRequest, false);
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), ByteOrder.LITTLE_ENDIAN);
extObject.serialize(buffer);
/* Functional Consumer example using inner class */
Consumer<byte[]> consumer = opcuaResponse -> {
PlcReadResponse response = null;
try {
ExtensionObjectDefinition reply = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, ByteOrder.LITTLE_ENDIAN), false).getBody();
if (reply instanceof ReadResponse) {
future.complete(new DefaultPlcReadResponse(request, readResponse(request.getFieldNames(), ((ReadResponse) reply).getResults())));
} else {
if (reply instanceof ServiceFault) {
ExtensionObjectDefinition header = ((ServiceFault) reply).getResponseHeader();
LOGGER.error("Read request ended up with ServiceFault: {}", header);
} else {
LOGGER.error("Remote party returned an error '{}'", reply);
}
Map<String, ResponseItem<PlcValue>> status = new LinkedHashMap<>();
for (String key : request.getFieldNames()) {
status.put(key, new ResponseItem<>(PlcResponseCode.INTERNAL_ERROR, null));
}
future.complete(new DefaultPlcReadResponse(request, status));
return;
}
} catch (ParseException e) {
future.completeExceptionally(new PlcRuntimeException(e));
}
;
};
/* Functional Consumer example using inner class */
// Pass the response back to the application.
Consumer<TimeoutException> timeout = future::completeExceptionally;
/* Functional Consumer example using inner class */
BiConsumer<OpcuaAPU, Throwable> error = (message, t) -> {
// Pass the response back to the application.
future.completeExceptionally(t);
};
channel.submit(context, timeout, error, consumer, buffer);
} catch (SerializationException e) {
LOGGER.error("Unable to serialise the ReadRequest");
}
return future;
}
use of org.apache.plc4x.java.opcua.field.OpcuaField in project plc4x by apache.
the class OpcuaProtocolLogic method write.
@Override
public CompletableFuture<PlcWriteResponse> write(PlcWriteRequest writeRequest) {
LOGGER.trace("Writing Value");
CompletableFuture<PlcWriteResponse> future = new CompletableFuture<>();
DefaultPlcWriteRequest request = (DefaultPlcWriteRequest) writeRequest;
RequestHeader requestHeader = new RequestHeader(channel.getAuthenticationToken(), SecureChannel.getCurrentDateTime(), channel.getRequestHandle(), 0L, NULL_STRING, SecureChannel.REQUEST_TIMEOUT_LONG, NULL_EXTENSION_OBJECT);
List<ExtensionObjectDefinition> writeValueList = new ArrayList<>(request.getFieldNames().size());
for (String fieldName : request.getFieldNames()) {
OpcuaField field = (OpcuaField) request.getField(fieldName);
NodeId nodeId = generateNodeId(field);
writeValueList.add(new WriteValue(nodeId, 0xD, NULL_STRING, new DataValue(false, false, false, false, false, true, fromPlcValue(fieldName, field, writeRequest), null, null, null, null, null)));
}
WriteRequest opcuaWriteRequest = new WriteRequest(requestHeader, writeValueList.size(), writeValueList);
ExpandedNodeId expandedNodeId = new // Namespace Uri Specified
ExpandedNodeId(// Namespace Uri Specified
false, // Server Index Specified
false, new NodeIdFourByte((short) 0, Integer.parseInt(opcuaWriteRequest.getIdentifier())), null, null);
ExtensionObject extObject = new ExtensionObject(expandedNodeId, null, opcuaWriteRequest, false);
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), ByteOrder.LITTLE_ENDIAN);
extObject.serialize(buffer);
/* Functional Consumer example using inner class */
Consumer<byte[]> consumer = opcuaResponse -> {
WriteResponse responseMessage = null;
try {
responseMessage = (WriteResponse) ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, ByteOrder.LITTLE_ENDIAN), 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 */
// Pass the response back to the application.
Consumer<TimeoutException> timeout = future::completeExceptionally;
/* Functional Consumer example using inner class */
BiConsumer<OpcuaAPU, Throwable> error = (message, t) -> {
// Pass the response back to the application.
future.completeExceptionally(t);
};
channel.submit(context, timeout, error, consumer, buffer);
} catch (SerializationException e) {
LOGGER.error("Unable to serialise the ReadRequest");
}
return future;
}
Aggregations