Search in sources :

Example 1 with UaMonitoredItem

use of org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem 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 UaMonitoredItem

use of org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem in project milo by eclipse.

the class TriggeringExample 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 a static value that reports
    ReadValueId readValueId1 = new ReadValueId(new NodeId(2, "HelloWorld/ScalarTypes/Float"), AttributeId.Value.uid(), null, QualifiedName.NULL_VALUE);
    UaMonitoredItem reportingItem = createMonitoredItem(subscription, readValueId1, MonitoringMode.Reporting);
    // subscribe to a dynamic value that only samples
    ReadValueId readValueId2 = new ReadValueId(Identifiers.Server_ServerStatus_CurrentTime, AttributeId.Value.uid(), null, QualifiedName.NULL_VALUE);
    UaMonitoredItem samplingItem = createMonitoredItem(subscription, readValueId2, MonitoringMode.Sampling);
    subscription.addTriggeringLinks(reportingItem, newArrayList(samplingItem)).get();
    // trigger reporting of both by writing to the static item and changing its value
    client.writeValue(new NodeId(2, "HelloWorld/ScalarTypes/Float"), new DataValue(new Variant(1.0f))).get();
    // let the example run for 5 seconds then terminate
    Thread.sleep(5000);
    future.complete(client);
}
Also used : UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) Variant(org.eclipse.milo.opcua.stack.core.types.builtin.Variant) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) ReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId) DataValue(org.eclipse.milo.opcua.stack.core.types.builtin.DataValue) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId)

Example 3 with UaMonitoredItem

use of org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem 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 4 with UaMonitoredItem

use of org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem in project milo by eclipse.

the class BatchSetMonitoringMode method setMonitoringModeAsync.

private CompletableFuture<List<SetMonitoringModeResult>> setMonitoringModeAsync(List<Map.Entry<OpcUaMonitoredItem, MonitoringMode>> itemsAndModes) {
    serviceInvocationCount.incrementAndGet();
    MonitoringMode monitoringMode = itemsAndModes.get(0).getValue();
    List<UaMonitoredItem> items = itemsAndModes.stream().map(Map.Entry::getKey).collect(Collectors.toList());
    CompletableFuture<List<SetMonitoringModeResult>> resultsFuture = subscription.setMonitoringMode(monitoringMode, items).thenApply(statusCodes -> statusCodes.stream().map(statusCode -> new SetMonitoringModeResult(StatusCode.GOOD, statusCode)).collect(Collectors.toList()));
    return resultsFuture.exceptionally(ex -> {
        StatusCode serviceResult = UaException.extractStatusCode(ex).orElse(new StatusCode(StatusCodes.Bad_UnexpectedError));
        SetMonitoringModeResult result = new SetMonitoringModeResult(serviceResult);
        return Collections.nCopies(items.size(), result);
    });
}
Also used : UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) ArrayList(java.util.ArrayList) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) MonitoringMode(org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode)

Example 5 with UaMonitoredItem

use of org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem in project milo by eclipse.

the class OpcUaSubscriptionManager method deliverNotificationMessage.

private CompletableFuture<Unit> deliverNotificationMessage(OpcUaSubscription subscription, NotificationMessage notificationMessage) {
    CompletableFuture<Unit> delivered = new CompletableFuture<>();
    subscription.getNotificationSemaphore().acquire().thenAccept(permit -> deliveryQueue.submit(() -> {
        try {
            Map<UInteger, OpcUaMonitoredItem> items = subscription.getItemsByClientHandle();
            List<ExtensionObject> notificationData = l(notificationMessage.getNotificationData());
            if (notificationData.isEmpty()) {
                subscriptionListeners.forEach(listener -> listener.onKeepAlive(subscription, notificationMessage.getPublishTime()));
                subscription.getNotificationListeners().forEach(listener -> listener.onKeepAliveNotification(subscription, notificationMessage.getPublishTime()));
            }
            for (ExtensionObject xo : notificationData) {
                Object o = xo.decode(client.getStaticSerializationContext());
                if (o instanceof DataChangeNotification) {
                    DataChangeNotification dcn = (DataChangeNotification) o;
                    List<MonitoredItemNotification> monitoredItemNotifications = l(dcn.getMonitoredItems());
                    int notificationCount = monitoredItemNotifications.size();
                    logger.debug("Received {} MonitoredItemNotifications", notificationCount);
                    for (MonitoredItemNotification min : monitoredItemNotifications) {
                        logger.trace("MonitoredItemNotification: clientHandle={}, value={}", min.getClientHandle(), min.getValue());
                        OpcUaMonitoredItem item = items.get(min.getClientHandle());
                        if (item != null)
                            item.onValueArrived(min.getValue());
                        else
                            logger.warn("no item for clientHandle=" + min.getClientHandle());
                    }
                    if (notificationCount == 0) {
                        subscriptionListeners.forEach(listener -> listener.onKeepAlive(subscription, notificationMessage.getPublishTime()));
                        subscription.getNotificationListeners().forEach(listener -> listener.onKeepAliveNotification(subscription, notificationMessage.getPublishTime()));
                    } else {
                        if (!subscription.getNotificationListeners().isEmpty()) {
                            List<UaMonitoredItem> monitoredItems = new ArrayList<>();
                            List<DataValue> dataValues = new ArrayList<>();
                            for (MonitoredItemNotification n : monitoredItemNotifications) {
                                UaMonitoredItem item = subscription.getItemsByClientHandle().get(n.getClientHandle());
                                if (item != null) {
                                    monitoredItems.add(item);
                                    dataValues.add(n.getValue());
                                }
                            }
                            subscription.getNotificationListeners().forEach(listener -> listener.onDataChangeNotification(subscription, monitoredItems, dataValues, notificationMessage.getPublishTime()));
                        }
                    }
                } else if (o instanceof EventNotificationList) {
                    EventNotificationList enl = (EventNotificationList) o;
                    List<EventFieldList> eventFieldLists = l(enl.getEvents());
                    for (EventFieldList efl : eventFieldLists) {
                        logger.trace("EventFieldList: clientHandle={}, values={}", efl.getClientHandle(), Arrays.toString(efl.getEventFields()));
                        OpcUaMonitoredItem item = items.get(efl.getClientHandle());
                        if (item != null)
                            item.onEventArrived(efl.getEventFields());
                    }
                    if (!subscription.getNotificationListeners().isEmpty()) {
                        List<UaMonitoredItem> monitoredItems = new ArrayList<>();
                        List<Variant[]> eventFields = new ArrayList<>();
                        for (EventFieldList efl : eventFieldLists) {
                            UaMonitoredItem item = subscription.getItemsByClientHandle().get(efl.getClientHandle());
                            if (item != null) {
                                monitoredItems.add(item);
                                eventFields.add(efl.getEventFields());
                            }
                        }
                        subscription.getNotificationListeners().forEach(listener -> listener.onEventNotification(subscription, monitoredItems, eventFields, notificationMessage.getPublishTime()));
                    }
                } else if (o instanceof StatusChangeNotification) {
                    StatusChangeNotification scn = (StatusChangeNotification) o;
                    logger.debug("StatusChangeNotification: {}", scn.getStatus());
                    subscriptionListeners.forEach(listener -> listener.onStatusChanged(subscription, scn.getStatus()));
                    subscription.getNotificationListeners().forEach(listener -> listener.onStatusChangedNotification(subscription, scn.getStatus()));
                    if (scn.getStatus().getValue() == StatusCodes.Bad_Timeout) {
                        subscriptions.remove(subscription.getSubscriptionId());
                    }
                }
            }
        } finally {
            permit.release();
            delivered.complete(Unit.VALUE);
        }
    }));
    return delivered;
}
Also used : Arrays(java.util.Arrays) ScheduledFuture(java.util.concurrent.ScheduledFuture) BiFunction(java.util.function.BiFunction) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) UaSubscriptionManager(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscriptionManager) LoggerFactory(org.slf4j.LoggerFactory) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject) PublishRequest(org.eclipse.milo.opcua.stack.core.types.structured.PublishRequest) DateTime(org.eclipse.milo.opcua.stack.core.types.builtin.DateTime) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) Unit(org.eclipse.milo.opcua.stack.core.util.Unit) Map(java.util.Map) BigInteger(java.math.BigInteger) CreateSubscriptionResponse(org.eclipse.milo.opcua.stack.core.types.structured.CreateSubscriptionResponse) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) UByte(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UByte) EventNotificationList(org.eclipse.milo.opcua.stack.core.types.structured.EventNotificationList) RepublishResponse(org.eclipse.milo.opcua.stack.core.types.structured.RepublishResponse) SubscriptionAcknowledgement(org.eclipse.milo.opcua.stack.core.types.structured.SubscriptionAcknowledgement) List(java.util.List) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) Variant(org.eclipse.milo.opcua.stack.core.types.builtin.Variant) EventFieldList(org.eclipse.milo.opcua.stack.core.types.structured.EventFieldList) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) UaSession(org.eclipse.milo.opcua.sdk.client.api.UaSession) DataValue(org.eclipse.milo.opcua.stack.core.types.builtin.DataValue) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) NotificationMessage(org.eclipse.milo.opcua.stack.core.types.structured.NotificationMessage) CompletableFuture(java.util.concurrent.CompletableFuture) DataChangeNotification(org.eclipse.milo.opcua.stack.core.types.structured.DataChangeNotification) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) RequestHeader(org.eclipse.milo.opcua.stack.core.types.structured.RequestHeader) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) ConversionUtil.l(org.eclipse.milo.opcua.stack.core.util.ConversionUtil.l) UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) FutureUtils.failedUaFuture(org.eclipse.milo.opcua.stack.core.util.FutureUtils.failedUaFuture) SessionActivityListener(org.eclipse.milo.opcua.sdk.client.SessionActivityListener) StatusChangeNotification(org.eclipse.milo.opcua.stack.core.types.structured.StatusChangeNotification) ExecutionQueue(org.eclipse.milo.opcua.stack.core.util.ExecutionQueue) Logger(org.slf4j.Logger) MonitoredItemNotification(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemNotification) PublishResponse(org.eclipse.milo.opcua.stack.core.types.structured.PublishResponse) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) Maps(com.google.common.collect.Maps) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) ModifySubscriptionResponse(org.eclipse.milo.opcua.stack.core.types.structured.ModifySubscriptionResponse) UaException(org.eclipse.milo.opcua.stack.core.UaException) Comparator(java.util.Comparator) Collections(java.util.Collections) UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) MonitoredItemNotification(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemNotification) EventNotificationList(org.eclipse.milo.opcua.stack.core.types.structured.EventNotificationList) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) ArrayList(java.util.ArrayList) DataChangeNotification(org.eclipse.milo.opcua.stack.core.types.structured.DataChangeNotification) StatusChangeNotification(org.eclipse.milo.opcua.stack.core.types.structured.StatusChangeNotification) Unit(org.eclipse.milo.opcua.stack.core.util.Unit) TimeUnit(java.util.concurrent.TimeUnit) CompletableFuture(java.util.concurrent.CompletableFuture) EventFieldList(org.eclipse.milo.opcua.stack.core.types.structured.EventFieldList) EventNotificationList(org.eclipse.milo.opcua.stack.core.types.structured.EventNotificationList) List(java.util.List) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) EventFieldList(org.eclipse.milo.opcua.stack.core.types.structured.EventFieldList) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject) Map(java.util.Map) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Aggregations

UaMonitoredItem (org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem)13 Unsigned.uint (org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint)10 List (java.util.List)9 UaSubscription (org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription)9 OpcUaClient (org.eclipse.milo.opcua.sdk.client.OpcUaClient)8 CompletableFuture (java.util.concurrent.CompletableFuture)7 DataValue (org.eclipse.milo.opcua.stack.core.types.builtin.DataValue)7 UInteger (org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger)7 MonitoringMode (org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode)7 MonitoredItemCreateRequest (org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest)7 ReadValueId (org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId)7 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 ExecutionException (java.util.concurrent.ExecutionException)6 AttributeId (org.eclipse.milo.opcua.stack.core.AttributeId)6 UaException (org.eclipse.milo.opcua.stack.core.UaException)6 NodeId (org.eclipse.milo.opcua.stack.core.types.builtin.NodeId)6 QualifiedName (org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName)6 Variant (org.eclipse.milo.opcua.stack.core.types.builtin.Variant)6 TimestampsToReturn (org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn)6