SpringBoot集成Milo库实现OPC UA客户端:连接、遍历节点、读取、写入、订阅与批量订阅
import org.eclipse.milo.opcua.sdk.client.*;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription;
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.enumerated.ServerState;
import org.eclipse.milo.opcua.stack.core.types.structures.EndpointDescription;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class OpcUaClientExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建OPC UA客户端配置
OpcUaClientConfig clientConfig = OpcUaClientConfig.builder()
.setApplicationName(LocalizedText.english("OpcUaClient"))
.setApplicationUri("http://example.com/OpcUaClient")
.setProductUri("http://example.com/OpcUaClient")
.build();
// 连接到OPC UA服务器
try (OpcUaClient client = OpcUaClient.create("opc.tcp://example.com:4840", clientConfig)) {
// 连接
client.connect().get();
// 浏览服务器端点并选择一个端点
EndpointDescription endpoint = client.getEndpoints()
.orElseThrow(() -> new IllegalStateException("No endpoints found"))
.stream()
.findFirst()
.orElseThrow(() -> new IllegalStateException("No endpoints found"));
// 状态变更事件
client.addStateListener((oldState, newState) -> {
System.out.println("State changed from " + oldState + " to " + newState);
if (newState == ServerState.Connected) {
System.out.println("Connected to server!");
}
});
// 浏览服务器信息
client.getServerDiagnosticInfos()
.ifPresent(diagnosticInfos -> diagnosticInfos.forEach(diagnosticInfo -> {
System.out.println("Server Diagnostic Info: " + diagnosticInfo);
}));
// 创建订阅
UaSubscription subscription = client.getSubscriptionManager().createSubscription().get();
// 读取节点属性
CompletableFuture<DataValue> future = client.readValue(0.0, NodeId.parse("ns=2;s=1"));
DataValue value
评论已关闭