Search in sources :

Example 1 with UaSubscription

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

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

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

the class SubscriptionWatchdogTimerTest method testSubscriptionWatchdogTimer.

@Disabled("run this test manually")
@Test
public void testSubscriptionWatchdogTimer() throws UaException, InterruptedException {
    ManagedDataItem dataItem = subscription.createDataItem(Identifiers.Server_ServerStatus_State);
    assertTrue(dataItem.getStatusCode().isGood());
    CountDownLatch latch = new CountDownLatch(2);
    subscription.addStatusListener(new ManagedSubscription.StatusListener() {

        @Override
        public void onSubscriptionWatchdogTimerElapsed(ManagedSubscription subscription) {
            System.out.println("onWatchdogTimerElapsed() id=" + subscription.getSubscription().getSubscriptionId());
            latch.countDown();
        }
    });
    client.getSubscriptionManager().addSubscriptionListener(new SubscriptionListener() {

        @Override
        public void onSubscriptionWatchdogTimerElapsed(UaSubscription subscription) {
            System.out.println("onWatchdogTimerElapsed() id=" + subscription.getSubscriptionId());
            latch.countDown();
        }
    });
    UInteger subscriptionId = subscription.getSubscription().getSubscriptionId();
    server.getSubscriptions().get(subscriptionId).deleteSubscription();
    System.out.printf("deleted subscription id=%s on server...%n", subscriptionId);
    System.out.println("waiting for watchdog timer to elapse...");
    assertTrue(latch.await(15, TimeUnit.SECONDS));
}
Also used : UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) SubscriptionListener(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscriptionManager.SubscriptionListener) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Example 4 with UaSubscription

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

use of org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription in project JBM by numen06.

the class OpcUaTemplate method createItemMonitored.

private List<UaMonitoredItem> createItemMonitored(OpcUaClientBean opcUaClientBean, OpcPoint opcPoint) throws ExecutionException, InterruptedException {
    int namespace = opcPoint.getNamespace();
    String tag = opcPoint.getTagName();
    NodeId nodeId = new NodeId(namespace, tag);
    // 创建发布间隔1000ms的订阅对象
    UaSubscription subscription = this.getSubscription(opcUaClientBean.getOpcUaClient());
    MonitoringParameters parameters = new MonitoringParameters(uint(subscription.getMonitoredItems().size() + 1), 1000.0, null, uint(10), true);
    List<MonitoredItemCreateRequest> requests = Lists.newArrayList();
    ReadValueId readValueId = new ReadValueId(nodeId, AttributeId.Value.uid(), null, null);
    // 创建监控item, 第一个为Reporting mode
    MonitoredItemCreateRequest request = new MonitoredItemCreateRequest(readValueId, MonitoringMode.Reporting, parameters);
    requests.add(request);
    List<UaMonitoredItem> items = subscription.createMonitoredItems(TimestampsToReturn.Both, requests, (item, id) -> item.setValueConsumer(new UaMonitoredItem.ValueConsumer() {

        @Override
        public void onValueArrived(UaMonitoredItem item, DataValue value) {
            try {
                log.debug("OPC数据变化回调:subscription value received: item={}, value={}", item.getReadValueId().getNodeId(), value.getValue());
                ValueChanageEvent valueChanageEvent = opcUaClientBean.getSubscriptionPoints().get(opcPoint.getAlias());
                valueChanageEvent.putData(item, value);
                applicationContext.publishEvent(valueChanageEvent);
            } catch (Exception e) {
            }
        }
    })).get();
    log.info("添加监听:[{}]到监听器[{}]监听数量:{}", nodeId, subscription.getSubscriptionId(), subscription.getMonitoredItems().size());
    return items;
}
Also used : UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) MonitoringMode(org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode) PointSubscribeEvent(com.jbm.framework.opcua.event.PointSubscribeEvent) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) Autowired(org.springframework.beans.factory.annotation.Autowired) ValueChanageEvent(com.jbm.framework.opcua.event.ValueChanageEvent) CompletableFuture(java.util.concurrent.CompletableFuture) Lists(com.google.common.collect.Lists) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) Service(org.springframework.stereotype.Service) AttributeId(org.eclipse.milo.opcua.stack.core.AttributeId) Map(java.util.Map) UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) org.eclipse.milo.opcua.stack.core.types.builtin(org.eclipse.milo.opcua.stack.core.types.builtin) AnonymousProvider(org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider) GuardSubscriptionListener(com.jbm.framework.opcua.listener.GuardSubscriptionListener) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) SessionActivityListener(org.eclipse.milo.opcua.sdk.client.SessionActivityListener) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Maps(com.google.common.collect.Maps) ApplicationContext(org.springframework.context.ApplicationContext) KeyLoader(com.jbm.framework.opcua.key.KeyLoader) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CollUtil(cn.hutool.core.collection.CollUtil) StrUtil(cn.hutool.core.util.StrUtil) Slf4j(lombok.extern.slf4j.Slf4j) org.eclipse.milo.opcua.stack.core.types.structured(org.eclipse.milo.opcua.stack.core.types.structured) List(java.util.List) JSON(com.alibaba.fastjson.JSON) OpcPointsRead(com.jbm.framework.opcua.attribute.OpcPointsRead) Paths(java.nio.file.Paths) ReflectUtil(cn.hutool.core.util.ReflectUtil) UaException(org.eclipse.milo.opcua.stack.core.UaException) DiscoveryClient(org.eclipse.milo.opcua.stack.client.DiscoveryClient) FileUtil(cn.hutool.core.io.FileUtil) ValueType(com.jbm.framework.opcua.attribute.ValueType) DriverUtils(com.jbm.framework.opcua.util.DriverUtils) OpcPoint(com.jbm.framework.opcua.attribute.OpcPoint) EndpointUtil(org.eclipse.milo.opcua.stack.core.util.EndpointUtil) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) OpcPoint(com.jbm.framework.opcua.attribute.OpcPoint) ExecutionException(java.util.concurrent.ExecutionException) UaException(org.eclipse.milo.opcua.stack.core.UaException) ValueChanageEvent(com.jbm.framework.opcua.event.ValueChanageEvent)

Aggregations

UaSubscription (org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription)7 UaMonitoredItem (org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem)5 UInteger (org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger)5 Unsigned.uint (org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint)5 ReadValueId (org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId)5 List (java.util.List)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 OpcUaClient (org.eclipse.milo.opcua.sdk.client.OpcUaClient)4 AttributeId (org.eclipse.milo.opcua.stack.core.AttributeId)4 DataValue (org.eclipse.milo.opcua.stack.core.types.builtin.DataValue)4 QualifiedName (org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName)4 TimestampsToReturn (org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn)4 Lists.newArrayList (com.google.common.collect.Lists.newArrayList)2 ExecutionException (java.util.concurrent.ExecutionException)2 TimeUnit (java.util.concurrent.TimeUnit)2 Identifiers (org.eclipse.milo.opcua.stack.core.Identifiers)2 MonitoringMode (org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode)2 MonitoredItemCreateRequest (org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest)2 MonitoringParameters (org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters)2 Logger (org.slf4j.Logger)2