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