opcUa连接方式java种基于Milo SDK的连接方式代码
时间: 2023-10-14 10:04:24 浏览: 187
OpcUa协议的Java实现
以下是基于Milo SDK的Java代码示例,连接到OPC UA服务器并读取节点值:
```java
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig;
import org.eclipse.milo.opcua.sdk.client.api.identity.UsernameProvider;
import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy;
import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;
import org.eclipse.milo.opcua.stack.core.types.structured.UserTokenPolicy;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class OpcUaClientExample {
public static void main(String[] args) throws Exception {
// 连接参数
String endpointUrl = "opc.tcp://localhost:12685/example";
String username = "user";
String password = "password";
// 创建OpcUaClientConfig
OpcUaClientConfig config = OpcUaClientConfig.builder()
.setEndpoint(getEndpoint(endpointUrl))
.setIdentityProvider(getIdentityProvider(username, password))
.setSecurityPolicy(SecurityPolicy.Basic256Sha256)
.setRequestTimeout(uint(5000))
.build();
// 创建OpcUaClient
OpcUaClient client = OpcUaClient.create(config);
// 连接服务器
CompletableFuture<Void> future = client.connect();
future.get();
// 读取节点值
String nodeToRead = "ns=2;s=MyVariable";
CompletableFuture<DataValue> readFuture = client.readValue(0, TimestampsToReturn.Both, nodeToRead);
DataValue value = readFuture.get();
System.out.println("Value: " + value.getValue().getValue());
// 断开连接
CompletableFuture<Void> closeFuture = client.disconnect();
closeFuture.get();
}
/**
* 获取EndpointDescription
*/
private static EndpointDescription getEndpoint(String endpointUrl) throws Exception {
List<EndpointDescription> endpoints = DiscoveryClient.getEndpoints(endpointUrl).get();
EndpointDescription endpoint = endpoints.stream()
.filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.Basic256Sha256.getUri()))
.findFirst().orElseThrow(() -> new Exception("no desired endpoints returned"));
return endpoint;
}
/**
* 获取IdentityProvider
*/
private static UsernameProvider getIdentityProvider(String username, String password) {
UserTokenPolicy userTokenPolicy = new UserTokenPolicy(null, null, null, null);
return new UsernameProvider(username, password, userTokenPolicy);
}
/**
* 将int转为UnsignedInteger
*/
private static UnsignedInteger uint(int value) {
return Unsigned.uint(value);
}
}
```
在这个示例中,我们先创建了一个OpcUaClientConfig对象,该对象包含了连接OPC UA服务器的参数,如服务器地址、用户名、密码、安全策略等。然后创建一个OpcUaClient对象,并使用connect()方法连接服务器。之后,我们使用readValue()方法读取指定节点的值,并使用disconnect()方法断开连接。
阅读全文