use of io.adminshell.aas.v3.model.Asset in project FAAAST-Service by FraunhoferIOSB.
the class ReferenceHelper method completeReferenceWithProperKeyElements.
/**
* Browse the keys of a reference and try to find the referenced element in the
* asset administration shell environment to set the right {@link io.adminshell.aas.v3.model.KeyElements}
* of the key.
* All key types must be null or SUBMODEL_ELEMENT.
*
* @param reference with keys which should be completed
* @param env the asset administration shell environment which contains the referenced elements
* @throws ResourceNotFoundException if an element referenced by a key could not be found
*/
public static void completeReferenceWithProperKeyElements(Reference reference, AssetAdministrationShellEnvironment env) throws ResourceNotFoundException {
if (reference == null) {
return;
}
List<Key> keys = reference.getKeys();
if (keys.stream().allMatch(x -> x.getType() != null && x.getType() != KeyElements.SUBMODEL_ELEMENT)) {
return;
}
final Referable[] parent = { null };
for (Key k : keys) {
if (env.getAssetAdministrationShells().stream().anyMatch(x -> x.getIdentification().getIdentifier().equalsIgnoreCase(k.getValue()) || x.getIdShort().equalsIgnoreCase(k.getValue()))) {
k.setType(KeyElements.ASSET_ADMINISTRATION_SHELL);
continue;
}
env.getSubmodels().forEach(x -> {
if (x.getIdentification().getIdentifier().equalsIgnoreCase(k.getValue()) || x.getIdShort().equalsIgnoreCase(k.getValue())) {
k.setType(KeyElements.SUBMODEL);
parent[0] = x;
}
});
if (k.getType() != null && k.getType() != KeyElements.SUBMODEL_ELEMENT) {
continue;
}
if (env.getConceptDescriptions().stream().anyMatch(x -> x.getIdentification().getIdentifier().equalsIgnoreCase(k.getValue()) || x.getIdShort().equalsIgnoreCase(k.getValue()))) {
k.setType(KeyElements.CONCEPT_DESCRIPTION);
continue;
}
if (env.getAssets().stream().anyMatch(x -> x.getIdentification().getIdentifier().equalsIgnoreCase(k.getValue()) || x.getIdShort().equalsIgnoreCase(k.getValue()))) {
k.setType(KeyElements.ASSET);
continue;
}
if (parent[0] != null && Submodel.class.isAssignableFrom(parent[0].getClass())) {
Submodel submodel = (Submodel) parent[0];
submodel.getSubmodelElements().forEach(y -> {
if (y.getIdShort().equalsIgnoreCase(k.getValue())) {
k.setType(AasUtils.referableToKeyType(y));
parent[0] = y;
}
});
} else if (SubmodelElementCollection.class.isAssignableFrom(parent[0].getClass())) {
((SubmodelElementCollection) parent[0]).getValues().forEach(x -> {
if (x.getIdShort().equalsIgnoreCase(k.getValue())) {
k.setType(AasUtils.referableToKeyType(x));
parent[0] = x;
}
});
} else if (Operation.class.isAssignableFrom(parent[0].getClass())) {
Operation operation = (Operation) parent[0];
Stream.concat(Stream.concat(operation.getInoutputVariables().stream(), operation.getInputVariables().stream()), operation.getOutputVariables().stream()).forEach(x -> {
if (x.getValue().getIdShort().equalsIgnoreCase(k.getValue())) {
k.setType(AasUtils.referableToKeyType(x.getValue()));
parent[0] = x.getValue();
}
});
}
if (k.getType() == null) {
throw new ResourceNotFoundException("Resource with ID " + k.getValue() + " was not found!");
}
}
}
use of io.adminshell.aas.v3.model.Asset in project FAAAST-Service by FraunhoferIOSB.
the class IntegrationTestHttpEndpoint method testPUTAssetInformation.
@Test
public void testPUTAssetInformation() throws IOException, DeserializationException {
AssetAdministrationShell aas = environment.getAssetAdministrationShells().get(1);
AssetInformation expected = aas.getAssetInformation();
expected.setAssetKind(AssetKind.TYPE);
String url = HTTP_SHELLS + "/" + Base64.getUrlEncoder().encodeToString(aas.getIdentification().getIdentifier().getBytes(StandardCharsets.UTF_8)) + "/aas/asset-information";
HttpResponse response = putCall(url, expected);
// TODO: StatusCode of spec seems to be wrong 204
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
AssetInformation actual = getCall(url, AssetInformation.class);
Assert.assertEquals(expected, actual);
}
use of io.adminshell.aas.v3.model.Asset in project FAAAST-Service by FraunhoferIOSB.
the class Application method run.
@Override
public void run() {
try {
ConfigFactory configFactory = new ConfigFactory();
AASEnvironmentFactory environmentFactory = new AASEnvironmentFactory();
readConfigurationParametersOverEnvironmentVariables();
readFilePathsOverEnvironmentVariables();
List<Config> customConfigComponents = getCustomConfigComponents();
ServiceConfig config = configFactory.toServiceConfig(configFilePath, autoCompleteConfiguration, properties, customConfigComponents);
AssetAdministrationShellEnvironment environment = null;
if (useEmptyAASEnvironment) {
LOGGER.info("Using empty Asset Administration Shell Environment");
environment = environmentFactory.getEmptyAASEnvironment();
} else {
environment = environmentFactory.getAASEnvironment(aasEnvironmentFilePath);
LOGGER.info("Successfully parsed Asset Administration Shell Environment");
}
if (validateAASEnv) {
validate(environment);
}
service = new Service(config);
service.setAASEnvironment(environment);
service.start();
LOGGER.info("FAAAST Service is running!");
} catch (Exception ex) {
if (service != null) {
service.stop();
}
LOGGER.error(ex.getMessage());
LOGGER.error("Abort starting FAAAST Service");
}
}
use of io.adminshell.aas.v3.model.Asset in project FAAAST-Service by FraunhoferIOSB.
the class AASEnvironmentFactory method getAASEnvironment.
/**
* Parses the content in the given file path to an
* {@link io.adminshell.aas.v3.model.AssetAdministrationShellEnvironment}.
* Supported formats of the file:
* <p>
* <ul>
* <li>json
* <li>aml
* <li>xml
* <li>opcua nodeset (also as .xml)
* <li>rdf
* <li>json-ld
* </ul>
* The method retrieves the right deserializer and parses the content to an
* {@link io.adminshell.aas.v3.model.AssetAdministrationShellEnvironment}.
*
* @param envFilePath of the file which contains the Asset Administration Shell Environment
* @return the parsed Asset Administration Shell Environment object
* @throws Exception
*/
public AssetAdministrationShellEnvironment getAASEnvironment(String envFilePath) throws Exception {
initDeserializer();
String env = getFileContent(envFilePath);
LOGGER.info("Try to resolve Asset Administration Shell Environment from file '" + envFilePath + "'");
AssetAdministrationShellEnvironment parsedEnvironment = guessDeserializerAndTryToParse(envFilePath, env);
if (parsedEnvironment != null) {
return parsedEnvironment;
}
// else try every deserializer
String formats = "";
for (Map.Entry<String, Deserializer> deserializer : deserializer.entrySet()) {
try {
LOGGER.debug("Try resolving with '" + deserializer.getValue().getClass().getSimpleName() + "'");
formats += "\t" + deserializer.getKey() + "\n";
return deserializer.getValue().read(env);
} catch (DeserializationException ex) {
}
}
throw new Exception("Could not deserialize content to an Asset Administration Shell Environment. Used File: " + envFilePath + "\nSupported Formats:\n" + formats);
}
use of io.adminshell.aas.v3.model.Asset in project FAAAST-Service by FraunhoferIOSB.
the class OpcUaAssetConnection method registerOperationProvider.
/**
* {@inheritdoc}
*
* @throws AssetConnectionException if nodeId could not be parsed
* @throws AssetConnectionException if nodeId does not refer to a method
* node
* @throws AssetConnectionException if parent node of nodeId could not be
* resolved
* @throws AssetConnectionException if output variables are null or do
* contain any other type than
* {@link de.fraunhofer.iosb.ilt.faaast.service.model.value.PropertyValue}
*/
@Override
public void registerOperationProvider(Reference reference, OpcUaOperationProviderConfig operationProvider) throws AssetConnectionException {
String baseErrorMessage = "error registering operation provider";
final NodeId nodeId = parseNodeId(operationProvider.getNodeId());
final UaNode node;
try {
node = client.getAddressSpace().getNode(nodeId);
} catch (UaException ex) {
throw new AssetConnectionException(String.format("%s - could not resolve nodeId (nodeId: %s)", baseErrorMessage, operationProvider.getNodeId()), ex);
}
if (!UaMethodNode.class.isAssignableFrom(node.getClass())) {
throw new AssetConnectionException(String.format("%s - provided node must be a method (nodeId: %s", baseErrorMessage, operationProvider.getNodeId()));
}
final UaMethodNode methodNode = (UaMethodNode) node;
final NodeId parentNodeId;
try {
parentNodeId = client.getAddressSpace().getNode(nodeId).browseNodes(AddressSpace.BrowseOptions.builder().setBrowseDirection(BrowseDirection.Inverse).build()).get(0).getNodeId();
} catch (UaException ex) {
throw new AssetConnectionException(String.format("%s - could not resolve parent node (nodeId: %s)", baseErrorMessage, operationProvider.getNodeId()), ex);
}
final Argument[] methodArguments;
try {
methodArguments = methodNode.readInputArgumentsAsync().get() != null ? methodNode.readInputArgumentsAsync().get() : new Argument[0];
} catch (InterruptedException | ExecutionException ex) {
throw new AssetConnectionException(String.format("%s - could not read input arguments (nodeId: %s)", baseErrorMessage, operationProvider.getNodeId()), ex);
}
final Argument[] methodOutputArguments;
try {
methodOutputArguments = methodNode.readOutputArgumentsAsync().get() != null ? methodNode.readOutputArgumentsAsync().get() : new Argument[0];
} catch (InterruptedException | ExecutionException ex) {
throw new AssetConnectionException(String.format("%s - could not read ouput arguments (nodeId: %s)", baseErrorMessage, operationProvider.getNodeId()), ex);
}
final OperationVariable[] outputVariables = serviceContext.getOperationOutputVariables(reference) != null ? serviceContext.getOperationOutputVariables(reference) : new OperationVariable[0];
for (var outputVariable : outputVariables) {
if (outputVariable == null) {
throw new AssetConnectionException(String.format("%s - output variable must be non-null (nodeId: %s)", baseErrorMessage, operationProvider.getNodeId()));
}
SubmodelElement submodelElement = outputVariable.getValue();
if (submodelElement == null) {
throw new AssetConnectionException(String.format("%s - output variable must contain non-null submodel element (nodeId: %s)", baseErrorMessage, operationProvider.getNodeId()));
}
if (!Property.class.isAssignableFrom(submodelElement.getClass())) {
throw new AssetConnectionException(String.format("%s - unsupported element type (nodeId: %s, element type: %s)", baseErrorMessage, submodelElement.getClass(), operationProvider.getNodeId()));
}
}
this.operationProviders.put(reference, new AssetOperationProvider() {
@Override
public OperationVariable[] invoke(OperationVariable[] input, OperationVariable[] inoutput) throws AssetConnectionException {
String baseErrorMessage = "error invoking operation on asset connection";
Map<String, ElementValue> inputParameter = input == null ? new HashMap<>() : Stream.of(input).collect(Collectors.toMap(x -> x.getValue().getIdShort(), x -> ElementValueMapper.toValue(x.getValue())));
Map<String, ElementValue> inoutputParameter = inoutput == null ? new HashMap<>() : Stream.of(inoutput).collect(Collectors.toMap(x -> x.getValue().getIdShort(), x -> ElementValueMapper.toValue(x.getValue())));
if (methodArguments.length != (inputParameter.size() + inoutputParameter.size())) {
throw new AssetConnectionException(String.format("%s - argument count mismatch (expected: %d, provided input arguments: %d, provided inoutput arguments: %d)", baseErrorMessage, methodArguments.length, inputParameter.size(), inoutputParameter.size()));
}
Variant[] actualParameters = new Variant[methodArguments.length];
for (int i = 0; i < methodArguments.length; i++) {
String argumentName = methodArguments[i].getName();
ElementValue parameterValue;
if (inputParameter.containsKey(argumentName)) {
parameterValue = inputParameter.get(argumentName);
} else if (inoutputParameter.containsKey(argumentName)) {
parameterValue = inoutputParameter.get(argumentName);
} else {
throw new AssetConnectionException(String.format("%s - missing argument (argument name: %s)", baseErrorMessage, argumentName));
}
if (parameterValue == null) {
throw new AssetConnectionException(String.format("%s - parameter value must be non-null (argument name: %s)", baseErrorMessage, argumentName));
}
if (!PropertyValue.class.isAssignableFrom(parameterValue.getClass())) {
throw new AssetConnectionException(String.format("%s - currently only parameters of the Property are supported (argument name: %s, provided type: %s)", baseErrorMessage, argumentName, parameterValue.getClass()));
}
actualParameters[i] = valueConverter.convert(((PropertyValue) parameterValue).getValue(), methodArguments[i].getDataType());
}
CallMethodResult methodResult;
try {
methodResult = client.call(new CallMethodRequest(parentNodeId, nodeId, actualParameters)).get();
} catch (InterruptedException | ExecutionException ex) {
throw new AssetConnectionException(String.format("%s - executing OPC UA method failed (nodeId: %s)", baseErrorMessage, operationProvider.getNodeId()));
}
OperationVariable[] result = new OperationVariable[outputVariables.length];
for (int i = 0; i < methodOutputArguments.length; i++) {
String argumentName = methodArguments[i].getName();
for (int j = 0; j < outputVariables.length; j++) {
if (Objects.equals(argumentName, outputVariables[j].getValue().getIdShort())) {
SubmodelElement element = outputVariables[j].getValue();
Datatype targetType = ((PropertyValue) ElementValueMapper.toValue(element)).getValue().getDataType();
TypedValue<?> newValue = valueConverter.convert(methodResult.getOutputArguments()[i], targetType);
// TODO better use deep copy?
DefaultProperty newProperty = new DefaultProperty.Builder().idShort(element.getIdShort()).build();
ElementValueMapper.setValue(newProperty, PropertyValue.builder().value(newValue).build());
result[j] = new DefaultOperationVariable.Builder().value(newProperty).build();
}
}
// update inoutput variable values
if (inoutputParameter.containsKey(argumentName)) {
// find in original array and set there
for (int j = 0; j < inoutput.length; j++) {
if (Objects.equals(argumentName, inoutput[j].getValue().getIdShort())) {
ElementValueMapper.setValue(inoutput[j].getValue(), new PropertyValue(valueConverter.convert(methodResult.getOutputArguments()[i], ((PropertyValue) inoutputParameter.get(argumentName)).getValue().getDataType())));
}
}
}
}
return result;
}
});
}
Aggregations