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);
}
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);
}
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);
}
});
}
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);
});
}
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;
}
Aggregations