All Downloads are FREE. Search and download functionalities are using the official Maven repository.

info.unterrainer.commons.opcuabrowser.parts.NodeReader Maven / Gradle / Ivy

The newest version!
package info.unterrainer.commons.opcuabrowser.parts;

import java.util.concurrent.ExecutionException;

import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.BuiltinDataType;
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.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.ExpandedNodeId;
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.TimestampsToReturn;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import info.unterrainer.commons.opcuabrowser.dtos.BrowseNode;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NodeReader {

	private final OpcUaClient client;
	private final LoadingCache cache;

	public NodeReader(final OpcUaClient client) {
		super();
		this.client = client;
		cache = CacheBuilder.newBuilder().maximumSize(1000).build(new CacheLoader<>() {
			public BrowseNode load(final String id) {
				return loadNode(id);
			}
		});
	}

	public BrowseNode get(final String nodeId) {
		try {
			return cache.get(nodeId);
		} catch (ExecutionException e) {
			log.warn("Getting nodeId=[{}] failed: [{}] cause: [{}]", nodeId, e.getMessage(), e.getCause().getMessage());
		}
		return null;
	}

	private BrowseNode loadNode(final String nodeId) {
		BrowseNode n = null;
		try {
			n = BrowseNode.getFrom(client.getAddressSpace().getNode(NodeId.parse(nodeId)));
		} catch (InterruptedException | ExecutionException | UaRuntimeException | UaException e) {
			log.warn("Getting nodeId=[{}] failed: [{}] cause: [{}]", nodeId, e.getMessage(), e.getCause().getMessage());
		}
		return n;
	}

	public String getTypeOf(final String nodeId) throws InterruptedException, ExecutionException {
		NodeId nId = NodeId.parseOrNull(nodeId);
		if (nId == null)
			return null;

		DataValue dataValue = client.readValue(0, TimestampsToReturn.Both, nId).get();
		Variant variant = dataValue.getValue();
		Object value = variant.getValue();
		if (value == null)
			return null;

		ExpandedNodeId dataType = dataValue.getValue().getDataType().get();
		Class javaType = BuiltinDataType.getBackingClass(dataType);
		return javaType.getSimpleName();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy