Search in sources :

Example 1 with TypeInfo

use of de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo in project FAAAST-Service by FraunhoferIOSB.

the class ContextAwareElementValueDeserializer method deserializeChildren.

/**
 * Deserialize children as a map of element values with their idShort as
 * key.
 *
 * @param <T> element value type
 * @param node node to deserialize
 * @param context deserialization context
 * @param type target type
 * @return map of sub-values identified by their idShort as key
 * @throws IOException as reading node fails
 */
protected <T extends ElementValue> Map<String, T> deserializeChildren(JsonNode node, DeserializationContext context, Class<T> type) throws IOException {
    Map<String, T> result = new HashMap<>();
    if (node == null) {
        return result;
    }
    TypeInfo typeInfo = getTypeInfo(context);
    Map<String, JsonNode> childNodes = new HashMap<>();
    if (node.isObject()) {
        node.fields().forEachRemaining(x -> childNodes.put(x.getKey(), x.getValue()));
    } else if (node.isArray()) {
        Iterator<JsonNode> iterator = node.elements();
        while (iterator.hasNext()) {
            Map.Entry<String, JsonNode> child = iterator.next().fields().next();
            childNodes.put(child.getKey(), child.getValue());
        }
    }
    for (Map.Entry<String, JsonNode> childNode : childNodes.entrySet()) {
        TypeInfo childTypeInfo = (TypeInfo) typeInfo.getElements().get(childNode.getKey());
        if (childTypeInfo == null || childTypeInfo.getType() == null) {
            throw new RuntimeException(String.format("no type information found for element (idShort: %s)", childNode.getKey()));
        }
        result.put(childNode.getKey(), (T) context.setAttribute(VALUE_TYPE_CONTEXT, childTypeInfo).readTreeAsValue(childNode.getValue(), childTypeInfo.getType()));
    }
    return result;
}
Also used : HashMap(java.util.HashMap) Iterator(java.util.Iterator) JsonNode(com.fasterxml.jackson.databind.JsonNode) TypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with TypeInfo

use of de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo in project FAAAST-Service by FraunhoferIOSB.

the class ValueMapDeserializer method deserialize.

@Override
public Map<Object, Object> deserialize(JsonParser parser, DeserializationContext context, Map<Object, Object> result) throws IOException {
    TypeInfo typeInfo = ContextAwareElementValueDeserializer.getTypeInfo(context);
    if (typeInfo == null || !ContainerTypeInfo.class.isAssignableFrom(typeInfo.getClass())) {
        return super.deserialize(parser, context);
    }
    JsonNode node = context.readTree(parser);
    if (!node.isObject()) {
        return context.reportBadDefinition(Collection.class, "expected array");
    }
    if (node.size() != typeInfo.getElements().size()) {
        return context.reportBadDefinition(Collection.class, String.format("number of elements mismatch (expected: %d, actual: %d)", typeInfo.getElements().size(), node.size()));
    }
    Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();
    int i = 0;
    while (iterator.hasNext()) {
        Map.Entry<String, JsonNode> element = iterator.next();
        context.setAttribute(ContextAwareElementValueDeserializer.VALUE_TYPE_CONTEXT, typeInfo.getElements().get(element.getKey()));
        Class type = ((TypeInfo) typeInfo.getElements().get(element.getKey())).getType();
        result.put(element.getKey(), context.readTreeAsValue(element.getValue(), type));
        i++;
    }
    return result;
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) TypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo) ContainerTypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.ContainerTypeInfo) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with TypeInfo

use of de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo in project FAAAST-Service by FraunhoferIOSB.

the class JsonDeserializerTest method compareValueList.

private void compareValueList(Map<SubmodelElement, File> input) throws DeserializationException, IOException {
    List<Object> expected = input.keySet().stream().map(x -> ElementValueMapper.toValue(x)).collect(Collectors.toList());
    TypeInfo typeInfo = TypeExtractor.extractTypeInfo(input.keySet());
    List<ElementValue> actual = deserializer.readValueList(filesAsJsonArray(input), typeInfo);
    Assert.assertEquals(expected, actual);
}
Also used : SubmodelElement(io.adminshell.aas.v3.model.SubmodelElement) TypeExtractor(de.fraunhofer.iosb.ilt.faaast.service.typing.TypeExtractor) ElementValueMapper(de.fraunhofer.iosb.ilt.faaast.service.model.value.mapper.ElementValueMapper) Datatype(de.fraunhofer.iosb.ilt.faaast.service.model.value.primitive.Datatype) IOException(java.io.IOException) Test(org.junit.Test) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Level(java.util.logging.Level) List(java.util.List) DeserializationException(de.fraunhofer.iosb.ilt.faaast.service.dataformat.DeserializationException) RangeValue(de.fraunhofer.iosb.ilt.faaast.service.model.value.RangeValue) ElementValue(de.fraunhofer.iosb.ilt.faaast.service.model.value.ElementValue) PropertyValues(de.fraunhofer.iosb.ilt.faaast.service.serialization.json.fixture.PropertyValues) Map(java.util.Map) JsonDeserializer(de.fraunhofer.iosb.ilt.faaast.service.dataformat.json.JsonDeserializer) TypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo) PropertyValue(de.fraunhofer.iosb.ilt.faaast.service.model.value.PropertyValue) Assert(org.junit.Assert) ElementValue(de.fraunhofer.iosb.ilt.faaast.service.model.value.ElementValue) TypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo)

Example 4 with TypeInfo

use of de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo in project FAAAST-Service by FraunhoferIOSB.

the class OpcUaAssetConnectionTest method testSubscribe.

private void testSubscribe(String nodeId, PropertyValue expected) throws AssetConnectionException, InterruptedException, ExecutionException, UaException {
    Reference reference = AasUtils.parseReference("(Property)[ID_SHORT]Temperature");
    long interval = 1000;
    ServiceContext serviceContext = mock(ServiceContext.class);
    TypeInfo infoExample = ElementValueTypeInfo.builder().type(PropertyValue.class).datatype(expected.getValue().getDataType()).build();
    doReturn(infoExample).when(serviceContext).getTypeInfo(reference);
    OpcUaAssetConnection connection = new OpcUaAssetConnection();
    connection.init(CoreConfig.builder().build(), OpcUaAssetConnectionConfig.builder().host(serverUrl).subscriptionProvider(reference, OpcUaSubscriptionProviderConfig.builder().nodeId(nodeId).interval(interval).build()).valueProvider(reference, OpcUaValueProviderConfig.builder().nodeId(nodeId).build()).build(), serviceContext);
    final AtomicReference<DataElementValue> response = new AtomicReference<>();
    CountDownLatch condition = new CountDownLatch(1);
    connection.getSubscriptionProviders().get(reference).addNewDataListener(new NewDataListener() {

        @Override
        public void newDataReceived(DataElementValue data) {
            response.set(data);
            condition.countDown();
        }
    });
    connection.getValueProviders().get(reference).setValue(expected);
    long waitTime = 5 * interval;
    TimeUnit waitTimeUnit = isDebugging() ? TimeUnit.SECONDS : TimeUnit.MILLISECONDS;
    Assert.assertTrue(String.format("test failed because there was no response within defined time (%d %s)", waitTime, waitTimeUnit), condition.await(waitTime, waitTimeUnit));
    Assert.assertEquals(expected, response.get());
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) Reference(io.adminshell.aas.v3.model.Reference) ServiceContext(de.fraunhofer.iosb.ilt.faaast.service.ServiceContext) NewDataListener(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.NewDataListener) TimeUnit(java.util.concurrent.TimeUnit) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ElementValueTypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.ElementValueTypeInfo) TypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo) DataElementValue(de.fraunhofer.iosb.ilt.faaast.service.model.value.DataElementValue)

Example 5 with TypeInfo

use of de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo in project FAAAST-Service by FraunhoferIOSB.

the class OpcUaAssetConnection method registerSubscriptionProvider.

/**
 * {@inheritdoc}
 *
 * @throws AssetConnectionException if reference does not point to a
 *             {@link io.adminshell.aas.v3.model.Property}
 * @throws AssetConnectionException if referenced
 *             {@link io.adminshell.aas.v3.model.Property} does not have datatype
 *             defined
 */
@Override
public void registerSubscriptionProvider(Reference reference, OpcUaSubscriptionProviderConfig subscriptionProvider) throws AssetConnectionException {
    final String baseErrorMessage = "error registering subscription provider";
    TypeInfo typeInfo = serviceContext.getTypeInfo(reference);
    if (typeInfo == null) {
        throw new AssetConnectionException(String.format("%s - could not resolve type information (reference: %s)", baseErrorMessage, AasUtils.asString(reference)));
    }
    if (!ElementValueTypeInfo.class.isAssignableFrom(typeInfo.getClass())) {
        throw new AssetConnectionException(String.format("%s - reference must point to element with value (reference: %s)", baseErrorMessage, AasUtils.asString(reference)));
    }
    ElementValueTypeInfo valueTypeInfo = (ElementValueTypeInfo) typeInfo;
    if (!PropertyValue.class.isAssignableFrom(valueTypeInfo.getType())) {
        throw new AssetConnectionException(String.format("%s - unsupported element type (reference: %s, element type: %s)", baseErrorMessage, AasUtils.asString(reference), valueTypeInfo.getType()));
    }
    final Datatype datatype = valueTypeInfo.getDatatype();
    if (datatype == null) {
        throw new AssetConnectionException(String.format("%s - missing datatype (reference: %s)", baseErrorMessage, AasUtils.asString(reference)));
    }
    this.subscriptionProviders.put(reference, new AssetSubscriptionProvider() {

        @Override
        public void addNewDataListener(NewDataListener listener) throws AssetConnectionException {
            if (!subscriptions.containsKey(subscriptionProvider.getNodeId())) {
                SubscriptionHandler handler = new SubscriptionHandler();
                handler.datatype = datatype;
                try {
                    handler.originalValue = client.readValue(0, TimestampsToReturn.Neither, client.getAddressSpace().getVariableNode(parseNodeId(subscriptionProvider.getNodeId())).getNodeId()).get();
                } catch (UaException | InterruptedException | ExecutionException ex) {
                    logger.warn("{} - reading initial value of subscribed node failed (reference: {}, nodeId: {})", baseErrorMessage, AasUtils.asString(reference), subscriptionProvider.getNodeId());
                }
                try {
                    handler.dataItem = opcUaSubscription.createDataItem(parseNodeId(subscriptionProvider.getNodeId()), LambdaExceptionHelper.rethrowConsumer(x -> {
                        x.addDataValueListener(LambdaExceptionHelper.rethrowConsumer(v -> handler.notify(v)));
                    }));
                } catch (UaException ex) {
                    logger.warn("{} - could not create subscrption item (reference: {}, nodeId: {})", baseErrorMessage, AasUtils.asString(reference), subscriptionProvider.getNodeId());
                }
                subscriptions.put(subscriptionProvider.getNodeId(), handler);
            }
            List<NewDataListener> listeners = subscriptions.get(subscriptionProvider.getNodeId()).listeners;
            if (!listeners.contains(listener)) {
                listeners.add(listener);
            }
        }

        @Override
        public void removeNewDataListener(NewDataListener listener) throws AssetConnectionException {
            if (subscriptions.containsKey(subscriptionProvider.getNodeId())) {
                SubscriptionHandler handler = subscriptions.get(subscriptionProvider.getNodeId());
                if (handler.listeners.contains(listener)) {
                    handler.listeners.remove(listener);
                }
                if (handler.listeners.isEmpty()) {
                    try {
                        handler.dataItem.delete();
                        subscriptions.remove(subscriptionProvider.getNodeId());
                    } catch (UaException ex) {
                        throw new AssetConnectionException(String.format("%s - removing subscription failed (reference: %s, nodeId: %s)", baseErrorMessage, AasUtils.asString(reference), subscriptionProvider.getNodeId()), ex);
                    }
                }
            }
        }
    });
}
Also used : SubmodelElement(io.adminshell.aas.v3.model.SubmodelElement) ValueConversionException(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.opcua.conversion.ValueConversionException) DataElementValue(de.fraunhofer.iosb.ilt.faaast.service.model.value.DataElementValue) VariableNode(org.eclipse.milo.opcua.sdk.core.nodes.VariableNode) LoggerFactory(org.slf4j.LoggerFactory) CallMethodResult(org.eclipse.milo.opcua.stack.core.types.structured.CallMethodResult) AddressSpace(org.eclipse.milo.opcua.sdk.client.AddressSpace) DefaultProperty(io.adminshell.aas.v3.model.impl.DefaultProperty) NewDataListener(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.NewDataListener) Argument(org.eclipse.milo.opcua.stack.core.types.structured.Argument) ManagedDataItem(org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedDataItem) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) Property(io.adminshell.aas.v3.model.Property) Map(java.util.Map) AssetConnection(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.AssetConnection) UaMethodNode(org.eclipse.milo.opcua.sdk.client.nodes.UaMethodNode) ManagedSubscription(org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedSubscription) AnonymousProvider(org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) BrowseDirection(org.eclipse.milo.opcua.stack.core.types.enumerated.BrowseDirection) Reference(io.adminshell.aas.v3.model.Reference) Collectors(java.util.stream.Collectors) AssetConnectionException(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.AssetConnectionException) AasUtils(io.adminshell.aas.v3.dataformat.core.util.AasUtils) TypedValue(de.fraunhofer.iosb.ilt.faaast.service.model.value.primitive.TypedValue) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) Variant(org.eclipse.milo.opcua.stack.core.types.builtin.Variant) CoreConfig(de.fraunhofer.iosb.ilt.faaast.service.config.CoreConfig) ElementValue(de.fraunhofer.iosb.ilt.faaast.service.model.value.ElementValue) UaNode(org.eclipse.milo.opcua.sdk.client.nodes.UaNode) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) TypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo) Optional(java.util.Optional) ElementValueTypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.ElementValueTypeInfo) CallMethodRequest(org.eclipse.milo.opcua.stack.core.types.structured.CallMethodRequest) DefaultOperationVariable(io.adminshell.aas.v3.model.impl.DefaultOperationVariable) DataValue(org.eclipse.milo.opcua.stack.core.types.builtin.DataValue) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) OperationVariable(io.adminshell.aas.v3.model.OperationVariable) ServiceContext(de.fraunhofer.iosb.ilt.faaast.service.ServiceContext) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) UShort(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UShort) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) AssetOperationProvider(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.AssetOperationProvider) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) Logger(org.slf4j.Logger) ElementValueMapper(de.fraunhofer.iosb.ilt.faaast.service.model.value.mapper.ElementValueMapper) Datatype(de.fraunhofer.iosb.ilt.faaast.service.model.value.primitive.Datatype) LocalizedText(org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText) ValueConverter(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.opcua.conversion.ValueConverter) AssetSubscriptionProvider(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.AssetSubscriptionProvider) ExecutionException(java.util.concurrent.ExecutionException) UaException(org.eclipse.milo.opcua.stack.core.UaException) LambdaExceptionHelper(de.fraunhofer.iosb.ilt.faaast.service.util.LambdaExceptionHelper) AssetValueProvider(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.AssetValueProvider) PropertyValue(de.fraunhofer.iosb.ilt.faaast.service.model.value.PropertyValue) UaException(org.eclipse.milo.opcua.stack.core.UaException) ElementValueTypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.ElementValueTypeInfo) PropertyValue(de.fraunhofer.iosb.ilt.faaast.service.model.value.PropertyValue) TypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo) ElementValueTypeInfo(de.fraunhofer.iosb.ilt.faaast.service.typing.ElementValueTypeInfo) Datatype(de.fraunhofer.iosb.ilt.faaast.service.model.value.primitive.Datatype) NewDataListener(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.NewDataListener) List(java.util.List) ArrayList(java.util.ArrayList) AssetConnectionException(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.AssetConnectionException) AssetSubscriptionProvider(de.fraunhofer.iosb.ilt.faaast.service.assetconnection.AssetSubscriptionProvider)

Aggregations

TypeInfo (de.fraunhofer.iosb.ilt.faaast.service.typing.TypeInfo)12 ElementValue (de.fraunhofer.iosb.ilt.faaast.service.model.value.ElementValue)6 Datatype (de.fraunhofer.iosb.ilt.faaast.service.model.value.primitive.Datatype)6 Map (java.util.Map)6 PropertyValue (de.fraunhofer.iosb.ilt.faaast.service.model.value.PropertyValue)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 ElementValueMapper (de.fraunhofer.iosb.ilt.faaast.service.model.value.mapper.ElementValueMapper)4 ElementValueTypeInfo (de.fraunhofer.iosb.ilt.faaast.service.typing.ElementValueTypeInfo)4 SubmodelElement (io.adminshell.aas.v3.model.SubmodelElement)4 IOException (java.io.IOException)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 DeserializationException (de.fraunhofer.iosb.ilt.faaast.service.dataformat.DeserializationException)3 JsonDeserializer (de.fraunhofer.iosb.ilt.faaast.service.dataformat.json.JsonDeserializer)3 DataElementValue (de.fraunhofer.iosb.ilt.faaast.service.model.value.DataElementValue)3 RangeValue (de.fraunhofer.iosb.ilt.faaast.service.model.value.RangeValue)3 PropertyValues (de.fraunhofer.iosb.ilt.faaast.service.serialization.json.fixture.PropertyValues)3 ContainerTypeInfo (de.fraunhofer.iosb.ilt.faaast.service.typing.ContainerTypeInfo)3 TypeExtractor (de.fraunhofer.iosb.ilt.faaast.service.typing.TypeExtractor)3 File (java.io.File)3