Search in sources :

Example 1 with MonitoringParameters

use of org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters in project milo by eclipse.

the class SubscriptionExample method run.

@Override
public void run(OpcUaClient client, CompletableFuture<OpcUaClient> future) throws Exception {
    // synchronous connect
    client.connect().get();
    // create a subscription @ 1000ms
    UaSubscription subscription = client.getSubscriptionManager().createSubscription(1000.0).get();
    // subscribe to the Value attribute of the server's CurrentTime node
    ReadValueId readValueId = new ReadValueId(Identifiers.Server_ServerStatus_CurrentTime, AttributeId.Value.uid(), null, QualifiedName.NULL_VALUE);
    // IMPORTANT: client handle must be unique per item within the context of a subscription.
    // You are not required to use the UaSubscription's client handle sequence; it is provided as a convenience.
    // Your application is free to assign client handles by whatever means necessary.
    UInteger clientHandle = subscription.nextClientHandle();
    MonitoringParameters parameters = new MonitoringParameters(clientHandle, // sampling interval
    1000.0, // filter, null means use default
    null, // queue size
    uint(10), // discard oldest
    true);
    MonitoredItemCreateRequest request = new MonitoredItemCreateRequest(readValueId, MonitoringMode.Reporting, parameters);
    // when creating items in MonitoringMode.Reporting this callback is where each item needs to have its
    // value/event consumer hooked up. The alternative is to create the item in sampling mode, hook up the
    // consumer after the creation call completes, and then change the mode for all items to reporting.
    UaSubscription.ItemCreationCallback onItemCreated = (item, id) -> item.setValueConsumer(this::onSubscriptionValue);
    List<UaMonitoredItem> items = subscription.createMonitoredItems(TimestampsToReturn.Both, newArrayList(request), onItemCreated).get();
    for (UaMonitoredItem item : items) {
        if (item.getStatusCode().isGood()) {
            logger.info("item created for nodeId={}", item.getReadValueId().getNodeId());
        } else {
            logger.warn("failed to create item for nodeId={} (status={})", item.getReadValueId().getNodeId(), item.getStatusCode());
        }
    }
    // let the example run for 5 seconds then terminate
    Thread.sleep(5000);
    future.complete(client);
}
Also used : MonitoringMode(org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode) MonitoringParameters(org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) Logger(org.slf4j.Logger) DataValue(org.eclipse.milo.opcua.stack.core.types.builtin.DataValue) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) ReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId) MonitoredItemCreateRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest) List(java.util.List) QualifiedName(org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) AttributeId(org.eclipse.milo.opcua.stack.core.AttributeId) UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) Identifiers(org.eclipse.milo.opcua.stack.core.Identifiers) UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) ReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId) MonitoredItemCreateRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) MonitoringParameters(org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters)

Example 2 with MonitoringParameters

use of org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters in project milo by eclipse.

the class EventSubscriptionExample method run.

@Override
public void run(OpcUaClient client, CompletableFuture<OpcUaClient> future) throws Exception {
    // synchronous connect
    client.connect().get();
    // create a subscription and a monitored item
    UaSubscription subscription = client.getSubscriptionManager().createSubscription(1000.0).get();
    ReadValueId readValueId = new ReadValueId(Identifiers.Server, AttributeId.EventNotifier.uid(), null, QualifiedName.NULL_VALUE);
    // client handle must be unique per item
    UInteger clientHandle = uint(clientHandles.getAndIncrement());
    EventFilter eventFilter = new EventFilter(new SimpleAttributeOperand[] { new SimpleAttributeOperand(Identifiers.BaseEventType, new QualifiedName[] { new QualifiedName(0, "EventId") }, AttributeId.Value.uid(), null), new SimpleAttributeOperand(Identifiers.BaseEventType, new QualifiedName[] { new QualifiedName(0, "EventType") }, AttributeId.Value.uid(), null), new SimpleAttributeOperand(Identifiers.BaseEventType, new QualifiedName[] { new QualifiedName(0, "Severity") }, AttributeId.Value.uid(), null), new SimpleAttributeOperand(Identifiers.BaseEventType, new QualifiedName[] { new QualifiedName(0, "Time") }, AttributeId.Value.uid(), null), new SimpleAttributeOperand(Identifiers.BaseEventType, new QualifiedName[] { new QualifiedName(0, "Message") }, AttributeId.Value.uid(), null) }, new ContentFilter(null));
    MonitoringParameters parameters = new MonitoringParameters(clientHandle, 0.0, ExtensionObject.encode(client.getStaticSerializationContext(), eventFilter), uint(10), true);
    MonitoredItemCreateRequest request = new MonitoredItemCreateRequest(readValueId, MonitoringMode.Reporting, parameters);
    List<UaMonitoredItem> items = subscription.createMonitoredItems(TimestampsToReturn.Both, newArrayList(request)).get();
    // do something with the value updates
    UaMonitoredItem monitoredItem = items.get(0);
    final AtomicInteger eventCount = new AtomicInteger(0);
    monitoredItem.setEventConsumer((item, vs) -> {
        logger.info("Event Received from {}", item.getReadValueId().getNodeId());
        for (int i = 0; i < vs.length; i++) {
            logger.info("\tvariant[{}]: {}", i, vs[i].getValue());
        }
        if (eventCount.incrementAndGet() == 3) {
            future.complete(client);
        }
    });
}
Also used : UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) MonitoredItemCreateRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest) QualifiedName(org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName) EventFilter(org.eclipse.milo.opcua.stack.core.types.structured.EventFilter) ContentFilter(org.eclipse.milo.opcua.stack.core.types.structured.ContentFilter) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) ReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId) SimpleAttributeOperand(org.eclipse.milo.opcua.stack.core.types.structured.SimpleAttributeOperand) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) MonitoringParameters(org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters)

Example 3 with MonitoringParameters

use of org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters in project milo by eclipse.

the class SubscriptionManager method modifyMonitoredItem.

private BaseMonitoredItem<?> modifyMonitoredItem(MonitoredItemModifyRequest request, TimestampsToReturn timestamps, Subscription subscription, Map<NodeId, AttributeGroup> attributeGroups) throws UaException {
    UInteger itemId = request.getMonitoredItemId();
    MonitoringParameters parameters = request.getRequestedParameters();
    BaseMonitoredItem<?> monitoredItem = subscription.getMonitoredItems().get(itemId);
    if (monitoredItem == null) {
        throw new UaException(StatusCodes.Bad_MonitoredItemIdInvalid);
    }
    NodeId nodeId = monitoredItem.getReadValueId().getNodeId();
    UInteger attributeId = monitoredItem.getReadValueId().getAttributeId();
    AttributeGroup attributeGroup = attributeGroups.get(nodeId);
    if (attributeId.equals(AttributeId.EventNotifier.uid())) {
        Object filterObject = request.getRequestedParameters().getFilter().decode(server.getSerializationContext());
        MonitoringFilter filter = validateEventItemFilter(filterObject, attributeGroup);
        UInteger requestedQueueSize = parameters.getQueueSize();
        AtomicReference<UInteger> revisedQueueSize = new AtomicReference<>(requestedQueueSize);
        try {
            server.getAddressSpaceManager().onModifyEventItem(monitoredItem.getReadValueId(), requestedQueueSize, revisedQueueSize::set);
        } catch (Throwable t) {
            throw new UaException(StatusCodes.Bad_InternalError, t);
        }
        monitoredItem.modify(timestamps, parameters.getClientHandle(), monitoredItem.getSamplingInterval(), filter, revisedQueueSize.get(), parameters.getDiscardOldest());
    } else {
        MonitoringFilter filter = MonitoredDataItem.DEFAULT_FILTER;
        try {
            ExtensionObject filterXo = request.getRequestedParameters().getFilter();
            if (filterXo != null && !filterXo.isNull()) {
                Object filterObject = filterXo.decode(server.getSerializationContext());
                filter = validateDataItemFilter(filterObject, attributeId, attributeGroup);
            }
        } catch (UaSerializationException e) {
            logger.debug("error decoding MonitoringFilter", e);
            throw new UaException(StatusCodes.Bad_MonitoredItemFilterInvalid, e);
        }
        Double minimumSamplingInterval = -1.0;
        try {
            minimumSamplingInterval = attributeGroup.getMinimumSamplingInterval();
            if (minimumSamplingInterval == null) {
                minimumSamplingInterval = server.getConfig().getLimits().getMinSupportedSampleRate();
            }
        } catch (UaException e) {
            long statusCodeValue = e.getStatusCode().getValue();
            if (statusCodeValue != StatusCodes.Bad_AttributeIdInvalid && statusCodeValue != StatusCodes.Bad_NodeIdUnknown) {
                throw e;
            }
        }
        double requestedSamplingInterval = getSamplingInterval(subscription, minimumSamplingInterval, request.getRequestedParameters().getSamplingInterval());
        UInteger requestedQueueSize = parameters.getQueueSize();
        AtomicReference<Double> revisedSamplingInterval = new AtomicReference<>(requestedSamplingInterval);
        AtomicReference<UInteger> revisedQueueSize = new AtomicReference<>(requestedQueueSize);
        try {
            server.getAddressSpaceManager().onModifyDataItem(monitoredItem.getReadValueId(), requestedSamplingInterval, requestedQueueSize, (rsi, rqs) -> {
                revisedSamplingInterval.set(rsi);
                revisedQueueSize.set(rqs);
            });
        } catch (Throwable t) {
            throw new UaException(StatusCodes.Bad_InternalError, t);
        }
        monitoredItem.modify(timestamps, parameters.getClientHandle(), revisedSamplingInterval.get(), filter, revisedQueueSize.get(), parameters.getDiscardOldest());
    }
    return monitoredItem;
}
Also used : UaSerializationException(org.eclipse.milo.opcua.stack.core.UaSerializationException) UaException(org.eclipse.milo.opcua.stack.core.UaException) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject) AtomicReference(java.util.concurrent.atomic.AtomicReference) MonitoringFilter(org.eclipse.milo.opcua.stack.core.types.structured.MonitoringFilter) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) MonitoringParameters(org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject)

Example 4 with MonitoringParameters

use of org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters in project milo by eclipse.

the class ManagedItem method setTimestampsToReturnAsync.

/**
 * Set a new {@link TimestampsToReturn} parameter on this item.
 * <p>
 * This call completes asynchronously.
 *
 * @param timestamps a new {@link TimestampsToReturn} parameter.
 * @return a {@link CompletableFuture} that completes successfully if the item was modified and completes
 * exceptionally if an operation- or service-level error occurs.
 */
public CompletableFuture<Unit> setTimestampsToReturnAsync(TimestampsToReturn timestamps) {
    MonitoringParameters parameters = new MonitoringParameters(monitoredItem.getClientHandle(), monitoredItem.getRevisedSamplingInterval(), monitoredItem.getMonitoringFilter(), monitoredItem.getRevisedQueueSize(), monitoredItem.getDiscardOldest());
    MonitoredItemModifyRequest modifyRequest = new MonitoredItemModifyRequest(monitoredItem.getMonitoredItemId(), parameters);
    CompletableFuture<List<StatusCode>> future = subscription.getSubscription().modifyMonitoredItems(timestamps, singletonList(modifyRequest));
    return future.thenApply(statusCodes -> statusCodes.get(0)).thenCompose(statusCode -> {
        if (statusCode.isGood()) {
            return completedFuture(Unit.VALUE);
        } else {
            return failedUaFuture(statusCode);
        }
    });
}
Also used : MonitoringMode(org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode) MonitoringParameters(org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters) ModifyMonitoredItemResult(org.eclipse.milo.opcua.sdk.client.subscriptions.BatchModifyMonitoredItems.ModifyMonitoredItemResult) SetMonitoringModeResult(org.eclipse.milo.opcua.sdk.client.subscriptions.BatchSetMonitoringMode.SetMonitoringModeResult) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) FutureUtils.failedUaFuture(org.eclipse.milo.opcua.stack.core.util.FutureUtils.failedUaFuture) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) CompletableFuture(java.util.concurrent.CompletableFuture) ReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId) Collections.singletonList(java.util.Collections.singletonList) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) MonitoredItemModifyRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemModifyRequest) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) Unit(org.eclipse.milo.opcua.stack.core.util.Unit) UaException(org.eclipse.milo.opcua.stack.core.UaException) Optional(java.util.Optional) UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) MonitoredItemModifyRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemModifyRequest) MonitoringParameters(org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List)

Example 5 with MonitoringParameters

use of org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters in project milo by eclipse.

the class BatchModifyMonitoredItems method executeAsync.

private CompletableFuture<List<ModifyMonitoredItemResult>> executeAsync(UInteger operationLimit) {
    List<BatchModifyParameters> allMonitoringParameters = buildersByItem.values().stream().map(BatchModifyParametersBuilder::build).collect(Collectors.toList());
    CompletableFuture<List<ModifyMonitoredItemResult>> resultsFuture = GroupMapCollate.groupMapCollate(allMonitoringParameters, parametersItem -> parametersItem.timestamps, (TimestampsToReturn timestampsKey) -> parameterGroup -> {
        List<MonitoredItemModifyRequest> itemsToModify = parameterGroup.stream().map(parameters -> new MonitoredItemModifyRequest(parameters.item.getMonitoredItemId(), new MonitoringParameters(parameters.clientHandle, parameters.samplingInterval, parameters.filter, parameters.queueSize, parameters.discardOldest))).collect(Collectors.toList());
        List<CompletableFuture<List<ModifyMonitoredItemResult>>> partitionFutures = Lists.partition(itemsToModify, operationLimit.intValue()).stream().map(partition -> modifyItemsAsync(timestampsKey, partition)).collect(Collectors.toList());
        return FutureUtils.flatSequence(partitionFutures);
    });
    return resultsFuture.thenCompose(results -> {
        List<OpcUaMonitoredItem> items = new ArrayList<>(buildersByItem.keySet());
        assert items.size() == results.size();
        for (int i = 0; i < items.size(); i++) {
            OpcUaMonitoredItem item = items.get(i);
            ModifyMonitoredItemResult result = results.get(i);
            List<CompletableFuture<ModifyMonitoredItemResult>> futures;
            synchronized (futuresByItem) {
                futures = new ArrayList<>(futuresByItem.get(item));
            }
            futures.forEach(f -> f.complete(result));
        }
        return FutureUtils.sequence(resultFutures);
    });
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) MonitoringParameters(org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters) ListMultimap(com.google.common.collect.ListMultimap) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) CompletableFuture(java.util.concurrent.CompletableFuture) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject) GroupMapCollate(org.eclipse.milo.opcua.sdk.core.util.GroupMapCollate) ArrayList(java.util.ArrayList) Multimaps(com.google.common.collect.Multimaps) LinkedHashMap(java.util.LinkedHashMap) Lists(com.google.common.collect.Lists) MonitoredItemModifyRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemModifyRequest) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) AttributeId(org.eclipse.milo.opcua.stack.core.AttributeId) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) Consumer(java.util.function.Consumer) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) FutureUtils(org.eclipse.milo.opcua.stack.core.util.FutureUtils) UaException(org.eclipse.milo.opcua.stack.core.UaException) Optional(java.util.Optional) UaVariableNode(org.eclipse.milo.opcua.sdk.client.nodes.UaVariableNode) Collections(java.util.Collections) Identifiers(org.eclipse.milo.opcua.stack.core.Identifiers) MonitoredItemModifyRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemModifyRequest) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) ArrayList(java.util.ArrayList) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) List(java.util.List) MonitoringParameters(org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters)

Aggregations

MonitoringParameters (org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters)12 UInteger (org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger)11 List (java.util.List)10 CompletableFuture (java.util.concurrent.CompletableFuture)10 OpcUaClient (org.eclipse.milo.opcua.sdk.client.OpcUaClient)10 UaMonitoredItem (org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem)10 ReadValueId (org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId)10 ExecutionException (java.util.concurrent.ExecutionException)9 UaException (org.eclipse.milo.opcua.stack.core.UaException)9 TimestampsToReturn (org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn)9 NodeId (org.eclipse.milo.opcua.stack.core.types.builtin.NodeId)8 StatusCode (org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode)8 MonitoringMode (org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode)8 StatusCodes (org.eclipse.milo.opcua.stack.core.StatusCodes)7 Unsigned.uint (org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint)7 Collections.singletonList (java.util.Collections.singletonList)6 Optional (java.util.Optional)6 CompletableFuture.completedFuture (java.util.concurrent.CompletableFuture.completedFuture)6 UaSubscription (org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription)6 AttributeId (org.eclipse.milo.opcua.stack.core.AttributeId)6