use of org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest 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.stack.core.types.structured.MonitoredItemCreateRequest 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.stack.core.types.structured.MonitoredItemCreateRequest in project milo by eclipse.
the class ManagedSubscription method createEventItemsAsync.
/**
* Create one or more {@link ManagedEventItem}s.
* <p>
* This operation will fail of the Node identified by {@code nodeId} is not an Object Node.
* <p>
* The operation result should be checked before this item is used further.
* See {@link ManagedEventItem#getStatusCode()}.
* <p>
* This operation completes asynchronously.
*
* @param nodeIds the {@link NodeId}s identifying Object Nodes.
* @param eventFilters the corresponding {@link EventFilter} to create each item with.
* @param consumer a {@link Consumer} that will receive each item as it is created.
* @return a {@link CompletableFuture} that completes successfully with the List of {@link ManagedEventItem}s or
* completes exceptionally if a service-level error occurs.
*/
public CompletableFuture<List<ManagedEventItem>> createEventItemsAsync(List<NodeId> nodeIds, List<EventFilter> eventFilters, Consumer<ManagedEventItem> consumer) {
final UInteger queueSize = getDefaultQueueSize();
final boolean discardOldest = getDefaultDiscardOldest();
List<MonitoredItemCreateRequest> createRequests = new ArrayList<>();
for (int i = 0; i < nodeIds.size(); i++) {
ReadValueId readValueId = new ReadValueId(nodeIds.get(i), AttributeId.EventNotifier.uid(), null, QualifiedName.NULL_VALUE);
MonitoringParameters parameters = new MonitoringParameters(subscription.nextClientHandle(), 0.0, ExtensionObject.encode(client.getStaticSerializationContext(), eventFilters.get(i)), queueSize, discardOldest);
createRequests.add(new MonitoredItemCreateRequest(readValueId, getDefaultMonitoringMode(), parameters));
}
CompletableFuture<List<UaMonitoredItem>> monitoredItems = subscription.createMonitoredItems(getDefaultTimestamps(), createRequests, (item, id) -> {
ManagedEventItem eventItem = createAndTrackEventItem(item);
consumer.accept(eventItem);
});
return monitoredItems.thenApply(items -> items.stream().map(item -> eventItems.get(item.getClientHandle())).filter(Objects::nonNull).collect(Collectors.toList()));
}
use of org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest in project milo by eclipse.
the class SubscriptionManager method createMonitoredItems.
public void createMonitoredItems(ServiceRequest service) throws UaException {
CreateMonitoredItemsRequest request = (CreateMonitoredItemsRequest) service.getRequest();
UInteger subscriptionId = request.getSubscriptionId();
Subscription subscription = subscriptions.get(subscriptionId);
TimestampsToReturn timestamps = request.getTimestampsToReturn();
List<MonitoredItemCreateRequest> itemsToCreate = l(request.getItemsToCreate());
if (subscription == null) {
throw new UaException(StatusCodes.Bad_SubscriptionIdInvalid);
}
if (timestamps == null) {
throw new UaException(StatusCodes.Bad_TimestampsToReturnInvalid);
}
if (itemsToCreate.isEmpty()) {
throw new UaException(StatusCodes.Bad_NothingToDo);
}
List<NodeId> distinctNodeIds = itemsToCreate.stream().map(item -> item.getItemToMonitor().getNodeId()).distinct().collect(toList());
CompletableFuture<Map<NodeId, AttributeGroup>> attributesFuture = readMonitoringAttributes(distinctNodeIds);
attributesFuture.thenAccept(attributeGroups -> {
MonitoredItemCreateResult[] createResults = new MonitoredItemCreateResult[itemsToCreate.size()];
List<BaseMonitoredItem<?>> monitoredItems = new ArrayList<>();
for (int i = 0; i < itemsToCreate.size(); i++) {
MonitoredItemCreateRequest createRequest = itemsToCreate.get(i);
try {
BaseMonitoredItem<?> monitoredItem = createMonitoredItem(createRequest, subscription, timestamps, attributeGroups);
monitoredItems.add(monitoredItem);
createResults[i] = new MonitoredItemCreateResult(StatusCode.GOOD, monitoredItem.getId(), monitoredItem.getSamplingInterval(), uint(monitoredItem.getQueueSize()), monitoredItem.getFilterResult());
} catch (UaException e) {
createResults[i] = new MonitoredItemCreateResult(e.getStatusCode(), UInteger.MIN, 0.0, UInteger.MIN, null);
}
}
subscription.addMonitoredItems(monitoredItems);
// Notify AddressSpaces of the items we just created.
byMonitoredItemType(monitoredItems, dataItems -> server.getAddressSpaceManager().onDataItemsCreated(dataItems), eventItems -> server.getAddressSpaceManager().onEventItemsCreated(eventItems));
ResponseHeader header = service.createResponseHeader();
CreateMonitoredItemsResponse response = new CreateMonitoredItemsResponse(header, createResults, new DiagnosticInfo[0]);
service.setResponse(response);
});
}
use of org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest in project milo by eclipse.
the class ManagedSubscription method createDataItemsAsync.
/**
* Create {@link ManagedDataItem}s monitoring the Nodes and Attributes identified by {@code readValueIds}.
* <p>
* {@code consumer} will receive each item as it is created to provide an opportunity to add a
* {@link DataValueListener} before the first value change has arrived.
* <p>
* The operation results should be checked before each item is used further.
* See {@link ManagedDataItem#getStatusCode()}.
* <p>
* This call completes asynchronously.
*
* @param samplingInterval the sampling interval to request.
* @param readValueIds the {@link ReadValueId}s identifying the Nodes and Attributes.
* @param consumer a {@link Consumer} that will receive each item as it is created.
* @return a {@link CompletableFuture} that completes successfully with a List of {@link ManagedDataItem} or
* completes exceptionally if a service-level error occurs.
*/
public CompletableFuture<List<ManagedDataItem>> createDataItemsAsync(double samplingInterval, List<ReadValueId> readValueIds, Consumer<ManagedDataItem> consumer) {
final ExtensionObject filter = getDefaultDataFilter();
final UInteger queueSize = getDefaultQueueSize();
final boolean discardOldest = getDefaultDiscardOldest();
List<MonitoredItemCreateRequest> createRequests = readValueIds.stream().map(readValueId -> {
MonitoringParameters parameters = new MonitoringParameters(subscription.nextClientHandle(), samplingInterval, filter, queueSize, discardOldest);
return new MonitoredItemCreateRequest(readValueId, getDefaultMonitoringMode(), parameters);
}).collect(Collectors.toList());
CompletableFuture<List<UaMonitoredItem>> monitoredItems = subscription.createMonitoredItems(getDefaultTimestamps(), createRequests, (item, id) -> {
ManagedDataItem dataItem = createAndTrackDataItem(item);
consumer.accept(dataItem);
});
return monitoredItems.thenApply(items -> items.stream().map(item -> dataItems.get(item.getClientHandle())).filter(Objects::nonNull).collect(Collectors.toList()));
}
Aggregations