SpringBoot集成milo读写OPC UA
OPC UA客户端工具Softing OPC Client使用_推荐使用
maven引入依赖
<dependency>
<groupId>org.eclipse.milo</groupId>
<artifactId>sdk-client</artifactId>
<version>0.5.2</version>
</dependency>
读写的伪代码
{
"opcua": {
"appUri": "",
"appName": "",
"password": "opcua",
"username": "opcua",
"endPointUrl": "opc.tcp://192.168.3.5:49320",
"namespaceIndex": "2",
"requestTimeout": "5000"
}
}
private OpcUaDto dto;
private static OpcUaClient opcUaClient;
private OpcUaClient getOpcUaClient() {
if (opcUaClient == null) {
log.info("初始化OPC UA Client......");
try {
IdentityProvider identityProvider;
if (!StringUtil.isNull(dto.getUsername()) && !StringUtil.isNull(dto.getPassword())) {
identityProvider = new UsernameProvider(dto.getUsername(), dto.getPassword());
} else {
identityProvider = new AnonymousProvider();
}
opcUaClient = OpcUaClient.create(
dto.getEndPointUrl(),
endpoints ->
endpoints.stream()
.findFirst(),
configBuilder ->
configBuilder
.setIdentityProvider(identityProvider)
.setRequestTimeout(uint(dto.getRequestTimeout()))
.build()
);
log.info("初始化OPC UA Client......成功");
} catch (Exception e) {
log.error("初始化OPC UA Client失败, {}", e.getMessage());
return null;
}
}
if (!opcUaClient.getSession().isDone()) {
try {
// synchronous connect
opcUaClient.connect().get();
log.info("OPC UA Client连接connect成功");
} catch (Exception e) {
log.error("OPC UA Client连接connect失败, {}", e.getMessage());
opcUaClient.disconnect();
opcUaClient = null;
return null;
}
}
return opcUaClient;
}
public void read() {
String item = "tongdao.tag1.aaa";
NodeId nodeId = new NodeId(dto.getNamespaceIndex(),
Item);
DataValue value = opcUaClient.readValue(0.0, TimestampsToReturn.Both, nodeId).get();
if (value.getValue() == null) {
log.error("OPC UA字段读取为空, code={}", Item);
}
System.out.println(value.getValue().getValue());
}
public void write() {
//写入值
int v = 1;
String item = "tongdao.tag1.aaa";
NodeId nodeId = new NodeId(dto.getNamespaceIndex(), item);
Variant value = new Variant(v);
DataValue dataValue = new DataValue(value,null,null);
StatusCode statusCode = opcUaClient.writeValue(nodeId,dataValue).get();
System.out.println(statusCode.isGood());
}