如何通過(guò)Java Milo實(shí)現(xiàn)實(shí)時(shí)通信功能

小樊
102
2024-08-09 20:03:38

在Java中使用Milo可以實(shí)現(xiàn)實(shí)時(shí)通信功能,以下是一個(gè)簡(jiǎn)單的示例:

  1. 首先引入Milo的依賴,可以在pom.xml文件中添加以下依賴:
<dependency>
    <groupId>org.eclipse.milo</groupId>
    <artifactId>milo-client-opcua-stack</artifactId>
    <version>0.6.6</version>
</dependency>
  1. 創(chuàng)建一個(gè)OpcUaClient實(shí)例并連接到OPC UA服務(wù)器:
String endpointUrl = "opc.tcp://localhost:4840";
OpcUaClient client = new OpcUaClient(endpointUrl);
client.connect().get();
  1. 通過(guò)OpcUaClient實(shí)例可以發(fā)送和接收數(shù)據(jù),例如讀取節(jié)點(diǎn)值:
NodeId nodeId = new NodeId(2, "HelloWorld/ScalarTypes/Int32");
DataValue value = client.readValue(0, TimestampsToReturn.Both, nodeId).get();
System.out.println("Value: " + value.getValue().getValue().toString());
  1. 可以在需要的時(shí)候訂閱節(jié)點(diǎn)的值變化:
MonitoredItemCreateRequest request = new MonitoredItemCreateRequest(
        new ReadValueId(nodeId, AttributeId.Value.uid(), null, QualifiedName.NULL_VALUE),
        MonitoringMode.Reporting,
        new MonitoringParameters(
                UInt32.valueOf(1),
                Double.valueOf(0.0),
                null,
                UInt32.valueOf(10),
                true
        )
);

client.getSubscriptionManager().createSubscription(1000.0).get();
client.getSubscriptionManager().createMonitoredItems(
        TimestampsToReturn.Both,
        Collections.singletonList(request),
        (item, id) -> System.out.println("Value changed: " + item.getValue().getValue().getValue())
).get();

通過(guò)以上步驟,您可以實(shí)現(xiàn)基于Java Milo的實(shí)時(shí)通信功能。更多關(guān)于Java Milo的文檔可以在官方網(wǎng)站上找到:https://github.com/eclipse/milo

0