use of com.prosysopc.ua.StatusException in project FAAAST-Service by FraunhoferIOSB.
the class OpcUaEndpoint method callOperation.
/**
* Calls the desired operation in the service.
*
* @param operation The desired operation
* @param inputVariables The input arguments
* @param submodel The corresponding submodel
* @param refElement The reference to the SubmodelElement
* @return The OutputArguments The output arguments returned from the operation call
* @throws StatusException If the operation fails
*/
public List<OperationVariable> callOperation(Operation operation, List<OperationVariable> inputVariables, Submodel submodel, Reference refElement) throws StatusException {
List<OperationVariable> outputArguments;
try {
InvokeOperationSyncRequest request = new InvokeOperationSyncRequest();
List<Key> path = new ArrayList<>();
path.addAll(refElement.getKeys());
request.setId(submodel.getIdentification());
request.setPath(path);
request.setInputArguments(inputVariables);
request.setContent(Content.Normal);
requestCounter++;
request.setRequestId(Integer.toString(requestCounter));
// execute method
InvokeOperationSyncResponse response = (InvokeOperationSyncResponse) service.execute(request);
if (isSuccess(response.getStatusCode())) {
logger.info("callOperation: Operation " + operation.getIdShort() + " executed successfully");
} else if (response.getStatusCode() == StatusCode.ClientMethodNotAllowed) {
logger.warn("callOperation: Operation " + operation.getIdShort() + " error executing operation: " + response.getStatusCode());
throw new StatusException(StatusCodes.Bad_NotExecutable);
} else {
logger.warn("callOperation: Operation " + operation.getIdShort() + " error executing operation: " + response.getStatusCode());
throw new StatusException(StatusCodes.Bad_UnexpectedError);
}
outputArguments = response.getPayload().getOutputArguments();
} catch (Exception ex) {
logger.error("callOperation error", ex);
throw ex;
}
return outputArguments;
}
use of com.prosysopc.ua.StatusException in project FAAAST-Service by FraunhoferIOSB.
the class AasServiceMethodManagerListener method onCall.
/**
* Callback method when a method was called
*
* @param serviceContext the current service context
* @param objectId the ID of the node whose method is being called
* @param object the object node whose method is being called, if available
* @param methodId the ID of the method being called
* @param method the method node being called, if available
* @param inputArguments input argument values
* @param inputArgumentResults argument errors. If errors in the values are
* encountered.
* @param inputArgumentDiagnosticInfos diagnostic info, in case of errors.
* @param outputs output values. The array is pre-created, just fill in the
* values.
* @return true if you handle the call, which prevents any other handler
* being called.
* @throws StatusException if there are errors in the method handling. For
* example, if you set inputArgumentResults, you should throw a
* StatusException with StatusCodes.Bad_InvalidArgument
*/
@Override
public boolean onCall(ServiceContext serviceContext, NodeId objectId, UaNode object, NodeId methodId, UaMethod method, Variant[] inputArguments, StatusCode[] inputArgumentResults, DiagnosticInfo[] inputArgumentDiagnosticInfos, Variant[] outputs) throws StatusException {
boolean retval = false;
// Handle method calls
// Note that the outputs array is already allocated
logger.info("onCall: method " + methodId.toString() + ": called. InputArguments: " + Arrays.toString(inputArguments));
try {
if (endpoint == null) {
logger.warn("onCall: no Endpoint available");
} else {
SubmodelElementData data = nodeManager.getAasData(objectId);
Operation aasOper = (Operation) data.getSubmodelElement();
if (aasOper != null) {
List<OperationVariable> inputVariables = aasOper.getInputVariables();
ValueConverter.setOperationValues(inputVariables, inputArguments);
List<OperationVariable> outputVariables = endpoint.callOperation(aasOper, inputVariables, data.getSubmodel(), data.getReference());
ValueConverter.setOutputArguments(outputVariables, outputs);
retval = true;
} else {
logger.info("onCall: Property for " + objectId.toString() + " not found");
}
}
} catch (StatusException se) {
logger.error("onCall StatusException", se);
throw se;
} catch (Throwable ex) {
logger.error("onCall Exception", ex);
throw new StatusException(ex.getMessage(), StatusCodes.Bad_UnexpectedError);
}
return retval;
}
use of com.prosysopc.ua.StatusException in project FAAAST-Service by FraunhoferIOSB.
the class AasServiceNodeManager method setAasReferenceData.
/**
* Sets the data in the given Reference node.
*
* @param ref The desired UA reference object
* @param refNode The AAS Reference object with the source data
* @param readOnly True if the value should be read-only
* @throws StatusException If the operation fails
*/
private void setAasReferenceData(Reference ref, AASReferenceType refNode, boolean readOnly) throws StatusException {
if (refNode == null) {
throw new IllegalArgumentException("refNode is null");
} else if (ref == null) {
throw new IllegalArgumentException("ref is null");
}
try {
List<AASKeyDataType> keyList = new ArrayList<>();
ref.getKeys().stream().map(k -> {
AASKeyDataType keyValue = new AASKeyDataType();
keyValue.setIdType(ValueConverter.getAasKeyType(k.getIdType()));
keyValue.setType(ValueConverter.getAasKeyElementsDataType(k.getType()));
keyValue.setValue(k.getValue());
return keyValue;
}).forEachOrdered(keyValue -> {
keyList.add(keyValue);
});
refNode.getKeysNode().setArrayDimensions(new UnsignedInteger[] { UnsignedInteger.valueOf(keyList.size()) });
if (readOnly) {
refNode.getKeysNode().setAccessLevel(AccessLevelType.CurrentRead);
}
refNode.setKeys(keyList.toArray(AASKeyDataType[]::new));
} catch (Throwable ex) {
logger.error("setAasReferenceData Exception", ex);
throw ex;
}
}
use of com.prosysopc.ua.StatusException in project FAAAST-Service by FraunhoferIOSB.
the class OpcUaEndpointTest method testUpdatePropertyValue.
/**
* Test method for changing a property based on an event from the MessageBus. Sets an event
* on the MessageBus and checks the new value in the server.
*
* @throws SecureIdentityException If the operation fails
* @throws ServiceException If the operation fails
* @throws IOException If the operation fails
* @throws StatusException If the operation fails
*/
@Test
public void testUpdatePropertyValue() throws SecureIdentityException, ServiceException, IOException, StatusException, Exception {
UaClient client = new UaClient(ENDPOINT_URL);
client.setSecurityMode(SecurityMode.NONE);
TestUtils.initialize(client);
client.connect();
System.out.println("testUpdatePropertyValue: client connected");
aasns = client.getAddressSpace().getNamespaceTable().getIndex(VariableIds.AASAssetAdministrationShellType_AssetInformation_AssetKind.getNamespaceUri());
List<RelativePath> relPath = new ArrayList<>();
List<RelativePathElement> browsePath = new ArrayList<>();
browsePath.add(new RelativePathElement(Identifiers.HierarchicalReferences, false, true, new QualifiedName(aasns, TestDefines.AAS_ENVIRONMENT_NAME)));
browsePath.add(new RelativePathElement(Identifiers.HierarchicalReferences, false, true, new QualifiedName(aasns, TestDefines.SUBMODEL_OPER_DATA_NODE_NAME)));
browsePath.add(new RelativePathElement(Identifiers.HierarchicalReferences, false, true, new QualifiedName(aasns, TestDefines.ROTATION_SPEED_NAME)));
browsePath.add(new RelativePathElement(Identifiers.HasProperty, false, true, new QualifiedName(aasns, TestDefines.PROPERTY_VALUE_NAME)));
relPath.add(new RelativePath(browsePath.toArray(RelativePathElement[]::new)));
BrowsePathResult[] bpres = client.getAddressSpace().translateBrowsePathsToNodeIds(Identifiers.ObjectsFolder, relPath.toArray(RelativePath[]::new));
Assert.assertNotNull("testWriteProperty Browse Result Null", bpres);
Assert.assertTrue("testWriteProperty Browse Result: size doesn't match", bpres.length == 1);
Assert.assertTrue("testWriteProperty Browse Result Good", bpres[0].getStatusCode().isGood());
BrowsePathTarget[] targets = bpres[0].getTargets();
Assert.assertNotNull("testWriteProperty ValueType Null", targets);
Assert.assertTrue("testWriteProperty ValueType empty", targets.length > 0);
DataValue value = client.readValue(targets[0].getTargetId());
Assert.assertEquals(StatusCode.GOOD, value.getStatusCode());
Integer oldValue = 4370;
Assert.assertEquals("intial value not equal", oldValue, value.getValue().getValue());
CountDownLatch condition = new CountDownLatch(1);
final AtomicReference<EventMessage> response = new AtomicReference<>();
service.getMessageBus().subscribe(SubscriptionInfo.create(ValueChangeEventMessage.class, x -> {
response.set(x);
condition.countDown();
}));
Integer newValue = 9999;
List<Key> keys = new ArrayList<>();
keys.add(new DefaultKey.Builder().idType(KeyType.IRI).type(KeyElements.SUBMODEL).value(TestDefines.SUBMODEL_OPER_DATA_NAME).build());
keys.add(new DefaultKey.Builder().idType(KeyType.ID_SHORT).type(KeyElements.PROPERTY).value(TestDefines.ROTATION_SPEED_NAME).build());
Reference propRef = new DefaultReference.Builder().keys(keys).build();
ValueChangeEventMessage valueChangeMessage = new ValueChangeEventMessage();
valueChangeMessage.setElement(propRef);
// PropertyValue propertyValue = new PropertyValue();
// propertyValue.setValue(new IntValue(oldValue));
valueChangeMessage.setOldValue(PropertyValue.of(Datatype.Int, oldValue.toString()));
// propertyValue.setValue(new IntValue(newValue));
valueChangeMessage.setNewValue(PropertyValue.of(Datatype.Int, newValue.toString()));
service.getMessageBus().publish(valueChangeMessage);
Thread.sleep(100);
// check MessageBus
condition.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
Assert.assertEquals(valueChangeMessage, response.get());
// read new value
value = client.readValue(targets[0].getTargetId());
Assert.assertEquals(StatusCode.GOOD, value.getStatusCode());
Assert.assertEquals("new value not equal", newValue, value.getValue().getValue());
System.out.println("disconnect client");
client.disconnect();
}
use of com.prosysopc.ua.StatusException in project FAAAST-Service by FraunhoferIOSB.
the class AasServiceNodeManager method subscribeMessageBus.
/**
* Subscribes to Events on the MessageBus (e.g. ValueChangeEvents).
*/
private void subscribeMessageBus() {
try {
if (messageBus != null) {
logger.debug("subscribeMessageBus: subscribe ValueChangeEvents");
SubscriptionInfo info = SubscriptionInfo.create(ValueChangeEventMessage.class, (t) -> {
try {
valueChanged(t.getElement(), t.getNewValue(), t.getOldValue());
} catch (StatusException ex2) {
logger.error("valueChanged Exception", ex2);
}
});
SubscriptionId rv = messageBus.subscribe(info);
subscriptions.add(rv);
info = SubscriptionInfo.create(ElementCreateEventMessage.class, (x) -> {
try {
elementCreated(x.getElement(), x.getValue());
} catch (Exception ex3) {
logger.error("elementCreated Exception", ex3);
}
});
rv = messageBus.subscribe(info);
subscriptions.add(rv);
info = SubscriptionInfo.create(ElementDeleteEventMessage.class, (x) -> {
try {
elementDeleted(x.getElement());
} catch (Exception ex3) {
logger.error("elementDeleted Exception", ex3);
}
});
rv = messageBus.subscribe(info);
subscriptions.add(rv);
info = SubscriptionInfo.create(ElementUpdateEventMessage.class, (x) -> {
try {
elementUpdated(x.getElement(), x.getValue());
} catch (Exception ex3) {
logger.error("elementUpdated Exception", ex3);
}
});
rv = messageBus.subscribe(info);
subscriptions.add(rv);
} else {
logger.warn("MessageBus not available!");
}
} catch (Throwable ex) {
logger.error("subscribeMessageBus Exception", ex);
throw ex;
}
}
Aggregations