创建OPC UA客户端
private static OpcUaClient createClient() throws Exception {
Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "security");
Files.createDirectories(securityTempDir);
if (!Files.exists(securityTempDir)) {
throw new Exception("unable to create security dir: " + securityTempDir);
}
return OpcUaClient.create(endPointUrl,
endpoints ->
endpoints.stream()
.filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.None.getUri()))
.findFirst(),
configBuilder ->
configBuilder
.setApplicationName(LocalizedText.english("eclipse milo opc-ua client"))
.setApplicationUri("urn:eclipse:milo:examples:client")
.setIdentityProvider(new AnonymousProvider())
.setRequestTimeout(UInteger.valueOf(500))
.build()
);
}
遍历树形节点
private static void browseNode(OpcUaClient client, UaNode uaNode) throws Exception {
List<? extends UaNode> nodes;
if (uaNode == null) {
nodes = client.getAddressSpace().browseNodes(Identifiers.ObjectsFolder);
} else {
nodes = client.getAddressSpace().browseNodes(uaNode);
}
for (UaNode nd : nodes) {
if (Objects.requireNonNull(nd.getBrowseName().getName()).contains("_")) {
continue;
}
browseNode(client, nd);
}
}
读取节点数据
private static void readNode(OpcUaClient client) throws Exception {
int namespaceIndex = 2;
String identifier = "通道 1.设备 1.TT1";
NodeId nodeId = new NodeId(namespaceIndex, identifier);
DataValue value = client.readValue(0.0, TimestampsToReturn.Neither, nodeId).get();
identifier = String.valueOf(nodeId.getIdentifier());
System.out.println(identifier + ": " + value.getServerTime() + value.getValue().getValue());
}
直接存储节点数据到mysql
public static PreparedStatement ps;
public static Connection con;
private static void cunchuNode(OpcUaClient client) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/opc_test?seUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "root", "123456");
System.out.println("数据库连接成功");
int namespaceIndex = 2;
String identifier = "通道 1.设备 1.TT1";
NodeId nodeId = new NodeId(namespaceIndex, identifier);
DataValue value = client.readValue(0.0, TimestampsToReturn.Server, nodeId).get();
identifier = String.valueOf(nodeId.getIdentifier());
Date javaDate = value.getServerTime().getJavaDate();
System.out.println(identifier + ": " + stampToDate(String.valueOf(value.getServerTime().getJavaTime())) + " " + value.getValue().getValue());
System.out.println("time:" + javaDate);
String s1 = "insert into test_table1(tag1, tag2) values(?, ?)";
ps = con.prepareStatement(s1);
ps.setString(1, String.valueOf(value.getValue().getValue()));
ps.setString(2, String.valueOf(value.getValue(