OPC UA(Open Platform Communications Unified Architecture)是一种工业通信协议,用于在工厂自动化和工业物联网(IIoT)环境中实现设备之间的数据交换。OPC UA Milo 是一个开源的Java库,用于实现OPC UA客户端和服务器。
回调 onDataChangeNotification
:
这是OPC UA客户端中的一个回调方法,当监控项(Monitored Item)的数据发生变化时,服务器会调用这个方法通知客户端。监控项是客户端用来订阅服务器上特定数据点的机制。
监控项集合: 监控项集合是指客户端订阅的一组数据点。每个监控项都关联一个特定的节点ID,表示客户端感兴趣的数据点。
监控项可以根据不同的触发条件进行分类,例如:
问题: 在 onDataChangeNotification
回调中,监控项的集合似乎没有按预期更新。
原因:
解决方法:
onDataChangeNotification
方法中添加日志记录,以便跟踪哪些监控项触发了通知,以及通知的时间戳。以下是一个简单的Java示例,展示了如何使用OPC UA Milo订阅监控项并在 onDataChangeNotification
中处理数据变化:
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.UsernameIdentityProvider;
import org.eclipse.milo.opcua.stack.client.UaTcpStackClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.eclipse.milo.opcua.stack.core.types.structured.ReadResponse;
import org.eclipse.milo.opcua.stack.core.types.structured.WriteResponse;
public class OpcUaClientExample {
public static void main(String[] args) throws Exception {
// 创建客户端配置
OpcUaClientConfig config = OpcUaClientConfig.builder()
.setEndpoint(UaTcpStackClient.getEndpoint("opc.tcp://localhost:4840").get())
.setIdentityProvider(new UsernameIdentityProvider("username", "password"))
.build();
// 创建OPC UA客户端
try (OpcUaClient client = new OpcUaClient(config)) {
client.connect().get();
// 订阅监控项
NodeId monitoredItemId = new NodeId(2, "MyMonitoredItem");
client.getSubscriptionManager().createSubscription(1000.0).thenAccept(subscription -> {
subscription.createMonitoredItem(monitoredItemId, item -> {
item.setValueConsumer(value -> {
DataValue dataValue = value.getValue();
Variant variant = dataValue.getValue();
System.out.println("Data changed: " + variant.getValue());
});
}).get();
}).get();
// 保持客户端运行
Thread.currentThread().join();
}
}
}
在这个示例中,我们创建了一个OPC UA客户端,连接到服务器,并订阅了一个监控项。当监控项的数据发生变化时,valueConsumer
中的代码会被执行,打印出新的数据值。
请注意,这只是一个基本的示例,实际应用中可能需要更复杂的错误处理和配置选项。
领取专属 10元无门槛券
手把手带您无忧上云