You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@streampipes.apache.org by ri...@apache.org on 2026/05/05 21:43:13 UTC
(streampipes) branch 4433-support-opc-ua-events updated: feat(#4433): Add OPC-UA Events adapter
This is an automated email from the ASF dual-hosted git repository.
dominikriemer pushed a commit to branch 4433-support-opc-ua-events
in repository https://gitbox.apache.org/repos/asf/streampipes.git
The following commit(s) were added to refs/heads/4433-support-opc-ua-events by this push:
new 79e6a2b508 feat(#4433): Add OPC-UA Events adapter
79e6a2b508 is described below
commit 79e6a2b5083fea7440756d0d2f808ed7e8098e4f
Author: Dominik Riemer <do...@gmail.com>
AuthorDate: Tue May 5 23:42:45 2026 +0200
feat(#4433): Add OPC-UA Events adapter
---
.../opcua/OpcUaConnectorsModuleExport.java | 4 +-
.../connectors/opcua/adapter/OpcUaNodeBrowser.java | 6 +-
.../connectors/opcua/alarms/OpcUaAlarmAdapter.java | 135 ++++++++
.../opcua/alarms/OpcUaAlarmAdapterConfig.java | 72 ++++
.../opcua/alarms/OpcUaAlarmConfiguration.java | 95 ++++++
.../opcua/alarms/OpcUaAlarmEventFilter.java | 63 ++++
.../opcua/alarms/OpcUaAlarmEventMapper.java | 129 ++++++++
.../opcua/alarms/OpcUaAlarmEventSubscriber.java | 368 +++++++++++++++++++++
.../connectors/opcua/alarms/OpcUaAlarmField.java | 165 +++++++++
.../opcua/alarms/OpcUaAlarmSchemaProvider.java | 73 ++++
.../opcua/alarms/OpcUaAlarmValueNormalizer.java | 56 ++++
.../opcua/alarms/OpcUaEventFieldProvider.java | 143 ++++++++
.../opcua/alarms/OpcUaEventTypeBrowser.java | 91 +++++
.../opcua/alarms/OpcUaNotifierBrowser.java | 142 ++++++++
.../opcua/client/ConnectedOpcUaClient.java | 7 +-
.../opcua/client/OpcUaClientProvider.java | 29 +-
.../opcua/config/SharedUserConfiguration.java | 21 +-
.../opcua/config/SpOpcUaConfigExtractor.java | 62 +++-
.../connectors/opcua/model/OpcUaNodeFactory.java | 4 +-
.../opcua/model/node/OpcUaNumberNormalizer.java | 23 +-
.../opcua/model/node/StructuredOpcUaNode.java | 130 +-------
.../opcua/utils/ExceptionMessageExtractor.java | 36 ++
.../connectors/opcua/utils/OpcUaUtils.java | 212 +++++++++++-
.../opcua/utils/OpcUaValueNormalizationUtils.java | 172 ++++++++++
.../documentation.md | 15 +
.../icon.png | Bin 0 -> 5087 bytes
.../strings.en | 100 ++++++
.../opcua/alarms/OpcUaAlarmEventFilterTest.java | 61 ++++
.../opcua/alarms/OpcUaAlarmEventMapperTest.java | 197 +++++++++++
.../alarms/OpcUaAlarmValueNormalizerTest.java | 56 ++++
.../connectors/opcua/utils/OpcUaUtilTest.java | 43 +++
...tic-runtime-resolvable-any-input.component.html | 6 +-
.../static-tree-input-browse-nodes.component.html | 29 +-
.../static-tree-input-browse-nodes.component.ts | 39 ++-
34 files changed, 2604 insertions(+), 180 deletions(-)
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/OpcUaConnectorsModuleExport.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/OpcUaConnectorsModuleExport.java
index 4eb8168567..0c7bf2088f 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/OpcUaConnectorsModuleExport.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/OpcUaConnectorsModuleExport.java
@@ -23,6 +23,7 @@ import org.apache.streampipes.extensions.api.declarer.IExtensionModuleExport;
import org.apache.streampipes.extensions.api.migration.IModelMigrator;
import org.apache.streampipes.extensions.api.pe.IStreamPipesPipelineElement;
import org.apache.streampipes.extensions.connectors.opcua.adapter.OpcUaAdapter;
+import org.apache.streampipes.extensions.connectors.opcua.alarms.OpcUaAlarmAdapter;
import org.apache.streampipes.extensions.connectors.opcua.client.OpcUaClientProvider;
import org.apache.streampipes.extensions.connectors.opcua.migration.OpcUaAdapterMigrationV1;
import org.apache.streampipes.extensions.connectors.opcua.migration.OpcUaAdapterMigrationV2;
@@ -47,7 +48,8 @@ public class OpcUaConnectorsModuleExport implements IExtensionModuleExport {
@Override
public List<StreamPipesAdapter> adapters() {
return List.of(
- new OpcUaAdapter(clientProvider)
+ new OpcUaAdapter(clientProvider),
+ new OpcUaAlarmAdapter(clientProvider)
);
}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/adapter/OpcUaNodeBrowser.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/adapter/OpcUaNodeBrowser.java
index 9dfff5a345..5e366af76e 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/adapter/OpcUaNodeBrowser.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/adapter/OpcUaNodeBrowser.java
@@ -29,7 +29,7 @@ import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.nodes.UaNode;
import org.eclipse.milo.opcua.sdk.client.nodes.UaVariableNode;
import org.eclipse.milo.opcua.sdk.core.nodes.VariableNode;
-import org.eclipse.milo.opcua.stack.core.Identifiers;
+import org.eclipse.milo.opcua.stack.core.NodeIds;
import org.eclipse.milo.opcua.stack.core.UaException;
import org.eclipse.milo.opcua.stack.core.UaRuntimeException;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
@@ -77,7 +77,7 @@ public class OpcUaNodeBrowser {
var requestsRootNode = Objects.isNull(nextBaseNodeToResolve);
var currentNodeId = requestsRootNode
- ? Identifiers.RootFolder : NodeId.parse(nextBaseNodeToResolve);
+ ? NodeIds.RootFolder : NodeId.parse(nextBaseNodeToResolve);
return findChildren(client, currentNodeId);
}
@@ -131,7 +131,7 @@ public class OpcUaNodeBrowser {
var options = AddressSpace.BrowseOptions.builder()
.setBrowseDirection(BrowseDirection.Forward)
- .setReferenceType(Identifiers.HierarchicalReferences)
+ .setReferenceType(NodeIds.HierarchicalReferences)
.setIncludeSubtypes(true)
.setNodeClassMask(Set.of(NodeClass.Object, NodeClass.Variable))
.build();
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmAdapter.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmAdapter.java
new file mode 100644
index 0000000000..56928d6bd6
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmAdapter.java
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.apache.streampipes.commons.exceptions.SpConfigurationException;
+import org.apache.streampipes.commons.exceptions.connect.AdapterException;
+import org.apache.streampipes.extensions.api.connect.IAdapterConfiguration;
+import org.apache.streampipes.extensions.api.connect.IEventCollector;
+import org.apache.streampipes.extensions.api.connect.StreamPipesAdapter;
+import org.apache.streampipes.extensions.api.connect.context.IAdapterGuessSchemaContext;
+import org.apache.streampipes.extensions.api.connect.context.IAdapterRuntimeContext;
+import org.apache.streampipes.extensions.api.extractor.IAdapterParameterExtractor;
+import org.apache.streampipes.extensions.api.extractor.IStaticPropertyExtractor;
+import org.apache.streampipes.extensions.api.runtime.SupportsRuntimeConfig;
+import org.apache.streampipes.extensions.connectors.opcua.client.ConnectedOpcUaClient;
+import org.apache.streampipes.extensions.connectors.opcua.client.OpcUaClientProvider;
+import org.apache.streampipes.extensions.connectors.opcua.config.SharedUserConfiguration;
+import org.apache.streampipes.extensions.connectors.opcua.config.SpOpcUaConfigExtractor;
+import org.apache.streampipes.extensions.connectors.opcua.utils.OpcUaUtils;
+import org.apache.streampipes.model.connect.guess.SampleData;
+import org.apache.streampipes.model.extensions.ExtensionAssetType;
+import org.apache.streampipes.model.staticproperty.StaticProperty;
+import org.apache.streampipes.sdk.builder.adapter.AdapterConfigurationBuilder;
+import org.apache.streampipes.sdk.helpers.Locales;
+
+public class OpcUaAlarmAdapter implements StreamPipesAdapter, SupportsRuntimeConfig {
+
+ public static final String ID = "org.apache.streampipes.connect.iiot.adapters.opcua-alarms";
+
+ private final OpcUaClientProvider clientProvider;
+
+ private OpcUaAlarmAdapterConfig opcUaConfig;
+ private ConnectedOpcUaClient connectedClient;
+ private OpcUaAlarmEventSubscriber subscriber;
+
+ public OpcUaAlarmAdapter(OpcUaClientProvider clientProvider) {
+ this.clientProvider = clientProvider;
+ }
+
+ @Override
+ public IAdapterConfiguration declareConfig() {
+ var builder = AdapterConfigurationBuilder.create(ID, 1, () -> new OpcUaAlarmAdapter(clientProvider))
+ .withLocales(Locales.EN)
+ .withAssets(ExtensionAssetType.DOCUMENTATION, ExtensionAssetType.ICON);
+
+ SharedUserConfiguration.appendSharedOpcUaConnectionConfig(builder);
+ OpcUaAlarmConfiguration.appendFilterConfiguration(builder);
+
+ return builder.buildConfiguration();
+ }
+
+ @Override
+ public void onAdapterStarted(IAdapterParameterExtractor extractor,
+ IEventCollector collector,
+ IAdapterRuntimeContext adapterRuntimeContext) throws AdapterException {
+ this.opcUaConfig = SpOpcUaConfigExtractor.extractAlarmAdapterConfig(
+ extractor.getStaticPropertyExtractor(),
+ adapterRuntimeContext.getStreamPipesClient(),
+ extractor.getAdapterDescription().getElementId()
+ );
+
+ try {
+ this.connectedClient = clientProvider.getClient(opcUaConfig);
+ this.subscriber = new OpcUaAlarmEventSubscriber(connectedClient, opcUaConfig, collector::collect);
+ this.subscriber.start();
+ } catch (Exception e) {
+ cleanup();
+ throw new AdapterException("The connection to the OPC UA server could not be established.", e);
+ }
+ }
+
+ @Override
+ public void onAdapterStopped(IAdapterParameterExtractor extractor,
+ IAdapterRuntimeContext adapterRuntimeContext) {
+ cleanup();
+ }
+
+ @Override
+ public SampleData onSampleDataRequested(IAdapterParameterExtractor extractor,
+ IAdapterGuessSchemaContext adapterGuessSchemaContext) throws AdapterException {
+ return new OpcUaAlarmSchemaProvider().getSampleData(
+ clientProvider,
+ extractor,
+ adapterGuessSchemaContext.getStreamPipesClient()
+ );
+ }
+
+ @Override
+ public StaticProperty resolveConfiguration(String staticPropertyInternalName,
+ IStaticPropertyExtractor parameterExtractor) throws SpConfigurationException {
+ if (OpcUaAlarmConfiguration.NOTIFIER_NODE.equals(staticPropertyInternalName)) {
+ return OpcUaUtils.resolveNotifierTreeConfig(clientProvider, staticPropertyInternalName, parameterExtractor);
+ }
+
+ if (OpcUaAlarmConfiguration.EVENT_TYPE.equals(staticPropertyInternalName)) {
+ return OpcUaUtils.resolveEventTypeTreeConfig(clientProvider, staticPropertyInternalName, parameterExtractor);
+ }
+
+ if (OpcUaAlarmConfiguration.ADDITIONAL_FIELDS.equals(staticPropertyInternalName)) {
+ return OpcUaUtils.resolveEventFieldConfig(clientProvider, staticPropertyInternalName, parameterExtractor);
+ }
+
+ throw new SpConfigurationException("Unsupported runtime-resolvable property: " + staticPropertyInternalName);
+ }
+
+ private void cleanup() {
+ if (subscriber != null) {
+ subscriber.close();
+ subscriber = null;
+ }
+
+ if (opcUaConfig != null) {
+ clientProvider.releaseClient(opcUaConfig);
+ opcUaConfig = null;
+ }
+
+ connectedClient = null;
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmAdapterConfig.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmAdapterConfig.java
new file mode 100644
index 0000000000..6fdfbe04ba
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmAdapterConfig.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.apache.streampipes.extensions.connectors.opcua.config.OpcUaConfig;
+
+import java.util.List;
+
+public class OpcUaAlarmAdapterConfig extends OpcUaConfig {
+
+ private String notifierNodeId;
+ private String eventTypeNodeId;
+ private List<String> selectedAdditionalFieldNames;
+ private String sourceNameFilter;
+ private Integer minimumSeverity;
+
+ public String getNotifierNodeId() {
+ return notifierNodeId;
+ }
+
+ public void setNotifierNodeId(String notifierNodeId) {
+ this.notifierNodeId = notifierNodeId;
+ }
+
+ public String getEventTypeNodeId() {
+ return eventTypeNodeId;
+ }
+
+ public void setEventTypeNodeId(String eventTypeNodeId) {
+ this.eventTypeNodeId = eventTypeNodeId;
+ }
+
+ public List<String> getSelectedAdditionalFieldNames() {
+ return selectedAdditionalFieldNames;
+ }
+
+ public void setSelectedAdditionalFieldNames(List<String> selectedAdditionalFieldNames) {
+ this.selectedAdditionalFieldNames = selectedAdditionalFieldNames;
+ }
+
+ public String getSourceNameFilter() {
+ return sourceNameFilter;
+ }
+
+ public void setSourceNameFilter(String sourceNameFilter) {
+ this.sourceNameFilter = sourceNameFilter;
+ }
+
+ public Integer getMinimumSeverity() {
+ return minimumSeverity;
+ }
+
+ public void setMinimumSeverity(Integer minimumSeverity) {
+ this.minimumSeverity = minimumSeverity;
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmConfiguration.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmConfiguration.java
new file mode 100644
index 0000000000..2bd4bdb495
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmConfiguration.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.apache.streampipes.model.staticproperty.Option;
+import org.apache.streampipes.sdk.StaticProperties;
+import org.apache.streampipes.sdk.builder.AbstractConfigurablePipelineElementBuilder;
+import org.apache.streampipes.sdk.helpers.Alternatives;
+import org.apache.streampipes.sdk.helpers.Labels;
+
+import java.util.List;
+
+public class OpcUaAlarmConfiguration {
+
+ public static final String ALARM_SOURCE_SCOPE = "alarm-source-scope";
+ public static final String WHOLE_SERVER = "whole-server";
+ public static final String SPECIFIC_AREA_OR_MACHINE = "specific-area-or-machine";
+ public static final String NOTIFIER_NODE = "notifier-node";
+ public static final String EVENT_TYPE = "event-type";
+ public static final String ADDITIONAL_FIELDS = "additional-fields";
+
+ public static final String ALARM_FILTER_MODE = "alarm-filter-mode";
+ public static final String ALL_ALARMS = "all-alarms";
+ public static final String SOURCE_NAME_CONTAINS = "source-name-contains";
+ public static final String SOURCE_NAME_FILTER = "source-name-filter";
+
+ public static final String MINIMUM_SEVERITY = "minimum-severity";
+ public static final String MINIMUM_SEVERITY_ANY = "any";
+
+ private OpcUaAlarmConfiguration() {
+ }
+
+ public static void appendFilterConfiguration(AbstractConfigurablePipelineElementBuilder<?, ?> builder) {
+ builder.requiredAlternatives(
+ Labels.withId(ALARM_SOURCE_SCOPE),
+ Alternatives.from(Labels.withId(WHOLE_SERVER)),
+ Alternatives.from(
+ Labels.withId(SPECIFIC_AREA_OR_MACHINE),
+ StaticProperties.runtimeResolvableTreeInput(
+ Labels.withId(NOTIFIER_NODE),
+ List.of(),
+ false,
+ false
+ )
+ )
+ );
+
+ builder.requiredRuntimeResolvableTreeInput(
+ Labels.withId(EVENT_TYPE),
+ List.of(),
+ false,
+ false
+ );
+
+ builder.requiredMultiValueSelectionFromContainer(
+ Labels.withId(ADDITIONAL_FIELDS)
+ );
+
+ builder.requiredAlternatives(
+ Labels.withId(ALARM_FILTER_MODE),
+ Alternatives.from(Labels.withId(ALL_ALARMS)),
+ Alternatives.from(
+ Labels.withId(SOURCE_NAME_CONTAINS),
+ StaticProperties.stringFreeTextProperty(Labels.withId(SOURCE_NAME_FILTER))
+ )
+ );
+
+ builder.requiredSingleValueSelection(
+ Labels.withId(MINIMUM_SEVERITY),
+ List.of(
+ new Option("Any", MINIMUM_SEVERITY_ANY),
+ new Option("100+", "100"),
+ new Option("300+", "300"),
+ new Option("500+", "500"),
+ new Option("700+", "700")
+ )
+ );
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventFilter.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventFilter.java
new file mode 100644
index 0000000000..8db8d520ef
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventFilter.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import java.util.Locale;
+import java.util.Map;
+
+public class OpcUaAlarmEventFilter {
+
+ private final OpcUaAlarmAdapterConfig config;
+
+ OpcUaAlarmEventFilter(OpcUaAlarmAdapterConfig config) {
+ this.config = config;
+ }
+
+ boolean matches(Map<String, Object> event) {
+ return matchesSourceName(event)
+ && matchesMinimumSeverity(event);
+ }
+
+ private boolean matchesSourceName(Map<String, Object> event) {
+ if (config.getSourceNameFilter() == null || config.getSourceNameFilter().isBlank()) {
+ return true;
+ }
+
+ var sourceName = event.get("sourceName");
+ if (!(sourceName instanceof String sourceNameValue)) {
+ return false;
+ }
+
+ return sourceNameValue.toLowerCase(Locale.ENGLISH)
+ .contains(config.getSourceNameFilter().toLowerCase(Locale.ENGLISH));
+ }
+
+ private boolean matchesMinimumSeverity(Map<String, Object> event) {
+ if (config.getMinimumSeverity() == null) {
+ return true;
+ }
+
+ var severity = event.get("severity");
+ if (!(severity instanceof Number severityValue)) {
+ return false;
+ }
+
+ return severityValue.intValue() >= config.getMinimumSeverity();
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventMapper.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventMapper.java
new file mode 100644
index 0000000000..9e65f66eb3
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventMapper.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
+import org.eclipse.milo.opcua.sdk.client.subscriptions.EventFilterBuilder;
+import org.eclipse.milo.opcua.stack.core.AttributeId;
+import org.eclipse.milo.opcua.stack.core.NodeIds;
+import org.eclipse.milo.opcua.stack.core.UaException;
+import org.eclipse.milo.opcua.stack.core.encoding.EncodingContext;
+import org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
+import org.eclipse.milo.opcua.stack.core.types.enumerated.FilterOperator;
+import org.eclipse.milo.opcua.stack.core.types.structured.ContentFilter;
+import org.eclipse.milo.opcua.stack.core.types.structured.ContentFilterElement;
+import org.eclipse.milo.opcua.stack.core.types.structured.EventFilter;
+import org.eclipse.milo.opcua.stack.core.types.structured.LiteralOperand;
+import org.eclipse.milo.opcua.stack.core.types.structured.SimpleAttributeOperand;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+public class OpcUaAlarmEventMapper {
+
+ private static final Logger LOG = LoggerFactory.getLogger(OpcUaAlarmEventMapper.class);
+
+ private final NodeId selectedEventTypeId;
+ private final List<OpcUaAlarmField> selectedFields;
+ private final OpcUaAlarmValueNormalizer valueNormalizer;
+
+ static OpcUaAlarmEventMapper create(OpcUaClient client, OpcUaAlarmAdapterConfig config) {
+ var selectedEventTypeId = determineSelectedEventTypeId(config);
+
+ try {
+ var fieldProvider = new OpcUaEventFieldProvider(client);
+ return new OpcUaAlarmEventMapper(
+ selectedEventTypeId,
+ fieldProvider.buildSelectedFields(
+ selectedEventTypeId.toParseableString(),
+ config.getSelectedAdditionalFieldNames())
+ );
+ } catch (UaException e) {
+ LOG.warn(
+ "Falling back to BaseEventType fields because reading OPC UA event field declarations failed for selectedEventTypeId={}",
+ selectedEventTypeId,
+ e
+ );
+ return new OpcUaAlarmEventMapper(selectedEventTypeId, OpcUaAlarmField.baseEventFieldsOnly());
+ }
+ }
+
+ OpcUaAlarmEventMapper(NodeId selectedEventTypeId, List<OpcUaAlarmField> selectedFields) {
+ this.selectedEventTypeId = selectedEventTypeId;
+ this.selectedFields = selectedFields;
+ this.valueNormalizer = new OpcUaAlarmValueNormalizer();
+ }
+
+ EventFilter makeEventFilter(EncodingContext encodingContext) {
+ var filterBuilder = new EventFilterBuilder();
+ selectedFields.forEach(field -> filterBuilder.select(toOperand(field)));
+ filterBuilder.where(makeOfTypeWhereClause(encodingContext));
+ return filterBuilder.build();
+ }
+
+ Map<String, Object> toEvent(Variant[] eventValues) {
+ var event = new LinkedHashMap<String, Object>();
+
+ for (int i = 0; i < selectedFields.size(); i++) {
+ var field = selectedFields.get(i);
+ var variantValue = i < eventValues.length ? eventValues[i].getValue() : null;
+ event.put(field.outputField(), valueNormalizer.normalize(variantValue));
+ }
+
+ return event;
+ }
+
+ private SimpleAttributeOperand toOperand(OpcUaAlarmField field) {
+ return new SimpleAttributeOperand(
+ field.typeDefinitionId(),
+ field.browsePath(),
+ AttributeId.Value.uid(),
+ null
+ );
+ }
+
+ private ContentFilter makeOfTypeWhereClause(EncodingContext encodingContext) {
+ var ofTypeOperand = ExtensionObject.encode(
+ encodingContext,
+ new LiteralOperand(new Variant(selectedEventTypeId))
+ );
+
+ return new ContentFilter(
+ new ContentFilterElement[] {
+ new ContentFilterElement(
+ FilterOperator.OfType,
+ new ExtensionObject[] {ofTypeOperand}
+ )
+ }
+ );
+ }
+
+ private static NodeId determineSelectedEventTypeId(OpcUaAlarmAdapterConfig config) {
+ if (config.getEventTypeNodeId() == null || config.getEventTypeNodeId().isBlank()) {
+ return NodeIds.BaseEventType;
+ }
+
+ return NodeId.parse(config.getEventTypeNodeId());
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventSubscriber.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventSubscriber.java
new file mode 100644
index 0000000000..866bae83a1
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventSubscriber.java
@@ -0,0 +1,368 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.apache.streampipes.extensions.connectors.opcua.client.ConnectedOpcUaClient;
+
+import org.eclipse.milo.opcua.sdk.client.ServiceFaultListener;
+import org.eclipse.milo.opcua.sdk.client.SessionActivityListener;
+import org.eclipse.milo.opcua.sdk.client.subscriptions.MonitoredItemServiceOperationResult;
+import org.eclipse.milo.opcua.sdk.client.subscriptions.OpcUaMonitoredItem;
+import org.eclipse.milo.opcua.sdk.client.subscriptions.OpcUaSubscription;
+import org.eclipse.milo.opcua.stack.core.NodeIds;
+import org.eclipse.milo.opcua.stack.core.UaException;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;
+import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
+import org.eclipse.milo.opcua.stack.core.types.enumerated.BrowseDirection;
+import org.eclipse.milo.opcua.stack.core.types.enumerated.BrowseResultMask;
+import org.eclipse.milo.opcua.stack.core.types.enumerated.NodeClass;
+import org.eclipse.milo.opcua.stack.core.types.structured.BrowseDescription;
+import org.eclipse.milo.opcua.stack.core.types.structured.CallMethodRequest;
+import org.eclipse.milo.opcua.stack.core.types.structured.CallMethodResult;
+import org.eclipse.milo.opcua.stack.core.types.structured.ReferenceDescription;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import static org.eclipse.milo.opcua.stack.core.StatusCodes.Bad_UnexpectedError;
+import static org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint;
+
+public class OpcUaAlarmEventSubscriber implements AutoCloseable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(OpcUaAlarmEventSubscriber.class);
+ private static final double PUBLISHING_INTERVAL_MS = 1000.0;
+
+ private final ConnectedOpcUaClient connectedClient;
+ private final OpcUaAlarmAdapterConfig config;
+ private final OpcUaAlarmEventMapper eventMapper;
+ private final OpcUaAlarmEventFilter eventFilter;
+ private final Consumer<Map<String, Object>> eventConsumer;
+ private final SessionActivityListener sessionActivityListener;
+ private final ServiceFaultListener serviceFaultListener;
+
+ private volatile boolean closed;
+ private volatile String lastSubscriptionOperation = "idle";
+ private OpcUaSubscription subscription;
+
+ OpcUaAlarmEventSubscriber(ConnectedOpcUaClient connectedClient,
+ OpcUaAlarmAdapterConfig config,
+ Consumer<Map<String, Object>> eventConsumer) {
+ this.connectedClient = connectedClient;
+ this.config = config;
+ this.eventConsumer = eventConsumer;
+ this.eventMapper = OpcUaAlarmEventMapper.create(connectedClient.getClient(), config);
+ this.eventFilter = new OpcUaAlarmEventFilter(config);
+ this.sessionActivityListener = new SessionActivityListener() {
+ @Override
+ public void onSessionActive(org.eclipse.milo.opcua.sdk.client.UaSession session) {
+ LOG.debug(
+ "OPC UA alarm subscriber client identity={} session became active: {}",
+ System.identityHashCode(OpcUaAlarmEventSubscriber.this.connectedClient.getClient()),
+ session.getSessionId()
+ );
+ }
+
+ @Override
+ public void onSessionInactive(org.eclipse.milo.opcua.sdk.client.UaSession session) {
+ LOG.debug(
+ "OPC UA alarm subscriber client identity={} session became inactive: {}",
+ System.identityHashCode(OpcUaAlarmEventSubscriber.this.connectedClient.getClient()),
+ session.getSessionId()
+ );
+ }
+ };
+ this.serviceFaultListener = serviceFault -> LOG.warn(
+ "OPC UA alarm subscriber client identity={} received service fault: {} lastOperation={} localSubscriptionId={} managedSubscriptionCount={}",
+ System.identityHashCode(OpcUaAlarmEventSubscriber.this.connectedClient.getClient()),
+ serviceFault.getResponseHeader().getServiceResult(),
+ lastSubscriptionOperation,
+ subscription != null ? subscription.getSubscriptionId().orElse(null) : null,
+ OpcUaAlarmEventSubscriber.this.connectedClient.getClient().getSubscriptions().size()
+ );
+ }
+
+ synchronized void start() throws UaException {
+ if (closed) {
+ throw new IllegalStateException("Subscriber is already closed");
+ }
+
+ if (subscription == null) {
+ connectedClient.getClient().addSessionActivityListener(sessionActivityListener);
+ connectedClient.getClient().addFaultListener(serviceFaultListener);
+ createSubscription();
+ }
+ }
+
+ private void createSubscription() throws UaException {
+ setLastSubscriptionOperation("create-subscription");
+ OpcUaSubscription newSubscription = createManagedSubscription();
+ newSubscription.setSubscriptionListener(new OpcUaSubscription.SubscriptionListener() {
+ @Override
+ public void onKeepAliveReceived(OpcUaSubscription subscription) {
+ LOG.debug(
+ "Received OPC UA alarm keepalive for subscriptionId={}",
+ subscription.getSubscriptionId().orElse(null)
+ );
+ }
+
+ @Override
+ public void onEventReceived(
+ OpcUaSubscription subscription,
+ List<OpcUaMonitoredItem> items,
+ List<Variant[]> eventFields) {
+ LOG.debug(
+ "Subscription listener received {} OPC UA alarm event notification(s) for subscriptionId={}",
+ eventFields.size(),
+ subscription.getSubscriptionId().orElse(null)
+ );
+ }
+
+ @Override
+ public void onTransferFailed(OpcUaSubscription subscription, StatusCode statusCode) {
+ if (closed) {
+ return;
+ }
+
+ setLastSubscriptionOperation(
+ "transfer-failed(subscriptionId=%s,status=%s)".formatted(
+ subscription.getSubscriptionId().orElse(null),
+ statusCode
+ )
+ );
+ LOG.warn("Transfer for alarm subscriptionId={} failed: {}", subscription.getSubscriptionId(), statusCode);
+ synchronized (OpcUaAlarmEventSubscriber.this) {
+ deleteSubscriptionQuietly();
+ try {
+ createSubscription();
+ } catch (UaException e) {
+ LOG.error("Re-creating OPC UA alarm subscription failed", e);
+ }
+ }
+ }
+ });
+
+ LOG.debug(
+ "Created OPC UA alarm subscription with subscriptionId={} on client identity={} managerSubscriptionCount={}",
+ newSubscription.getSubscriptionId().orElse(null),
+ System.identityHashCode(connectedClient.getClient()),
+ connectedClient.getClient().getSubscriptions().size()
+ );
+
+ var monitoredItem = OpcUaMonitoredItem.newEventItem(
+ getSubscriptionTargetNodeId(),
+ eventMapper.makeEventFilter(connectedClient.getClient().getStaticEncodingContext())
+ );
+ monitoredItem.setQueueSize(uint(100));
+ monitoredItem.setDiscardOldest(true);
+ monitoredItem.setEventValueListener(this::onEventReceived);
+
+ newSubscription.addMonitoredItem(monitoredItem);
+ setLastSubscriptionOperation(
+ "create-monitored-items(subscriptionId=%s,targetNodeId=%s)".formatted(
+ newSubscription.getSubscriptionId().orElse(null),
+ getSubscriptionTargetNodeId()
+ )
+ );
+ var results = newSubscription.createMonitoredItems();
+ assertSingleGoodResult(results);
+ LOG.debug(
+ "Created OPC UA alarm monitored item on subscriptionId={} client identity={} resultCount={} status={}",
+ newSubscription.getSubscriptionId().orElse(null),
+ System.identityHashCode(connectedClient.getClient()),
+ results.size(),
+ results.get(0).operationResult().orElse(results.get(0).serviceResult())
+ );
+
+ this.subscription = newSubscription;
+ requestConditionRefresh(newSubscription);
+ setLastSubscriptionOperation(
+ "subscription-ready(subscriptionId=%s)".formatted(newSubscription.getSubscriptionId().orElse(null))
+ );
+ }
+
+ private OpcUaSubscription createManagedSubscription() throws UaException {
+ var subscription = new OpcUaSubscription(connectedClient.getClient(), PUBLISHING_INTERVAL_MS);
+ subscription.create();
+ return subscription;
+ }
+
+ private void assertSingleGoodResult(List<MonitoredItemServiceOperationResult> results) throws UaException {
+ if (results.isEmpty()) {
+ throw new UaException(Bad_UnexpectedError, "No monitored item result returned for OPC UA alarm subscription");
+ }
+
+ var result = results.get(0);
+ if (!result.isGood()) {
+ throw new UaException(
+ result.operationResult().orElse(result.serviceResult()),
+ "Failed to create OPC UA alarm monitored item"
+ );
+ }
+ }
+
+ private void requestConditionRefresh(OpcUaSubscription subscription) {
+ var subscriptionId = subscription.getSubscriptionId();
+ if (subscriptionId.isEmpty()) {
+ LOG.warn("Skipping ConditionRefresh because the OPC UA subscription has no subscriptionId yet");
+ return;
+ }
+
+ try {
+ setLastSubscriptionOperation(
+ "condition-refresh(subscriptionId=%s)".formatted(subscriptionId.get())
+ );
+ Optional<NodeId> conditionRefreshMethodId = findConditionRefreshMethodId();
+
+ if (conditionRefreshMethodId.isEmpty()) {
+ LOG.debug("Skipping ConditionRefresh because the server does not expose a ConditionRefresh method on the Server object");
+ return;
+ }
+
+ var request = new CallMethodRequest(
+ NodeIds.Server,
+ conditionRefreshMethodId.get(),
+ new Variant[] {new Variant(subscriptionId.get())}
+ );
+
+ var response = connectedClient.getClient().call(List.of(request));
+ CallMethodResult result = response.getResults() != null && response.getResults().length > 0
+ ? response.getResults()[0]
+ : null;
+
+ if (result == null) {
+ LOG.warn("ConditionRefresh returned no result for subscriptionId={}", subscriptionId.get());
+ return;
+ }
+
+ if (result.getStatusCode().isGood()) {
+ LOG.debug("ConditionRefresh succeeded for subscriptionId={}", subscriptionId.get());
+ } else {
+ LOG.warn("ConditionRefresh failed for subscriptionId={} with status={}", subscriptionId.get(), result.getStatusCode());
+ }
+ } catch (UaException e) {
+ LOG.warn("ConditionRefresh invocation failed for subscriptionId={}", subscriptionId.get(), e);
+ }
+ }
+
+ private Optional<NodeId> findConditionRefreshMethodId() {
+ try {
+ var browseResult = connectedClient.getClient().browse(new BrowseDescription(
+ NodeIds.Server,
+ BrowseDirection.Forward,
+ NodeIds.References,
+ true,
+ uint(NodeClass.Method.getValue()),
+ uint(BrowseResultMask.All.getValue())
+ ));
+
+ Optional<NodeId> methodId = Arrays.stream(browseResult.getReferences())
+ .filter(reference -> "ConditionRefresh".equals(reference.getBrowseName().getName()))
+ .findFirst()
+ .flatMap(this::toNodeId);
+
+ if (methodId.isEmpty() && LOG.isDebugEnabled()) {
+ String availableMethods = Arrays.stream(browseResult.getReferences())
+ .map(reference -> reference.getBrowseName().getName())
+ .collect(Collectors.joining(", "));
+
+ LOG.debug("Server methods available for ConditionRefresh discovery: {}", availableMethods);
+ }
+
+ return methodId;
+ } catch (UaException e) {
+ LOG.debug("Browsing Server methods for ConditionRefresh failed", e);
+ return Optional.empty();
+ }
+ }
+
+ private Optional<NodeId> toNodeId(ReferenceDescription reference) {
+ return reference.getNodeId().toNodeId(connectedClient.getClient().getNamespaceTable());
+ }
+
+ private void onEventReceived(OpcUaMonitoredItem item, Variant[] eventValues) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Received OPC UA event from nodeId={} values={}",
+ item.getReadValueId().getNodeId(),
+ Arrays.toString(eventValues));
+ }
+
+ var event = eventMapper.toEvent(eventValues);
+ if (event.isEmpty()) {
+ LOG.debug("Dropped OPC UA event after mapping because it was not recognized as an alarm/condition");
+ return;
+ }
+
+ if (!eventFilter.matches(event)) {
+ LOG.debug("Dropped OPC UA alarm event after applying configured filters: {}", event);
+ return;
+ }
+
+ LOG.debug("Mapped OPC UA alarm event: {}", event);
+
+ try {
+ eventConsumer.accept(event);
+ } catch (Exception e) {
+ LOG.error("Processing OPC UA alarm event failed", e);
+ }
+ }
+
+ private NodeId getSubscriptionTargetNodeId() {
+ if (config.getNotifierNodeId() == null || config.getNotifierNodeId().isBlank()) {
+ return NodeIds.Server;
+ }
+
+ return NodeId.parse(config.getNotifierNodeId());
+ }
+
+ @Override
+ public synchronized void close() {
+ closed = true;
+ deleteSubscriptionQuietly();
+ connectedClient.getClient().removeSessionActivityListener(sessionActivityListener);
+ connectedClient.getClient().removeFaultListener(serviceFaultListener);
+ }
+
+ private void deleteSubscriptionQuietly() {
+ if (subscription == null) {
+ return;
+ }
+
+ try {
+ setLastSubscriptionOperation(
+ "delete-subscription(subscriptionId=%s)".formatted(subscription.getSubscriptionId().orElse(null))
+ );
+ subscription.delete();
+ } catch (UaException e) {
+ LOG.warn("Deleting OPC UA alarm subscription failed", e);
+ } finally {
+ subscription = null;
+ }
+ }
+
+ private void setLastSubscriptionOperation(String lastSubscriptionOperation) {
+ this.lastSubscriptionOperation = lastSubscriptionOperation;
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmField.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmField.java
new file mode 100644
index 0000000000..ceede175b2
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmField.java
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.eclipse.milo.opcua.sdk.core.typetree.ObjectTypeTree;
+import org.eclipse.milo.opcua.stack.core.NodeIds;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
+
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public record OpcUaAlarmField(String outputField,
+ NodeId typeDefinitionId,
+ QualifiedName[] browsePath) {
+
+ static OpcUaAlarmField fromBrowsePath(NodeId typeDefinitionId, List<QualifiedName> browsePath) {
+ return new OpcUaAlarmField(toOutputFieldName(browsePath), typeDefinitionId, browsePath.toArray(QualifiedName[]::new));
+ }
+
+ static List<OpcUaAlarmField> fieldsForType(NodeId selectedEventTypeId, ObjectTypeTree objectTypeTree) {
+ Map<String, OpcUaAlarmField> fields = new LinkedHashMap<>();
+
+ baseEventFields().forEach(field -> fields.put(field.outputField(), field));
+
+ if (isTypeOrSubtypeOf(selectedEventTypeId, NodeIds.ConditionType, objectTypeTree)) {
+ conditionFields().forEach(field -> fields.put(field.outputField(), field));
+ }
+
+ if (isTypeOrSubtypeOf(selectedEventTypeId, NodeIds.AcknowledgeableConditionType, objectTypeTree)) {
+ acknowledgeableConditionFields().forEach(field -> fields.put(field.outputField(), field));
+ }
+
+ if (isTypeOrSubtypeOf(selectedEventTypeId, NodeIds.AlarmConditionType, objectTypeTree)) {
+ alarmConditionFields().forEach(field -> fields.put(field.outputField(), field));
+ }
+
+ return List.copyOf(fields.values());
+ }
+
+ static List<OpcUaAlarmField> additionalFieldsForType(NodeId selectedEventTypeId, ObjectTypeTree objectTypeTree) {
+ var baseFieldNames = baseEventFields().stream().map(OpcUaAlarmField::outputField).collect(java.util.stream.Collectors.toSet());
+
+ return fieldsForType(selectedEventTypeId, objectTypeTree).stream()
+ .filter(field -> !baseFieldNames.contains(field.outputField()))
+ .sorted(Comparator.comparing(OpcUaAlarmField::displayName, String.CASE_INSENSITIVE_ORDER))
+ .toList();
+ }
+
+ static List<OpcUaAlarmField> selectedFieldsForType(NodeId selectedEventTypeId,
+ List<String> selectedAdditionalFieldNames,
+ ObjectTypeTree objectTypeTree) {
+ var selectedAdditionalFields = Set.copyOf(selectedAdditionalFieldNames == null
+ ? List.<String>of()
+ : selectedAdditionalFieldNames);
+
+ var fields = new LinkedHashMap<String, OpcUaAlarmField>();
+ baseEventFields().forEach(field -> fields.put(field.outputField(), field));
+
+ additionalFieldsForType(selectedEventTypeId, objectTypeTree).stream()
+ .filter(field -> selectedAdditionalFields.contains(field.outputField()))
+ .forEach(field -> fields.put(field.outputField(), field));
+
+ return List.copyOf(fields.values());
+ }
+
+ static List<OpcUaAlarmField> baseEventFieldsOnly() {
+ return baseEventFields();
+ }
+
+ String displayName() {
+ return Arrays.stream(browsePath)
+ .map(QualifiedName::getName)
+ .collect(Collectors.joining(" / "));
+ }
+
+ private static String toOutputFieldName(List<QualifiedName> browsePath) {
+ var pathNames = browsePath.stream().map(QualifiedName::getName).toList();
+
+ if (pathNames.equals(List.of("AckedState", "Id"))) {
+ return "acked";
+ }
+ if (pathNames.equals(List.of("ActiveState", "Id"))) {
+ return "active";
+ }
+ if (pathNames.equals(List.of("ConfirmedState", "Id"))) {
+ return "confirmed";
+ }
+
+ var combined = String.join("", pathNames);
+ return Character.toLowerCase(combined.charAt(0)) + combined.substring(1);
+ }
+
+ private static boolean isTypeOrSubtypeOf(NodeId selectedEventTypeId,
+ NodeId targetTypeId,
+ ObjectTypeTree objectTypeTree) {
+ return selectedEventTypeId.equals(targetTypeId) || objectTypeTree.isSubtypeOf(selectedEventTypeId, targetTypeId);
+ }
+
+ private static List<OpcUaAlarmField> baseEventFields() {
+ return List.of(
+ field("sourceName", NodeIds.BaseEventType, "SourceName"),
+ field("severity", NodeIds.BaseEventType, "Severity"),
+ field("sourceNode", NodeIds.BaseEventType, "SourceNode"),
+ field("message", NodeIds.BaseEventType, "Message"),
+ field("time", NodeIds.BaseEventType, "Time"),
+ field("eventId", NodeIds.BaseEventType, "EventId"),
+ field("eventType", NodeIds.BaseEventType, "EventType")
+ );
+ }
+
+ private static List<OpcUaAlarmField> conditionFields() {
+ return List.of(
+ field("conditionName", NodeIds.ConditionType, "ConditionName"),
+ field("retain", NodeIds.ConditionType, "Retain")
+ );
+ }
+
+ private static List<OpcUaAlarmField> acknowledgeableConditionFields() {
+ return List.of(
+ field("acked", NodeIds.AcknowledgeableConditionType, "AckedState", "Id")
+ );
+ }
+
+ private static List<OpcUaAlarmField> alarmConditionFields() {
+ return List.of(
+ field("active", NodeIds.AlarmConditionType, "ActiveState", "Id")
+ );
+ }
+
+ private static OpcUaAlarmField field(String outputField,
+ NodeId typeDefinitionId,
+ String... browsePath) {
+ return new OpcUaAlarmField(outputField, typeDefinitionId, qualifiedNames(browsePath));
+ }
+
+ private static QualifiedName[] qualifiedNames(String... elements) {
+ var qualifiedNames = new QualifiedName[elements.length];
+ for (int i = 0; i < elements.length; i++) {
+ qualifiedNames[i] = new QualifiedName(0, elements[i]);
+ }
+ return qualifiedNames;
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmSchemaProvider.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmSchemaProvider.java
new file mode 100644
index 0000000000..7299e4a18b
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmSchemaProvider.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.apache.streampipes.client.api.IStreamPipesClient;
+import org.apache.streampipes.commons.exceptions.connect.AdapterException;
+import org.apache.streampipes.extensions.api.extractor.IAdapterParameterExtractor;
+import org.apache.streampipes.extensions.connectors.opcua.client.OpcUaClientProvider;
+import org.apache.streampipes.extensions.connectors.opcua.config.SpOpcUaConfigExtractor;
+import org.apache.streampipes.model.connect.guess.SampleData;
+import org.apache.streampipes.sdk.builder.adapter.SampleDataBuilder;
+
+import java.util.Map;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+public class OpcUaAlarmSchemaProvider {
+
+ private static final long PREVIEW_TIMEOUT_SECONDS = 10L;
+
+ SampleData getSampleData(OpcUaClientProvider clientProvider,
+ IAdapterParameterExtractor extractor,
+ IStreamPipesClient streamPipesClient) throws AdapterException {
+ var opcUaConfig = SpOpcUaConfigExtractor.extractAlarmAdapterConfig(
+ extractor.getStaticPropertyExtractor(),
+ streamPipesClient,
+ extractor.getAdapterDescription().getElementId()
+ );
+
+ try {
+ var connectedClient = clientProvider.getClient(opcUaConfig);
+ var queue = new LinkedBlockingQueue<Map<String, Object>>(1);
+ var subscriber = new OpcUaAlarmEventSubscriber(connectedClient, opcUaConfig, queue::offer);
+
+ try (subscriber) {
+ subscriber.start();
+
+ var sampleEvent = queue.poll(PREVIEW_TIMEOUT_SECONDS, TimeUnit.SECONDS);
+ if (sampleEvent == null) {
+ throw new AdapterException(
+ "Connected successfully, but no OPC UA events were received during the preview window."
+ );
+ }
+
+ return SampleDataBuilder.create()
+ .sample(sampleEvent)
+ .build();
+ } finally {
+ clientProvider.releaseClient(opcUaConfig);
+ }
+ } catch (AdapterException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AdapterException("Could not read OPC UA event preview data", e);
+ }
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmValueNormalizer.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmValueNormalizer.java
new file mode 100644
index 0000000000..747eb0c058
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmValueNormalizer.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.apache.streampipes.extensions.connectors.opcua.utils.OpcUaValueNormalizationUtils;
+
+import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
+import org.eclipse.milo.opcua.stack.core.types.builtin.XmlElement;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class OpcUaAlarmValueNormalizer {
+
+ Object normalize(Object value) {
+ if (value == null) {
+ return null;
+ }
+
+ if (value instanceof DataValue dataValue) {
+ return dataValueToMap(dataValue);
+ }
+
+ if (value instanceof XmlElement xmlElement) {
+ return xmlElement.getFragment();
+ }
+
+ return OpcUaValueNormalizationUtils.tryNormalizeCommonValue(value, this::normalize)
+ .orElseGet(() -> String.valueOf(value));
+ }
+
+ private Map<String, Object> dataValueToMap(DataValue dataValue) {
+ var normalized = new LinkedHashMap<String, Object>();
+ normalized.put("value", dataValue.getValue() != null ? normalize(dataValue.getValue().getValue()) : null);
+ normalized.put("statusCode", dataValue.getStatusCode() != null ? dataValue.getStatusCode().getValue() : null);
+ normalized.put("sourceTimestamp", dataValue.getSourceTime() != null ? dataValue.getSourceTime().getJavaTime() : null);
+ normalized.put("serverTimestamp", dataValue.getServerTime() != null ? dataValue.getServerTime().getJavaTime() : null);
+ return normalized;
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaEventFieldProvider.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaEventFieldProvider.java
new file mode 100644
index 0000000000..dc17dcb739
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaEventFieldProvider.java
@@ -0,0 +1,143 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.apache.streampipes.model.staticproperty.Option;
+
+import org.eclipse.milo.opcua.sdk.client.AddressSpace;
+import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
+import org.eclipse.milo.opcua.sdk.client.nodes.UaNode;
+import org.eclipse.milo.opcua.sdk.core.typetree.ObjectType;
+import org.eclipse.milo.opcua.sdk.core.typetree.ObjectTypeTree;
+import org.eclipse.milo.opcua.stack.core.NodeIds;
+import org.eclipse.milo.opcua.stack.core.UaException;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
+import org.eclipse.milo.opcua.stack.core.types.enumerated.BrowseDirection;
+import org.eclipse.milo.opcua.stack.core.types.enumerated.NodeClass;
+import org.eclipse.milo.opcua.stack.core.util.Tree;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class OpcUaEventFieldProvider {
+
+ private static final Set<String> BASE_FIELD_NAMES = OpcUaAlarmField.baseEventFieldsOnly()
+ .stream()
+ .map(OpcUaAlarmField::outputField)
+ .collect(Collectors.toSet());
+
+ private final OpcUaClient client;
+ private final ObjectTypeTree objectTypeTree;
+
+ public OpcUaEventFieldProvider(OpcUaClient client) throws UaException {
+ this.client = client;
+ this.objectTypeTree = client.readObjectTypeTree();
+ }
+
+ public List<Option> buildAdditionalFieldOptions(String selectedEventTypeNodeId, List<Option> currentOptions) {
+ var selectedFieldNames = currentOptions == null
+ ? Set.<String>of()
+ : currentOptions.stream()
+ .filter(Option::isSelected)
+ .map(Option::getInternalName)
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+
+ return buildAdditionalFields(NodeId.parse(selectedEventTypeNodeId)).stream()
+ .map(field -> {
+ var option = new Option(field.displayName(), field.outputField());
+ option.setSelected(selectedFieldNames.contains(field.outputField()));
+ return option;
+ })
+ .toList();
+ }
+
+ public List<OpcUaAlarmField> buildSelectedFields(String selectedEventTypeNodeId,
+ List<String> selectedAdditionalFieldNames) {
+ var selectedNames = Set.copyOf(selectedAdditionalFieldNames == null
+ ? List.<String>of()
+ : selectedAdditionalFieldNames);
+
+ var fields = new LinkedHashMap<String, OpcUaAlarmField>();
+ OpcUaAlarmField.baseEventFieldsOnly().forEach(field -> fields.put(field.outputField(), field));
+
+ buildAdditionalFields(NodeId.parse(selectedEventTypeNodeId)).stream()
+ .filter(field -> selectedNames.contains(field.outputField()))
+ .forEach(field -> fields.put(field.outputField(), field));
+
+ return List.copyOf(fields.values());
+ }
+
+ private List<OpcUaAlarmField> buildAdditionalFields(NodeId selectedEventTypeId) {
+ Tree<ObjectType> selectedTypeNode = objectTypeTree.getTreeNode(selectedEventTypeId);
+ if (selectedTypeNode == null) {
+ return List.of();
+ }
+
+ var fields = new LinkedHashMap<String, OpcUaAlarmField>();
+
+ for (Tree<ObjectType> current = selectedTypeNode; current != null; current = current.getParent()) {
+ collectInstanceDeclarations(current.getValue().getNodeId(), current.getValue().getNodeId(), List.of(), fields);
+ }
+
+ return fields.values().stream()
+ .filter(field -> !BASE_FIELD_NAMES.contains(field.outputField()))
+ .sorted(java.util.Comparator.comparing(OpcUaAlarmField::displayName, String.CASE_INSENSITIVE_ORDER))
+ .toList();
+ }
+
+ private void collectInstanceDeclarations(NodeId currentNodeId,
+ NodeId declaringTypeId,
+ List<QualifiedName> currentPath,
+ Map<String, OpcUaAlarmField> fields) {
+ for (UaNode childNode : browseAggregateChildren(currentNodeId)) {
+ var nextPath = new ArrayList<>(currentPath);
+ nextPath.add(childNode.getBrowseName());
+
+ var nestedChildren = browseAggregateChildren(childNode.getNodeId());
+ if (nestedChildren.isEmpty()) {
+ var field = OpcUaAlarmField.fromBrowsePath(declaringTypeId, nextPath);
+ fields.putIfAbsent(field.outputField(), field);
+ } else {
+ collectInstanceDeclarations(childNode.getNodeId(), declaringTypeId, nextPath, fields);
+ }
+ }
+ }
+
+ private List<? extends UaNode> browseAggregateChildren(NodeId nodeId) {
+ try {
+ var options = AddressSpace.BrowseOptions.builder()
+ .setBrowseDirection(BrowseDirection.Forward)
+ .setReferenceType(NodeIds.Aggregates)
+ .setIncludeSubtypes(true)
+ .setNodeClassMask(Set.of(NodeClass.Object, NodeClass.Variable))
+ .build();
+
+ return client.getAddressSpace().browseNodes(nodeId, options);
+ } catch (UaException e) {
+ return List.of();
+ }
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaEventTypeBrowser.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaEventTypeBrowser.java
new file mode 100644
index 0000000000..a13c44f369
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaEventTypeBrowser.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.apache.streampipes.model.staticproperty.TreeInputNode;
+
+import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
+import org.eclipse.milo.opcua.sdk.core.typetree.ObjectType;
+import org.eclipse.milo.opcua.sdk.core.typetree.ObjectTypeTree;
+import org.eclipse.milo.opcua.stack.core.NodeIds;
+import org.eclipse.milo.opcua.stack.core.UaException;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+import org.eclipse.milo.opcua.stack.core.util.Tree;
+
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class OpcUaEventTypeBrowser {
+
+ private static final String SELECTABLE_METADATA_KEY = "selectable";
+
+ private final ObjectTypeTree objectTypeTree;
+
+ public OpcUaEventTypeBrowser(OpcUaClient client) throws UaException {
+ this.objectTypeTree = client.readObjectTypeTree();
+ }
+
+ public List<TreeInputNode> buildNodeTreeFromOrigin(String nextBaseNodeToResolve) {
+ Tree<ObjectType> currentNode = nextBaseNodeToResolve == null
+ ? objectTypeTree.getTreeNode(NodeIds.BaseEventType)
+ : objectTypeTree.getTreeNode(NodeId.parse(nextBaseNodeToResolve));
+
+ if (currentNode == null) {
+ return List.of();
+ }
+
+ if (nextBaseNodeToResolve == null) {
+ return List.of(toTreeNode(currentNode));
+ }
+
+ return currentNode.getChildren().stream()
+ .map(this::toTreeNode)
+ .collect(Collectors.toMap(
+ TreeInputNode::getInternalNodeName,
+ node -> node,
+ (existing, duplicate) -> existing,
+ LinkedHashMap::new
+ ))
+ .values()
+ .stream()
+ .sorted(Comparator.comparing(TreeInputNode::getNodeName, String.CASE_INSENSITIVE_ORDER))
+ .toList();
+ }
+
+ private TreeInputNode toTreeNode(Tree<ObjectType> treeNode) {
+ var objectType = treeNode.getValue();
+ var node = new TreeInputNode();
+ node.setNodeName(objectType.getBrowseName().getName());
+ node.setInternalNodeName(objectType.getNodeId().toParseableString());
+ node.setDataNode(false);
+
+ Map<String, Object> metadata = new LinkedHashMap<>();
+ metadata.put("Node ID", objectType.getNodeId().toParseableString());
+ metadata.put("BrowseName", objectType.getBrowseName().getName());
+ metadata.put("NodeClass", "ObjectType");
+ metadata.put("Abstract", String.valueOf(Boolean.TRUE.equals(objectType.isAbstract())));
+ metadata.put(SELECTABLE_METADATA_KEY, true);
+ node.setNodeMetadata(metadata);
+
+ return node;
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaNotifierBrowser.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaNotifierBrowser.java
new file mode 100644
index 0000000000..240145dafe
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaNotifierBrowser.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.apache.streampipes.extensions.connectors.opcua.adapter.OpcUaNodeMetadataExtractor;
+import org.apache.streampipes.model.staticproperty.TreeInputNode;
+
+import org.eclipse.milo.opcua.sdk.client.AddressSpace;
+import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
+import org.eclipse.milo.opcua.sdk.client.nodes.UaNode;
+import org.eclipse.milo.opcua.stack.core.AttributeId;
+import org.eclipse.milo.opcua.stack.core.NodeIds;
+import org.eclipse.milo.opcua.stack.core.UaException;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UByte;
+import org.eclipse.milo.opcua.stack.core.types.enumerated.BrowseDirection;
+import org.eclipse.milo.opcua.stack.core.types.enumerated.NodeClass;
+import org.eclipse.milo.opcua.stack.core.types.structured.ReferenceDescription;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class OpcUaNotifierBrowser {
+
+ private static final Logger LOG = LoggerFactory.getLogger(OpcUaNotifierBrowser.class);
+ private static final String SELECTABLE_METADATA_KEY = "selectable";
+
+ private final OpcUaClient client;
+
+ public OpcUaNotifierBrowser(OpcUaClient client) {
+ this.client = client;
+ }
+
+ public List<TreeInputNode> buildNodeTreeFromOrigin(String nextBaseNodeToResolve) throws UaException {
+ var currentNodeId = nextBaseNodeToResolve == null
+ ? NodeIds.ObjectsFolder
+ : NodeId.parse(nextBaseNodeToResolve);
+
+ return findChildren(currentNodeId);
+ }
+
+ private List<TreeInputNode> findChildren(NodeId nodeId) throws UaException {
+ var options = AddressSpace.BrowseOptions.builder()
+ .setBrowseDirection(BrowseDirection.Forward)
+ .setReferenceType(NodeIds.HierarchicalReferences)
+ .setIncludeSubtypes(true)
+ .setNodeClassMask(Set.of(NodeClass.Object))
+ .build();
+
+ var resolvedChildren = new ArrayList<TreeInputNode>();
+
+ for (ReferenceDescription reference : client.getAddressSpace().browse(nodeId, options)) {
+ tryResolveChildNode(reference).ifPresent(childNode -> resolvedChildren.add(toTreeNode(childNode)));
+ }
+
+ return resolvedChildren.stream()
+ .collect(Collectors.toMap(
+ TreeInputNode::getInternalNodeName,
+ node -> node,
+ (existing, duplicate) -> existing,
+ LinkedHashMap::new
+ ))
+ .values()
+ .stream()
+ .sorted(Comparator.comparing(TreeInputNode::getNodeName, String.CASE_INSENSITIVE_ORDER))
+ .toList();
+ }
+
+ private Optional<UaNode> tryResolveChildNode(ReferenceDescription reference) {
+ try {
+ var nodeId = reference.getNodeId().toNodeId(client.getNamespaceTable());
+ if (nodeId.isEmpty()) {
+ return Optional.empty();
+ }
+
+ return Optional.of(client.getAddressSpace().getNode(nodeId.get()));
+ } catch (UaException e) {
+ LOG.debug(
+ "Skipping OPC UA notifier tree reference {} because the node cannot be resolved with the current security settings",
+ reference.getNodeId(),
+ e
+ );
+ return Optional.empty();
+ }
+ }
+
+ private TreeInputNode toTreeNode(UaNode node) {
+ var treeNode = new TreeInputNode();
+ treeNode.setNodeName(node.getDisplayName().getText());
+ treeNode.setInternalNodeName(node.getNodeId().toParseableString());
+ treeNode.setDataNode(false);
+
+ var metadata = new OpcUaNodeMetadataExtractor(client, node).extract();
+ metadata.put(SELECTABLE_METADATA_KEY, isSelectableNotifierNode(node));
+ treeNode.setNodeMetadata(metadata);
+
+ return treeNode;
+ }
+
+ private boolean isSelectableNotifierNode(UaNode node) {
+ try {
+ var eventNotifier = node.readAttribute(AttributeId.EventNotifier);
+ var value = eventNotifier.getValue() != null ? eventNotifier.getValue().getValue() : null;
+
+ if (value instanceof UByte uByte) {
+ return uByte.intValue() > 0;
+ }
+
+ if (value instanceof Number number) {
+ return number.intValue() > 0;
+ }
+
+ return false;
+ } catch (UaException e) {
+ LOG.debug("Skipping EventNotifier inspection for node {}", node.getNodeId(), e);
+ return false;
+ }
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/client/ConnectedOpcUaClient.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/client/ConnectedOpcUaClient.java
index 7f1a92cacc..ddb27e5bd3 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/client/ConnectedOpcUaClient.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/client/ConnectedOpcUaClient.java
@@ -96,7 +96,7 @@ public class ConnectedOpcUaClient {
private @NonNull OpcUaSubscription getOpcUaSubscription(List<NodeId> nodes,
OpcUaAdapter opcUaAdapter) throws UaException {
- var subscription = new OpcUaSubscription(this.client, 1000.0);
+ OpcUaSubscription subscription = createManagedSubscription();
subscription.setSubscriptionListener(new OpcUaSubscription.SubscriptionListener() {
@Override
public void onTransferFailed(OpcUaSubscription subscription, StatusCode statusCode) {
@@ -108,6 +108,11 @@ public class ConnectedOpcUaClient {
}
}
});
+ return subscription;
+ }
+
+ private OpcUaSubscription createManagedSubscription() throws UaException {
+ var subscription = new OpcUaSubscription(this.client, 1000.0);
subscription.create();
return subscription;
}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/client/OpcUaClientProvider.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/client/OpcUaClientProvider.java
index e9fe90488f..056ec7a8ba 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/client/OpcUaClientProvider.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/client/OpcUaClientProvider.java
@@ -45,9 +45,15 @@ public class OpcUaClientProvider {
throws UaException, SpConfigurationException, URISyntaxException, ExecutionException, InterruptedException {
var serverId = config.getUniqueServerId();
if (clients.containsKey(serverId)) {
- LOG.debug("Adding new consumer to client {}", serverId);
- consumers.put(serverId, consumers.get(config.getUniqueServerId()) + 1);
+ int newConsumerCount = consumers.get(config.getUniqueServerId()) + 1;
+ consumers.put(serverId, newConsumerCount);
var client = clients.get(serverId);
+ LOG.debug(
+ "Reusing OPC UA client {} (identity={}) with consumerCount={}",
+ serverId,
+ System.identityHashCode(client.getClient()),
+ newConsumerCount
+ );
var associatedResourceId = config.getAssociatedResourceId();
if (serverThumbprints.containsKey(serverId) && Objects.nonNull(associatedResourceId)) {
OpcUaCertificateUtils.sendUsageToCore(
@@ -58,10 +64,15 @@ public class OpcUaClientProvider {
}
return client;
} else {
- LOG.debug("Creating new client {}", serverId);
+ LOG.debug("Creating new OPC UA client {}", serverId);
var connectedClient = new SpOpcUaClient<>(config).connect();
clients.put(serverId, connectedClient);
consumers.put(serverId, 1);
+ LOG.debug(
+ "Created OPC UA client {} (identity={}) with consumerCount=1",
+ serverId,
+ System.identityHashCode(connectedClient.getClient())
+ );
if (config.getCertificateThumbprint() != null) {
serverThumbprints.put(serverId, config.getCertificateThumbprint());
}
@@ -71,13 +82,19 @@ public class OpcUaClientProvider {
public <T extends OpcUaConfig> void releaseClient(T config) {
String serverId = config.getUniqueServerId();
- LOG.debug("Releasing client {}", serverId);
-
synchronized (this) {
consumers.computeIfPresent(serverId, (key, count) -> {
int updatedCount = count - 1;
+ ConnectedOpcUaClient client = clients.get(serverId);
+ LOG.debug(
+ "Releasing OPC UA client {} (identity={}) from consumerCount={} to {}",
+ serverId,
+ client != null ? System.identityHashCode(client.getClient()) : null,
+ count,
+ Math.max(updatedCount, 0)
+ );
if (updatedCount <= 0) {
- LOG.debug("Disconnecting client {}", serverId);
+ LOG.debug("Disconnecting OPC UA client {}", serverId);
if (clients.containsKey(serverId)) {
clients.get(serverId).disconnect();
clients.remove(serverId);
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/config/SharedUserConfiguration.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/config/SharedUserConfiguration.java
index 2e3960baf4..dbf25d83c6 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/config/SharedUserConfiguration.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/config/SharedUserConfiguration.java
@@ -72,9 +72,24 @@ public class SharedUserConfiguration {
public static void appendSharedOpcUaConfig(AbstractConfigurablePipelineElementBuilder<?, ?> builder,
boolean adapterConfig) {
+ appendConnectionConfiguration(builder);
var dependsOn = getDependsOn(adapterConfig);
+ builder.requiredRuntimeResolvableTreeInput(
+ Labels.withId(AVAILABLE_NODES.name()),
+ dependsOn,
+ true,
+ adapterConfig
+ );
+ }
+
+ public static void appendSharedOpcUaConnectionConfig(AbstractConfigurablePipelineElementBuilder<?, ?> builder) {
+ appendConnectionConfiguration(builder);
+ }
+
+ private static void appendConnectionConfiguration(AbstractConfigurablePipelineElementBuilder<?, ?> builder) {
+
var x509Group = StaticProperties.group(
Labels.withId(X509_GROUP),
StaticProperties.secretValue(Labels.withId(X509_PRIVATE_KEY_PEM)),
@@ -116,12 +131,6 @@ public class SharedUserConfiguration {
StaticProperties.integerFreeTextProperty(
Labels.withId(OPC_SERVER_PORT))
))
- )
- .requiredRuntimeResolvableTreeInput(
- Labels.withId(AVAILABLE_NODES.name()),
- dependsOn,
- true,
- adapterConfig
);
}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/config/SpOpcUaConfigExtractor.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/config/SpOpcUaConfigExtractor.java
index 9363339bd8..e017fb1856 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/config/SpOpcUaConfigExtractor.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/config/SpOpcUaConfigExtractor.java
@@ -21,6 +21,8 @@ package org.apache.streampipes.extensions.connectors.opcua.config;
import org.apache.streampipes.client.api.IStreamPipesClient;
import org.apache.streampipes.extensions.api.extractor.IParameterExtractor;
import org.apache.streampipes.extensions.api.extractor.IStaticPropertyExtractor;
+import org.apache.streampipes.extensions.connectors.opcua.alarms.OpcUaAlarmAdapterConfig;
+import org.apache.streampipes.extensions.connectors.opcua.alarms.OpcUaAlarmConfiguration;
import org.apache.streampipes.extensions.connectors.opcua.config.identity.AnonymousIdentityConfig;
import org.apache.streampipes.extensions.connectors.opcua.config.identity.UsernamePasswordIdentityConfig;
import org.apache.streampipes.extensions.connectors.opcua.config.identity.X509IdentityConfig;
@@ -32,6 +34,7 @@ import org.apache.streampipes.extensions.connectors.opcua.utils.OpcUaUtils;
import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy;
import org.eclipse.milo.opcua.stack.core.types.enumerated.MessageSecurityMode;
+import java.util.Collections;
import java.util.List;
import static org.apache.streampipes.extensions.connectors.opcua.utils.OpcUaLabels.ADAPTER_TYPE;
@@ -96,9 +99,58 @@ public class SpOpcUaConfigExtractor {
return extractSharedConfig(extractor, new OpcUaConfig(), streamPipesClient);
}
+ public static OpcUaAlarmAdapterConfig extractAlarmAdapterConfig(IStaticPropertyExtractor extractor,
+ IStreamPipesClient streamPipesClient,
+ String adapterId) {
+ var config = extractConnectionConfig(extractor, new OpcUaAlarmAdapterConfig(), streamPipesClient);
+ config.setAssociatedResourceId(adapterId);
+
+ var alarmSourceScope = extractor.selectedAlternativeInternalId(OpcUaAlarmConfiguration.ALARM_SOURCE_SCOPE);
+ if (OpcUaAlarmConfiguration.SPECIFIC_AREA_OR_MACHINE.equals(alarmSourceScope)) {
+ var selectedNotifierNodes =
+ extractor.selectedTreeNodesInternalNames(OpcUaAlarmConfiguration.NOTIFIER_NODE, String.class);
+ if (!selectedNotifierNodes.isEmpty()) {
+ config.setNotifierNodeId(selectedNotifierNodes.get(0));
+ }
+ }
+ var selectedEventTypes =
+ extractor.selectedTreeNodesInternalNames(OpcUaAlarmConfiguration.EVENT_TYPE, String.class);
+ if (!selectedEventTypes.isEmpty()) {
+ config.setEventTypeNodeId(selectedEventTypes.get(0));
+ }
+ config.setSelectedAdditionalFieldNames(
+ extractor.selectedMultiValuesInternalNames(OpcUaAlarmConfiguration.ADDITIONAL_FIELDS, String.class)
+ );
+
+ var alarmFilterMode = extractor.selectedAlternativeInternalId(OpcUaAlarmConfiguration.ALARM_FILTER_MODE);
+ if (OpcUaAlarmConfiguration.SOURCE_NAME_CONTAINS.equals(alarmFilterMode)) {
+ config.setSourceNameFilter(extractor.textParameter(OpcUaAlarmConfiguration.SOURCE_NAME_FILTER));
+ }
+
+ var minimumSeverity = extractor.selectedSingleValueInternalName(OpcUaAlarmConfiguration.MINIMUM_SEVERITY, String.class);
+ if (!OpcUaAlarmConfiguration.MINIMUM_SEVERITY_ANY.equals(minimumSeverity)) {
+ config.setMinimumSeverity(Integer.parseInt(minimumSeverity));
+ }
+
+ return config;
+ }
+
public static <T extends OpcUaConfig> T extractSharedConfig(IParameterExtractor extractor,
T config,
IStreamPipesClient streamPipesClient) {
+ return extractSharedConfig(extractor, config, streamPipesClient, true);
+ }
+
+ public static <T extends OpcUaConfig> T extractConnectionConfig(IParameterExtractor extractor,
+ T config,
+ IStreamPipesClient streamPipesClient) {
+ return extractSharedConfig(extractor, config, streamPipesClient, false);
+ }
+
+ private static <T extends OpcUaConfig> T extractSharedConfig(IParameterExtractor extractor,
+ T config,
+ IStreamPipesClient streamPipesClient,
+ boolean includeNodeSelection) {
String selectedAlternativeConnection =
extractor.selectedAlternativeInternalId(OPC_HOST_OR_URL.name());
@@ -106,9 +158,13 @@ public class SpOpcUaConfigExtractor {
String selectedAlternativeAuthentication =
extractor.selectedAlternativeInternalId(SharedUserConfiguration.USER_AUTHENTICATION);
- List<String> selectedNodeNames =
- extractor.selectedTreeNodesInternalNames(AVAILABLE_NODES.name(), String.class);
- config.setSelectedNodeNames(selectedNodeNames);
+ if (includeNodeSelection && extractor.getStaticPropertyByName(AVAILABLE_NODES.name()) != null) {
+ List<String> selectedNodeNames =
+ extractor.selectedTreeNodesInternalNames(AVAILABLE_NODES.name(), String.class);
+ config.setSelectedNodeNames(selectedNodeNames);
+ } else {
+ config.setSelectedNodeNames(Collections.emptyList());
+ }
String selectedSecurityMode = extractor.selectedSingleValueInternalName(
SharedUserConfiguration.SECURITY_MODE,
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/OpcUaNodeFactory.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/OpcUaNodeFactory.java
index 24418ae972..2ee07a3a19 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/OpcUaNodeFactory.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/OpcUaNodeFactory.java
@@ -23,7 +23,7 @@ import org.apache.streampipes.extensions.connectors.opcua.model.node.OpcUaNode;
import org.apache.streampipes.extensions.connectors.opcua.model.node.ScalarOpcUaNode;
import org.apache.streampipes.extensions.connectors.opcua.model.node.StructuredOpcUaNode;
-import org.eclipse.milo.opcua.stack.core.Identifiers;
+import org.eclipse.milo.opcua.stack.core.NodeIds;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
@@ -104,6 +104,6 @@ public class OpcUaNodeFactory {
*/
private static boolean isExtensionByDataType(BasicVariableNodeInfo nodeInfo) {
NodeId dt = nodeInfo.getNode().getDataType();
- return Objects.equals(dt, Identifiers.Structure);
+ return Objects.equals(dt, NodeIds.Structure);
}
}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/node/OpcUaNumberNormalizer.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/node/OpcUaNumberNormalizer.java
index e6708b30d7..69054fdd4c 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/node/OpcUaNumberNormalizer.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/node/OpcUaNumberNormalizer.java
@@ -18,10 +18,7 @@
package org.apache.streampipes.extensions.connectors.opcua.model.node;
-import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UByte;
-import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger;
-import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.ULong;
-import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UShort;
+import org.apache.streampipes.extensions.connectors.opcua.utils.OpcUaValueNormalizationUtils;
final class OpcUaNumberNormalizer {
@@ -29,22 +26,6 @@ final class OpcUaNumberNormalizer {
}
static Object normalize(Object value) {
- if (value instanceof UByte uByte) {
- return uByte.intValue();
- }
-
- if (value instanceof UShort uShort) {
- return uShort.intValue();
- }
-
- if (value instanceof UInteger uInteger) {
- return uInteger.longValue();
- }
-
- if (value instanceof ULong uLong) {
- return uLong.longValue();
- }
-
- return value;
+ return OpcUaValueNormalizationUtils.normalizeUnsignedNumber(value);
}
}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/node/StructuredOpcUaNode.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/node/StructuredOpcUaNode.java
index 696cdf6322..b97e7d0e15 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/node/StructuredOpcUaNode.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/model/node/StructuredOpcUaNode.java
@@ -18,6 +18,7 @@
package org.apache.streampipes.extensions.connectors.opcua.model.node;
+import org.apache.streampipes.extensions.connectors.opcua.utils.OpcUaValueNormalizationUtils;
import org.apache.streampipes.model.connect.guess.FieldStatus;
import org.apache.streampipes.model.connect.guess.FieldStatusInfo;
@@ -28,27 +29,14 @@ import org.eclipse.milo.opcua.sdk.core.types.DynamicEnumType;
import org.eclipse.milo.opcua.sdk.core.types.DynamicOptionSetType;
import org.eclipse.milo.opcua.sdk.core.types.DynamicStructType;
import org.eclipse.milo.opcua.sdk.core.types.DynamicUnionType;
-import org.eclipse.milo.opcua.stack.core.types.UaEnumeratedType;
import org.eclipse.milo.opcua.stack.core.types.UaStructuredType;
-import org.eclipse.milo.opcua.stack.core.types.builtin.ByteString;
-import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
-import org.eclipse.milo.opcua.stack.core.types.builtin.ExpandedNodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject;
-import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
-import org.eclipse.milo.opcua.stack.core.types.builtin.Matrix;
-import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
-import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
-import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.lang.reflect.Array;
import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Base64;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Map;
public class StructuredOpcUaNode implements OpcUaNode {
@@ -139,78 +127,18 @@ public class StructuredOpcUaNode implements OpcUaNode {
return dynamicEnumToValue(dynamicEnumType);
}
- if (value instanceof ByteString byteString) {
- var bytes = byteString.bytes();
- return bytes == null ? null : Base64.getEncoder().encodeToString(bytes);
- }
-
- if (value instanceof Matrix matrix) {
- return matrixToMap(client, matrix, depth + 1);
- }
-
- if (value instanceof DateTime dateTime) {
- return dateTime.getJavaTime();
- }
-
- if (value instanceof NodeId nodeId) {
- return nodeId.toParseableString();
- }
-
- if (value instanceof ExpandedNodeId expandedNodeId) {
- return expandedNodeId.toParseableString();
- }
-
- if (value instanceof QualifiedName qualifiedName) {
- return qualifiedName.toParseableString();
- }
-
- if (value instanceof LocalizedText localizedText) {
- return localizedText.getText();
- }
-
- if (value instanceof StatusCode statusCode) {
- return statusCode.getValue();
- }
-
- if (value instanceof UaEnumeratedType uaEnumeratedType) {
- return uaEnumeratedType.getName() != null ? uaEnumeratedType.getName() : uaEnumeratedType.getValue();
- }
-
- value = OpcUaNumberNormalizer.normalize(value);
-
- if (isScalar(value)) {
- return value;
- }
-
- if (value instanceof Map<?, ?> mapValue) {
- return mapToMap(client, mapValue, depth + 1);
- }
-
- if (value instanceof Iterable<?> iterable) {
- var listValue = new ArrayList<>();
- for (Object element : iterable) {
- listValue.add(normalizeValue(client, element, depth + 1));
- }
- return listValue;
- }
-
- if (value.getClass().isArray()) {
- int length = Array.getLength(value);
- List<Object> arrayValue = new ArrayList<>(length);
- for (int i = 0; i < length; i++) {
- arrayValue.add(normalizeValue(client, Array.get(value, i), depth + 1));
- }
- return arrayValue;
+ var normalizedCommonValue = OpcUaValueNormalizationUtils.tryNormalizeCommonValue(
+ value,
+ entry -> normalizeValue(client, entry, depth + 1)
+ );
+ if (normalizedCommonValue.isPresent()) {
+ return normalizedCommonValue.get();
}
if (value instanceof UaStructuredType) {
return objectToMap(client, value, depth + 1);
}
- if (value instanceof Enum<?> enumValue) {
- return enumValue.name();
- }
-
return objectToMap(client, value, depth + 1);
}
@@ -223,15 +151,6 @@ public class StructuredOpcUaNode implements OpcUaNode {
return result;
}
- private Map<String, Object> mapToMap(OpcUaClient client,
- Map<?, ?> mapValue,
- int depth) {
- var result = new LinkedHashMap<String, Object>();
- mapValue.forEach((key, entryValue) ->
- result.put(String.valueOf(key), normalizeValue(client, entryValue, depth + 1)));
- return result;
- }
-
private Map<String, Object> dynamicStructToMap(OpcUaClient client,
DynamicStructType dynamicStructType,
int depth) {
@@ -264,34 +183,6 @@ public class StructuredOpcUaNode implements OpcUaNode {
return enumName != null ? enumName : dynamicEnumType.getValue();
}
- private Map<String, Object> matrixToMap(OpcUaClient client,
- Matrix matrix,
- int depth) {
- var result = new LinkedHashMap<String, Object>();
- result.put("elements", arrayToList(client, matrix.getElements(), depth + 1));
- result.put("dimensions", intArrayToList(matrix.getDimensions()));
- return result;
- }
-
- private List<Object> arrayToList(OpcUaClient client,
- Object arrayValue,
- int depth) {
- int length = Array.getLength(arrayValue);
- var values = new ArrayList<>(length);
- for (int i = 0; i < length; i++) {
- values.add(normalizeValue(client, Array.get(arrayValue, i), depth + 1));
- }
- return values;
- }
-
- private List<Integer> intArrayToList(int[] values) {
- var dimensions = new ArrayList<Integer>(values.length);
- for (var value : values) {
- dimensions.add(value);
- }
- return dimensions;
- }
-
private Object decodeExtensionObject(OpcUaClient client,
ExtensionObject extensionObject,
int depth) {
@@ -353,11 +244,4 @@ public class StructuredOpcUaNode implements OpcUaNode {
return result;
}
-
- private boolean isScalar(Object value) {
- return value instanceof String
- || value instanceof Number
- || value instanceof Boolean
- || value instanceof Character;
- }
}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/ExceptionMessageExtractor.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/ExceptionMessageExtractor.java
index 9c37b09017..d6790da62e 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/ExceptionMessageExtractor.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/ExceptionMessageExtractor.java
@@ -35,4 +35,40 @@ public class ExceptionMessageExtractor {
return e.getMessage();
}
}
+
+ public static String getDescription(Throwable throwable) {
+ var rootCause = rootCause(throwable);
+
+ if (rootCause instanceof UaException uaException) {
+ return getDescription(uaException);
+ }
+
+ var message = rootCause.getMessage();
+ if (message == null || message.isBlank()) {
+ return rootCause.getClass().getSimpleName();
+ }
+
+ if (message.contains("Connection refused")) {
+ return message.substring(message.indexOf("Connection refused"));
+ }
+
+ if (message.contains("Unknown host")) {
+ return message.substring(message.indexOf("Unknown host"));
+ }
+
+ int lastColonIndex = message.lastIndexOf(": ");
+ if (lastColonIndex >= 0 && lastColonIndex + 2 < message.length()) {
+ return message.substring(lastColonIndex + 2);
+ }
+
+ return message;
+ }
+
+ private static Throwable rootCause(Throwable throwable) {
+ Throwable current = throwable;
+ while (current.getCause() != null && current.getCause() != current) {
+ current = current.getCause();
+ }
+ return current;
+ }
}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaUtils.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaUtils.java
index 9c998ea957..78eea6ecf3 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaUtils.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaUtils.java
@@ -22,11 +22,16 @@ import org.apache.streampipes.commons.exceptions.SpConfigurationException;
import org.apache.streampipes.extensions.api.extractor.IStaticPropertyExtractor;
import org.apache.streampipes.extensions.api.runtime.ResolvesContainerProvidedOptions;
import org.apache.streampipes.extensions.connectors.opcua.adapter.OpcUaNodeBrowser;
+import org.apache.streampipes.extensions.connectors.opcua.alarms.OpcUaEventFieldProvider;
+import org.apache.streampipes.extensions.connectors.opcua.alarms.OpcUaEventTypeBrowser;
+import org.apache.streampipes.extensions.connectors.opcua.alarms.OpcUaNotifierBrowser;
import org.apache.streampipes.extensions.connectors.opcua.client.OpcUaClientProvider;
import org.apache.streampipes.extensions.connectors.opcua.config.OpcUaAdapterConfig;
+import org.apache.streampipes.extensions.connectors.opcua.config.OpcUaConfig;
import org.apache.streampipes.extensions.connectors.opcua.config.SharedUserConfiguration;
import org.apache.streampipes.extensions.connectors.opcua.config.SpOpcUaConfigExtractor;
import org.apache.streampipes.extensions.management.client.StreamPipesClientResolver;
+import org.apache.streampipes.model.staticproperty.RuntimeResolvableAnyStaticProperty;
import org.apache.streampipes.model.staticproperty.RuntimeResolvableTreeInputStaticProperty;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
@@ -105,9 +110,12 @@ public class OpcUaUtils {
OpcUaCertificateUtils.makeExceptionMessage(e, opcUaConfig)
);
}
- throw new SpConfigurationException(ExceptionMessageExtractor.getDescription(e), e);
+ throw new SpConfigurationException(ExceptionMessageExtractor.getDescription(e));
} catch (ExecutionException | InterruptedException | URISyntaxException e) {
- throw new SpConfigurationException("Could not connect to the OPC UA server with the provided settings", e);
+ if (e instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ }
+ throw makeConnectionException(opcUaConfig, e);
} finally {
clientProvider.releaseClient(opcUaConfig);
}
@@ -126,4 +134,204 @@ public class OpcUaUtils {
}
}).toList();
}
+
+ public static RuntimeResolvableTreeInputStaticProperty resolveNotifierTreeConfig(
+ OpcUaClientProvider clientProvider,
+ String internalName,
+ IStaticPropertyExtractor parameterExtractor
+ )
+ throws SpConfigurationException {
+ var client = new StreamPipesClientResolver().makeStreamPipesClientInstance();
+ var config = parameterExtractor.getStaticPropertyByName(
+ internalName,
+ RuntimeResolvableTreeInputStaticProperty.class
+ );
+
+ try {
+ parameterExtractor.selectedAlternativeInternalId(OpcUaLabels.OPC_HOST_OR_URL.name());
+ parameterExtractor.selectedSingleValueInternalName(SharedUserConfiguration.SECURITY_MODE, String.class);
+ parameterExtractor.selectedSingleValue(SharedUserConfiguration.SECURITY_POLICY, String.class);
+ } catch (NullPointerException nullPointerException) {
+ return config;
+ }
+
+ var opcUaConfig = SpOpcUaConfigExtractor.extractConnectionConfig(parameterExtractor, new OpcUaConfig(), client);
+
+ try {
+ var connectedClient = clientProvider.getClient(opcUaConfig);
+ var nodeBrowser = new OpcUaNotifierBrowser(connectedClient.getClient());
+ var nodes = nodeBrowser.buildNodeTreeFromOrigin(config.getNextBaseNodeToResolve());
+ if (Objects.isNull(config.getNextBaseNodeToResolve())) {
+ config.setNodes(nodes);
+ } else {
+ config.setLatestFetchedNodes(nodes);
+ }
+
+ if (!config.getSelectedNodesInternalNames().isEmpty()) {
+ config.setSelectedNodesInternalNames(
+ filterExistingNodes(connectedClient.getClient(), config.getSelectedNodesInternalNames(), config.isMultiSelection())
+ );
+ }
+
+ return config;
+ } catch (UaException e) {
+ if (OpcUaCertificateUtils.isCertificateException(e)) {
+ throw new SpConfigurationException(
+ OpcUaCertificateUtils.makeExceptionMessage(e, opcUaConfig)
+ );
+ }
+ throw new SpConfigurationException(ExceptionMessageExtractor.getDescription(e));
+ } catch (ExecutionException | InterruptedException | URISyntaxException e) {
+ if (e instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ }
+ throw makeConnectionException(opcUaConfig, e);
+ } finally {
+ clientProvider.releaseClient(opcUaConfig);
+ }
+ }
+
+ public static RuntimeResolvableTreeInputStaticProperty resolveEventTypeTreeConfig(
+ OpcUaClientProvider clientProvider,
+ String internalName,
+ IStaticPropertyExtractor parameterExtractor
+ ) throws SpConfigurationException {
+ var client = new StreamPipesClientResolver().makeStreamPipesClientInstance();
+ var config = parameterExtractor.getStaticPropertyByName(
+ internalName,
+ RuntimeResolvableTreeInputStaticProperty.class
+ );
+
+ try {
+ parameterExtractor.selectedAlternativeInternalId(OpcUaLabels.OPC_HOST_OR_URL.name());
+ parameterExtractor.selectedSingleValueInternalName(SharedUserConfiguration.SECURITY_MODE, String.class);
+ parameterExtractor.selectedSingleValue(SharedUserConfiguration.SECURITY_POLICY, String.class);
+ } catch (NullPointerException nullPointerException) {
+ return config;
+ }
+
+ var opcUaConfig = SpOpcUaConfigExtractor.extractConnectionConfig(parameterExtractor, new OpcUaConfig(), client);
+
+ try {
+ var connectedClient = clientProvider.getClient(opcUaConfig);
+ var typeBrowser = new OpcUaEventTypeBrowser(connectedClient.getClient());
+ var nodes = typeBrowser.buildNodeTreeFromOrigin(config.getNextBaseNodeToResolve());
+ if (Objects.isNull(config.getNextBaseNodeToResolve())) {
+ config.setNodes(nodes);
+ } else {
+ config.setLatestFetchedNodes(nodes);
+ }
+
+ if (!config.getSelectedNodesInternalNames().isEmpty()) {
+ config.setSelectedNodesInternalNames(
+ filterExistingNodes(connectedClient.getClient(), config.getSelectedNodesInternalNames(), config.isMultiSelection())
+ );
+ }
+
+ return config;
+ } catch (UaException e) {
+ if (OpcUaCertificateUtils.isCertificateException(e)) {
+ throw new SpConfigurationException(
+ OpcUaCertificateUtils.makeExceptionMessage(e, opcUaConfig)
+ );
+ }
+ throw new SpConfigurationException(ExceptionMessageExtractor.getDescription(e));
+ } catch (ExecutionException | InterruptedException | URISyntaxException e) {
+ if (e instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ }
+ throw makeConnectionException(opcUaConfig, e);
+ } finally {
+ clientProvider.releaseClient(opcUaConfig);
+ }
+ }
+
+ public static RuntimeResolvableAnyStaticProperty resolveEventFieldConfig(
+ OpcUaClientProvider clientProvider,
+ String internalName,
+ IStaticPropertyExtractor parameterExtractor
+ ) throws SpConfigurationException {
+ var client = new StreamPipesClientResolver().makeStreamPipesClientInstance();
+ var config = parameterExtractor.getStaticPropertyByName(
+ internalName,
+ RuntimeResolvableAnyStaticProperty.class
+ );
+
+ try {
+ parameterExtractor.selectedAlternativeInternalId(OpcUaLabels.OPC_HOST_OR_URL.name());
+ parameterExtractor.selectedSingleValueInternalName(SharedUserConfiguration.SECURITY_MODE, String.class);
+ parameterExtractor.selectedSingleValue(SharedUserConfiguration.SECURITY_POLICY, String.class);
+ } catch (NullPointerException nullPointerException) {
+ return config;
+ }
+
+ var selectedEventTypes = parameterExtractor.selectedTreeNodesInternalNames(
+ org.apache.streampipes.extensions.connectors.opcua.alarms.OpcUaAlarmConfiguration.EVENT_TYPE,
+ String.class
+ );
+ if (selectedEventTypes.isEmpty()) {
+ config.setOptions(List.of());
+ return config;
+ }
+
+ var opcUaConfig = SpOpcUaConfigExtractor.extractConnectionConfig(parameterExtractor, new OpcUaConfig(), client);
+
+ try {
+ var connectedClient = clientProvider.getClient(opcUaConfig);
+ var fieldProvider = new OpcUaEventFieldProvider(connectedClient.getClient());
+ config.setOptions(fieldProvider.buildAdditionalFieldOptions(selectedEventTypes.get(0), config.getOptions()));
+ return config;
+ } catch (UaException e) {
+ if (OpcUaCertificateUtils.isCertificateException(e)) {
+ throw new SpConfigurationException(
+ OpcUaCertificateUtils.makeExceptionMessage(e, opcUaConfig)
+ );
+ }
+ throw new SpConfigurationException(ExceptionMessageExtractor.getDescription(e));
+ } catch (ExecutionException | InterruptedException | URISyntaxException e) {
+ if (e instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ }
+ throw makeConnectionException(opcUaConfig, e);
+ } finally {
+ clientProvider.releaseClient(opcUaConfig);
+ }
+ }
+
+ private static SpConfigurationException makeConnectionException(OpcUaConfig opcUaConfig,
+ Throwable throwable) {
+ String detail = ExceptionMessageExtractor.getDescription(throwable);
+ String serverUrl = opcUaConfig.getOpcServerURL();
+
+ if (detail == null || detail.isBlank()) {
+ return new SpConfigurationException(
+ "Could not connect to the OPC UA server at " + serverUrl + "."
+ );
+ }
+
+ return new SpConfigurationException(
+ "Could not connect to the OPC UA server at " + serverUrl + ": " + detail
+ );
+ }
+
+ private static List<String> filterExistingNodes(OpcUaClient opcUaClient,
+ List<String> selectedNodes,
+ boolean multiSelection) {
+ var filtered = selectedNodes.stream()
+ .filter(selectedNode -> {
+ try {
+ opcUaClient.getAddressSpace().getNode(NodeId.parse(selectedNode));
+ return true;
+ } catch (UaException e) {
+ return false;
+ }
+ })
+ .toList();
+
+ if (!multiSelection && !filtered.isEmpty()) {
+ return List.of(filtered.get(0));
+ }
+
+ return filtered;
+ }
}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaValueNormalizationUtils.java b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaValueNormalizationUtils.java
new file mode 100644
index 0000000000..a5f0e29544
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaValueNormalizationUtils.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.utils;
+
+import org.eclipse.milo.opcua.stack.core.types.UaEnumeratedType;
+import org.eclipse.milo.opcua.stack.core.types.builtin.ByteString;
+import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
+import org.eclipse.milo.opcua.stack.core.types.builtin.ExpandedNodeId;
+import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
+import org.eclipse.milo.opcua.stack.core.types.builtin.Matrix;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
+import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;
+import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UByte;
+import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger;
+import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.ULong;
+import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UShort;
+
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Function;
+
+public final class OpcUaValueNormalizationUtils {
+
+ private OpcUaValueNormalizationUtils() {
+ }
+
+ public static Optional<Object> tryNormalizeCommonValue(Object value,
+ Function<Object, Object> recursiveNormalizer) {
+ if (value instanceof ByteString byteString) {
+ var bytes = byteString.bytes();
+ return Optional.ofNullable(bytes == null ? null : Base64.getEncoder().encodeToString(bytes));
+ }
+
+ if (value instanceof DateTime dateTime) {
+ return Optional.of(dateTime.getJavaTime());
+ }
+
+ if (value instanceof NodeId nodeId) {
+ return Optional.of(nodeId.toParseableString());
+ }
+
+ if (value instanceof ExpandedNodeId expandedNodeId) {
+ return Optional.of(expandedNodeId.toParseableString());
+ }
+
+ if (value instanceof QualifiedName qualifiedName) {
+ return Optional.of(qualifiedName.toParseableString());
+ }
+
+ if (value instanceof LocalizedText localizedText) {
+ return Optional.ofNullable(localizedText.getText());
+ }
+
+ if (value instanceof StatusCode statusCode) {
+ return Optional.of(statusCode.getValue());
+ }
+
+ if (value instanceof UaEnumeratedType enumeratedType) {
+ return Optional.of(
+ enumeratedType.getName() != null ? enumeratedType.getName() : enumeratedType.getValue()
+ );
+ }
+
+ if (value instanceof Matrix matrix) {
+ return Optional.of(matrixToMap(matrix, recursiveNormalizer));
+ }
+
+ value = normalizeUnsignedNumber(value);
+
+ if (isScalar(value)) {
+ return Optional.of(value);
+ }
+
+ if (value instanceof Map<?, ?> mapValue) {
+ var normalized = new LinkedHashMap<String, Object>();
+ mapValue.forEach((key, mapEntryValue) ->
+ normalized.put(String.valueOf(key), recursiveNormalizer.apply(mapEntryValue)));
+ return Optional.of(normalized);
+ }
+
+ if (value instanceof Iterable<?> iterable) {
+ var normalized = new ArrayList<>();
+ iterable.forEach(entry -> normalized.add(recursiveNormalizer.apply(entry)));
+ return Optional.of(normalized);
+ }
+
+ if (value.getClass().isArray()) {
+ return Optional.of(arrayToList(value, recursiveNormalizer));
+ }
+
+ if (value instanceof Enum<?> enumValue) {
+ return Optional.of(enumValue.name());
+ }
+
+ return Optional.empty();
+ }
+
+ private static Map<String, Object> matrixToMap(Matrix matrix,
+ Function<Object, Object> recursiveNormalizer) {
+ var normalized = new LinkedHashMap<String, Object>();
+ normalized.put("elements", arrayToList(matrix.getElements(), recursiveNormalizer));
+ normalized.put("dimensions", intArrayToList(matrix.getDimensions()));
+ return normalized;
+ }
+
+ private static List<Object> arrayToList(Object arrayValue,
+ Function<Object, Object> recursiveNormalizer) {
+ var length = Array.getLength(arrayValue);
+ var values = new ArrayList<>(length);
+ for (int i = 0; i < length; i++) {
+ values.add(recursiveNormalizer.apply(Array.get(arrayValue, i)));
+ }
+ return values;
+ }
+
+ private static List<Integer> intArrayToList(int[] values) {
+ var normalized = new ArrayList<Integer>(values.length);
+ for (var value : values) {
+ normalized.add(value);
+ }
+ return normalized;
+ }
+
+ private static boolean isScalar(Object value) {
+ return value instanceof String
+ || value instanceof Number
+ || value instanceof Boolean
+ || value instanceof Character;
+ }
+
+ public static Object normalizeUnsignedNumber(Object value) {
+ if (value instanceof UByte uByte) {
+ return uByte.intValue();
+ }
+
+ if (value instanceof UShort uShort) {
+ return uShort.intValue();
+ }
+
+ if (value instanceof UInteger uInteger) {
+ return uInteger.longValue();
+ }
+
+ if (value instanceof ULong uLong) {
+ return uLong.longValue();
+ }
+
+ return value;
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/resources/org.apache.streampipes.connect.iiot.adapters.opcua-alarms/documentation.md b/streampipes-extensions/streampipes-connectors-opcua/src/main/resources/org.apache.streampipes.connect.iiot.adapters.opcua-alarms/documentation.md
new file mode 100644
index 0000000000..2559e5a80d
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/resources/org.apache.streampipes.connect.iiot.adapters.opcua-alarms/documentation.md
@@ -0,0 +1,15 @@
+# OPC UA Events
+
+This adapter subscribes to OPC UA server events and emits read-only OPC UA event payloads.
+
+## Current scope
+
+- Reuses the same OPC UA connection, security, and authentication settings as the OPC UA value adapter
+- Subscribes either server-wide or to a selected notifier node
+- Uses a selected OPC UA event type as a server-side `OfType(...)` filter
+- Lets users add optional event fields derived from the selected event type
+- Reads events only; acknowledge, confirm, and shelving actions are not part of this adapter yet
+
+## Preview behavior
+
+The preview step waits for a live event. If the server does not emit an alarm or condition during the preview window, the connection can still be valid and the preview will time out.
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/resources/org.apache.streampipes.connect.iiot.adapters.opcua-alarms/icon.png b/streampipes-extensions/streampipes-connectors-opcua/src/main/resources/org.apache.streampipes.connect.iiot.adapters.opcua-alarms/icon.png
new file mode 100644
index 0000000000..ab68d43485
Binary files /dev/null and b/streampipes-extensions/streampipes-connectors-opcua/src/main/resources/org.apache.streampipes.connect.iiot.adapters.opcua-alarms/icon.png differ
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/main/resources/org.apache.streampipes.connect.iiot.adapters.opcua-alarms/strings.en b/streampipes-extensions/streampipes-connectors-opcua/src/main/resources/org.apache.streampipes.connect.iiot.adapters.opcua-alarms/strings.en
new file mode 100644
index 0000000000..901d15b5e7
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/main/resources/org.apache.streampipes.connect.iiot.adapters.opcua-alarms/strings.en
@@ -0,0 +1,100 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+org.apache.streampipes.connect.iiot.adapters.opcua-alarms.title=OPC UA Events
+org.apache.streampipes.connect.iiot.adapters.opcua-alarms.description=Receives read-only OPC UA event notifications, including alarms and conditions
+
+OPC_HOST_OR_URL.title=OPC Server
+OPC_HOST_OR_URL.description=
+
+OPC_URL.title=URL
+OPC_URL.description=
+
+OPC_HOST.title=Host/Port
+OPC_HOST.description=
+
+OPC_SERVER_URL.title=URL
+OPC_SERVER_URL.description=Example: opc.tcp://test-server.com:4840
+
+OPC_SERVER_HOST.title=Host
+OPC_SERVER_HOST.description=Example: test-server.com, opc.tcp://test-server.com
+
+OPC_SERVER_PORT.title=Port
+OPC_SERVER_PORT.description=Example: 4840
+
+securityMode.title=Security Mode
+securityMode.description=The OPC-UA security mode
+
+securityPolicy.title=Security Policy
+securityPolicy.description=The OPC-UA security policy. Choose "None" if security mode is "None"
+
+userAuthentication.title=User Authentication
+userAuthentication.description=Choose an authentication method for the user
+
+anonymous.title=Anonymous
+anonymous.description=
+
+USERNAME_GROUP.title=Username & Password
+USERNAME_GROUP.description=
+
+USERNAME.title=Username
+USERNAME.description=
+
+PASSWORD.title=Password
+PASSWORD.description=
+
+x509Group.title=X.509 Certificate
+x509Group.description=
+
+x509PrivateKeyPem.title=Private Key PEM
+x509PrivateKeyPem.description=Private key in PEM format
+
+x509PublicKeyPem.title=Certificate PEM
+x509PublicKeyPem.description=Public key in PEM format
+
+alarm-source-scope.title=Where should events come from?
+alarm-source-scope.description=Choose whether to subscribe to the whole server or a specific area or machine.
+
+whole-server.title=Whole server
+whole-server.description=Receive events from the complete OPC UA server.
+
+specific-area-or-machine.title=Specific area or machine
+specific-area-or-machine.description=Receive events from one event-capable area or machine only.
+
+notifier-node.title=Area or machine
+notifier-node.description=Select the event-capable area or machine that should be monitored.
+
+event-type.title=Event type
+event-type.description=Select the OPC UA event type to subscribe to. The selected event type drives the server-side OfType filter and the available additional fields.
+
+additional-fields.title=Additional fields
+additional-fields.description=Select optional fields derived from the selected event type. After changing the event type, reload this field list. Some servers may stop delivering events if too many optional fields are selected.
+
+alarm-filter-mode.title=Which events should be included?
+alarm-filter-mode.description=Choose whether to receive all matching events or only events from sources whose names match a text filter.
+
+all-alarms.title=All events
+all-alarms.description=Receive all matching events from the selected source scope.
+
+source-name-contains.title=Only events whose source name contains text
+source-name-contains.description=Filter events by a substring match on the OPC UA SourceName field.
+
+source-name-filter.title=Source name contains
+source-name-filter.description=Example: Pump, Boiler_A, Line 3
+
+minimum-severity.title=Minimum severity
+minimum-severity.description=Only events with at least the selected severity are emitted.
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventFilterTest.java b/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventFilterTest.java
new file mode 100644
index 0000000000..b9f559b86e
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventFilterTest.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class OpcUaAlarmEventFilterTest {
+
+ @Test
+ void matchesAllEventsWhenNoSpecificFilterIsConfigured() {
+ var config = new OpcUaAlarmAdapterConfig();
+ var filter = new OpcUaAlarmEventFilter(config);
+
+ assertTrue(filter.matches(Map.of("sourceName", "Pump 1", "severity", 100)));
+ }
+
+ @Test
+ void filtersBySourceNameAndSeverity() {
+ var config = new OpcUaAlarmAdapterConfig();
+ config.setSourceNameFilter("pump");
+ config.setMinimumSeverity(500);
+
+ var filter = new OpcUaAlarmEventFilter(config);
+
+ assertTrue(filter.matches(Map.of(
+ "sourceName", "Pump 1",
+ "severity", 700
+ )));
+
+ assertFalse(filter.matches(Map.of(
+ "sourceName", "Boiler 1",
+ "severity", 700
+ )));
+
+ assertFalse(filter.matches(Map.of(
+ "sourceName", "Pump 1",
+ "severity", 300
+ )));
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventMapperTest.java b/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventMapperTest.java
new file mode 100644
index 0000000000..e9a6f8ce5d
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmEventMapperTest.java
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.eclipse.milo.opcua.sdk.core.typetree.ObjectType;
+import org.eclipse.milo.opcua.sdk.core.typetree.ObjectTypeTree;
+import org.eclipse.milo.opcua.stack.core.NodeIds;
+import org.eclipse.milo.opcua.stack.core.encoding.DefaultEncodingContext;
+import org.eclipse.milo.opcua.stack.core.types.builtin.ByteString;
+import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
+import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
+import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
+import org.eclipse.milo.opcua.stack.core.types.enumerated.FilterOperator;
+import org.eclipse.milo.opcua.stack.core.types.structured.ContentFilterElement;
+import org.eclipse.milo.opcua.stack.core.types.structured.LiteralOperand;
+import org.eclipse.milo.opcua.stack.core.util.Tree;
+import org.junit.jupiter.api.Test;
+
+import java.util.Base64;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class OpcUaAlarmEventMapperTest {
+
+ @Test
+ void derivesBaseEventFieldsForBaseEventType() {
+ var fields = OpcUaAlarmField.fieldsForType(NodeIds.BaseEventType, makeObjectTypeTree());
+
+ assertTrue(containsField(fields, "sourceName"));
+ assertTrue(containsField(fields, "severity"));
+ assertTrue(containsField(fields, "message"));
+ assertFalse(containsField(fields, "conditionName"));
+ assertFalse(containsField(fields, "acked"));
+ assertFalse(containsField(fields, "active"));
+ }
+
+ @Test
+ void derivesAdditionalFieldsForAlarmConditionSubtypes() {
+ var fields = OpcUaAlarmField.fieldsForType(NodeIds.AlarmConditionType, makeObjectTypeTree());
+
+ assertTrue(containsField(fields, "sourceName"));
+ assertTrue(containsField(fields, "conditionName"));
+ assertTrue(containsField(fields, "retain"));
+ assertTrue(containsField(fields, "acked"));
+ assertTrue(containsField(fields, "active"));
+ }
+
+ @Test
+ void selectsBaseFieldsPlusConfiguredAdditionalFieldsOnly() {
+ var fields = OpcUaAlarmField.selectedFieldsForType(
+ NodeIds.AlarmConditionType,
+ List.of("conditionName", "active"),
+ makeObjectTypeTree()
+ );
+
+ assertTrue(containsField(fields, "sourceName"));
+ assertTrue(containsField(fields, "message"));
+ assertTrue(containsField(fields, "conditionName"));
+ assertTrue(containsField(fields, "active"));
+ assertFalse(containsField(fields, "retain"));
+ assertFalse(containsField(fields, "acked"));
+ }
+
+ @Test
+ void derivesFieldNameAndDisplayNameFromBrowsePath() {
+ var activeField = OpcUaAlarmField.fromBrowsePath(
+ NodeIds.AlarmConditionType,
+ List.of(new QualifiedName(0, "ActiveState"), new QualifiedName(0, "Id"))
+ );
+ var limitField = OpcUaAlarmField.fromBrowsePath(
+ NodeIds.AlarmConditionType,
+ List.of(new QualifiedName(0, "HighLimit"))
+ );
+
+ assertEquals("active", activeField.outputField());
+ assertEquals("ActiveState / Id", activeField.displayName());
+ assertEquals("highLimit", limitField.outputField());
+ assertEquals("HighLimit", limitField.displayName());
+ }
+
+ @Test
+ void mapsEventValuesUsingDerivedFieldOrder() {
+ var mapper = new OpcUaAlarmEventMapper(
+ NodeIds.AlarmConditionType,
+ OpcUaAlarmField.selectedFieldsForType(
+ NodeIds.AlarmConditionType,
+ List.of("conditionName", "retain", "acked", "active"),
+ makeObjectTypeTree()
+ )
+ );
+ var now = DateTime.now();
+
+ var event = mapper.toEvent(new Variant[] {
+ new Variant("Pump 1"),
+ new Variant(700),
+ new Variant(new NodeId(2, "Pump_1")),
+ new Variant(LocalizedText.english("Pressure too low")),
+ new Variant(now),
+ new Variant(ByteString.of(new byte[] {1, 2, 3})),
+ new Variant(new NodeId(0, 2915)),
+ new Variant(false),
+ new Variant(true),
+ new Variant("LowPressure"),
+ new Variant(true)
+ });
+
+ assertEquals("Pump 1", event.get("sourceName"));
+ assertEquals(700, event.get("severity"));
+ assertEquals("ns=2;s=Pump_1", event.get("sourceNode"));
+ assertEquals("Pressure too low", event.get("message"));
+ assertEquals(now.getJavaTime(), event.get("time"));
+ assertEquals(Base64.getEncoder().encodeToString(new byte[] {1, 2, 3}), event.get("eventId"));
+ assertEquals("i=2915", event.get("eventType"));
+ assertEquals("LowPressure", event.get("conditionName"));
+ assertEquals(true, event.get("retain"));
+ assertEquals(false, event.get("acked"));
+ assertEquals(true, event.get("active"));
+ }
+
+ @Test
+ void addsServerSideWhereClauseForSelectedEventType() {
+ var mapper = new OpcUaAlarmEventMapper(
+ NodeIds.AlarmConditionType,
+ OpcUaAlarmField.fieldsForType(NodeIds.AlarmConditionType, makeObjectTypeTree())
+ );
+
+ var filter = mapper.makeEventFilter(DefaultEncodingContext.INSTANCE);
+
+ assertNotNull(filter.getWhereClause());
+ assertNotNull(filter.getWhereClause().getElements());
+ assertEquals(1, filter.getWhereClause().getElements().length);
+
+ ContentFilterElement element = filter.getWhereClause().getElements()[0];
+ assertEquals(FilterOperator.OfType, element.getFilterOperator());
+ assertNotNull(element.getFilterOperands());
+ assertEquals(1, element.getFilterOperands().length);
+
+ var operand = (LiteralOperand) element.getFilterOperands()[0].decode(DefaultEncodingContext.INSTANCE);
+ assertEquals(NodeIds.AlarmConditionType, operand.getValue().getValue());
+ }
+
+ private boolean containsField(List<OpcUaAlarmField> fields, String outputField) {
+ return fields.stream().anyMatch(field -> field.outputField().equals(outputField));
+ }
+
+ private ObjectTypeTree makeObjectTypeTree() {
+ Tree<ObjectType> baseEventType = new Tree<>(null, objectType(NodeIds.BaseEventType, "BaseEventType"));
+ Tree<ObjectType> conditionType = baseEventType.addChild(objectType(NodeIds.ConditionType, "ConditionType"));
+ Tree<ObjectType> acknowledgeableConditionType = conditionType.addChild(
+ objectType(NodeIds.AcknowledgeableConditionType, "AcknowledgeableConditionType")
+ );
+ acknowledgeableConditionType.addChild(objectType(NodeIds.AlarmConditionType, "AlarmConditionType"));
+
+ return new ObjectTypeTree(baseEventType);
+ }
+
+ private ObjectType objectType(NodeId nodeId, String browseName) {
+ return new ObjectType() {
+ @Override
+ public QualifiedName getBrowseName() {
+ return new QualifiedName(0, browseName);
+ }
+
+ @Override
+ public NodeId getNodeId() {
+ return nodeId;
+ }
+
+ @Override
+ public Boolean isAbstract() {
+ return false;
+ }
+ };
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmValueNormalizerTest.java b/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmValueNormalizerTest.java
new file mode 100644
index 0000000000..a0cbcb5474
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/alarms/OpcUaAlarmValueNormalizerTest.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.opcua.alarms;
+
+import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
+import org.eclipse.milo.opcua.stack.core.types.builtin.Matrix;
+import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.ULong;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class OpcUaAlarmValueNormalizerTest {
+
+ @Test
+ void normalizesUnsignedValuesInMatrix() {
+ var result = new OpcUaAlarmValueNormalizer().normalize(
+ new Matrix(new ULong[][] {{ULong.MAX}})
+ );
+
+ assertEquals(
+ Map.of(
+ "elements", List.of(-1L),
+ "dimensions", List.of(1, 1)
+ ),
+ result
+ );
+ }
+
+ @Test
+ void normalizesNestedDataValue() {
+ var result = new OpcUaAlarmValueNormalizer().normalize(
+ new DataValue(new org.eclipse.milo.opcua.stack.core.types.builtin.Variant(ULong.MAX))
+ );
+
+ assertEquals(-1L, ((Map<?, ?>) result).get("value"));
+ }
+}
diff --git a/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaUtilTest.java b/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaUtilTest.java
index 4d000118e0..3e04eaeef5 100644
--- a/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaUtilTest.java
+++ b/streampipes-extensions/streampipes-connectors-opcua/src/test/java/org/apache/streampipes/extensions/connectors/opcua/utils/OpcUaUtilTest.java
@@ -18,9 +18,15 @@
package org.apache.streampipes.extensions.connectors.opcua.utils;
+import org.apache.streampipes.commons.exceptions.SpConfigurationException;
+import org.apache.streampipes.extensions.connectors.opcua.config.OpcUaConfig;
+
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import java.net.ConnectException;
+import java.util.concurrent.ExecutionException;
+
public class OpcUaUtilTest {
private static final String SERVER_ADDRESS_WITH_OPC_PREFIX = "opc.tcp://example.com";
@@ -36,4 +42,41 @@ public class OpcUaUtilTest {
var result = OpcUaUtils.addOpcPrefixIfNotExists("example.com");
Assertions.assertEquals(SERVER_ADDRESS_WITH_OPC_PREFIX, result);
}
+
+ @Test
+ public void testExtractDescriptionFromNestedConnectionException() {
+ var exception = new ExecutionException(
+ new ConnectException("Connection refused: localhost/127.0.0.1:4840")
+ );
+
+ var result = ExceptionMessageExtractor.getDescription(exception);
+
+ Assertions.assertEquals("Connection refused: localhost/127.0.0.1:4840", result);
+ }
+
+ @Test
+ public void testCreateMeaningfulConnectionExceptionWithoutCauseChain() throws Exception {
+ var method = OpcUaUtils.class.getDeclaredMethod(
+ "makeConnectionException",
+ org.apache.streampipes.extensions.connectors.opcua.config.OpcUaConfig.class,
+ Throwable.class
+ );
+ method.setAccessible(true);
+
+ var config = new OpcUaConfig();
+ config.setOpcServerURL("opc.tcp://localhost:4840");
+
+ var result = (SpConfigurationException) method.invoke(
+ null,
+ config,
+ new ExecutionException(new ConnectException("Connection refused: localhost/127.0.0.1:4840"))
+ );
+
+ Assertions.assertEquals(
+ "Could not connect to the OPC UA server at opc.tcp://localhost:4840: "
+ + "Connection refused: localhost/127.0.0.1:4840",
+ result.getMessage()
+ );
+ Assertions.assertNull(result.getCause());
+ }
}
diff --git a/ui/src/app/core-ui/static-properties/static-runtime-resolvable-any-input/static-runtime-resolvable-any-input.component.html b/ui/src/app/core-ui/static-properties/static-runtime-resolvable-any-input/static-runtime-resolvable-any-input.component.html
index f31fb8761a..1da759b0a6 100644
--- a/ui/src/app/core-ui/static-properties/static-runtime-resolvable-any-input/static-runtime-resolvable-any-input.component.html
+++ b/ui/src/app/core-ui/static-properties/static-runtime-resolvable-any-input/static-runtime-resolvable-any-input.component.html
@@ -24,7 +24,7 @@
color="accent"
class="small-button"
(click)="selectAll(true)"
- [disabled]="!showOptions"
+ [disabled]="loading || !showOptions"
>
<span>{{ 'Select all' | translate }}</span>
</button>
@@ -33,7 +33,7 @@
mat-flat-button
class="mat-basic small-button"
(click)="selectAll(false)"
- [disabled]="!showOptions"
+ [disabled]="loading || !showOptions"
>
<span>{{ 'Select none' | translate }}</span>
</button>
@@ -43,7 +43,7 @@
color="accent"
class="small-button"
(click)="loadOptionsFromRestApi()"
- [disabled]="!showOptions"
+ [disabled]="loading"
>
<span>{{ 'Reload' | translate }}</span>
</button>
diff --git a/ui/src/app/core-ui/static-properties/static-runtime-resolvable-tree-input/static-tree-input-browse-nodes/static-tree-input-browse-nodes.component.html b/ui/src/app/core-ui/static-properties/static-runtime-resolvable-tree-input/static-tree-input-browse-nodes/static-tree-input-browse-nodes.component.html
index f7d1f839f2..6f001541e8 100644
--- a/ui/src/app/core-ui/static-properties/static-runtime-resolvable-tree-input/static-tree-input-browse-nodes/static-tree-input-browse-nodes.component.html
+++ b/ui/src/app/core-ui/static-properties/static-runtime-resolvable-tree-input/static-tree-input-browse-nodes/static-tree-input-browse-nodes.component.html
@@ -34,7 +34,7 @@
[attr.data-cy]="'tree-node-' + node.nodeName"
>
<i class="material-icons color-primary pr-5">wifi</i>
- @if (node.dataNode && !isNodeSelected(node)) {
+ @if (isSelectable(node) && !isNodeSelected(node)) {
<i
class="material-icons pr-5 icon-button"
(click)="addNode(node)"
@@ -44,7 +44,7 @@
>add_circle</i
>
}
- @if (node.dataNode && isNodeSelected(node)) {
+ @if (isSelectable(node) && isNodeSelected(node)) {
<i
class="material-icons pr-5 icon-button"
(click)="removeNode(node)"
@@ -108,7 +108,11 @@
@if (tree.isExpanded(node)) {
<i class="material-icons color-primary pr-5">folder_open</i>
}
- @if (tree.isExpanded(node) && hasDataChildren(node)) {
+ @if (
+ staticProperty.multiSelection &&
+ tree.isExpanded(node) &&
+ hasDataChildren(node)
+ ) {
<i
class="material-icons pr-5 icon-button"
[matTooltip]="'Add all direct children' | translate"
@@ -116,6 +120,25 @@
>add_circle</i
>
}
+ @if (isSelectable(node) && !isNodeSelected(node)) {
+ <i
+ class="material-icons pr-5 icon-button"
+ (click)="addNode(node)"
+ [attr.data-cy]="'select-' + node.nodeName"
+ [matTooltip]="'Add node' | translate"
+ matTooltipPosition="above"
+ >add_circle</i
+ >
+ }
+ @if (isSelectable(node) && isNodeSelected(node)) {
+ <i
+ class="material-icons pr-5 icon-button"
+ (click)="removeNode(node)"
+ [matTooltip]="'Remove node' | translate"
+ matTooltipPosition="above"
+ >remove_circle</i
+ >
+ }
@if (selectedNodeId !== node.internalNodeName) {
<i
class="material-icons pr-5 icon-button"
diff --git a/ui/src/app/core-ui/static-properties/static-runtime-resolvable-tree-input/static-tree-input-browse-nodes/static-tree-input-browse-nodes.component.ts b/ui/src/app/core-ui/static-properties/static-runtime-resolvable-tree-input/static-tree-input-browse-nodes/static-tree-input-browse-nodes.component.ts
index 54eec25a9b..cc59c6112a 100644
--- a/ui/src/app/core-ui/static-properties/static-runtime-resolvable-tree-input/static-tree-input-browse-nodes/static-tree-input-browse-nodes.component.ts
+++ b/ui/src/app/core-ui/static-properties/static-runtime-resolvable-tree-input/static-tree-input-browse-nodes/static-tree-input-browse-nodes.component.ts
@@ -123,16 +123,28 @@ export class StaticTreeInputBrowseNodesComponent implements OnInit {
}
addNode(node: TreeInputNode) {
- node.selected = true;
- this.staticProperty.selectedNodesInternalNames.push(
- node.internalNodeName,
- );
+ if (this.staticProperty.multiSelection) {
+ node.selected = true;
+ this.staticProperty.selectedNodesInternalNames.push(
+ node.internalNodeName,
+ );
+ } else {
+ this.clearSelectedFlags(this.dataSource.data);
+ node.selected = true;
+ this.staticProperty.selectedNodesInternalNames = [
+ node.internalNodeName,
+ ];
+ }
this.performValidationEmitter.emit();
}
addAllDirectChildren(node: TreeInputNode) {
+ if (!this.staticProperty.multiSelection) {
+ return;
+ }
+
node.children.forEach(child => {
- if (child.dataNode && !this.existsSelectedNode(child)) {
+ if (this.isSelectable(child) && !this.existsSelectedNode(child)) {
this.staticProperty.selectedNodesInternalNames.push(
child.internalNodeName,
);
@@ -173,7 +185,7 @@ export class StaticTreeInputBrowseNodesComponent implements OnInit {
hasDataChildren(node: TreeInputNode) {
return (
node.children.length > 0 &&
- node.children.find(c => c.dataNode) !== undefined
+ node.children.find(c => this.isSelectable(c)) !== undefined
);
}
@@ -184,4 +196,19 @@ export class StaticTreeInputBrowseNodesComponent implements OnInit {
) !== undefined
);
}
+
+ isSelectable(node: TreeInputNode) {
+ return (
+ node.dataNode ||
+ node.nodeMetadata?.Selectable === true ||
+ node.nodeMetadata?.selectable === true
+ );
+ }
+
+ private clearSelectedFlags(nodes: TreeInputNode[]) {
+ nodes.forEach(currentNode => {
+ currentNode.selected = false;
+ this.clearSelectedFlags(currentNode.children ?? []);
+ });
+ }
}