我正在使用OpcNetApi连接到OPC服务器。我可以毫无问题地连接和读取数据,但是,当数据更改时我需要再次阅读才能看到更改,虽然我已经向DataChanged事件添加了一个处理程序,但我没有收到任何更改事件的通知我的订阅。
为了让它发挥作用,我还需要做些什么吗?
Opc.URL url = new Opc.URL("opcda://localhost/ArchestrA.FSGateway.3");
OpcCom.Factory factory = new OpcCom.Factory();
using (Opc.Da.Server server = new Opc.Da.Server(factory, url)) {
server.Connect();
Console.WriteLine("Server LocalID = {0}", server.Locale);
Opc.Da.SubscriptionState state = new Opc.Da.SubscriptionState();
using (Opc.Da.Subscription group = server.CreateSubscription(new Opc.Da.SubscriptionState {
Name = "GROUP1",
UpdateRate = 40,
Deadband = 0,
Active = true
}) as Opc.Da.Subscription) {
// Create the itesm
Opc.Da.Item[] items = new Opc.Da.Item[2];
items[0] = new Opc.Da.Item { ItemName = "value1", Active = true, ClientHandle = "6S1", ActiveSpecified = true };
items[1] = new Opc.Da.Item { ItemName = "value2", Active = true, ClientHandle = "6S2", ActiveSpecified = true };
Opc.Da.ItemResult[] results = group.AddItems(items);
for (int i = 0; i < results.Length; i++) {
items[i].ServerHandle = results[i].ServerHandle;
}
group.DataChanged += new Opc.Da.DataChangedEventHandler(group_DataChanged);
group.State.Active = true;
Opc.IRequest request;
group.Read(group.Items, 1234, new Opc.Da.ReadCompleteEventHandler(group_ReadComplete), out request);
// Stop when 'q' is pressed
ConsoleKeyInfo key = new ConsoleKeyInfo();
while (key.Key != ConsoleKey.Q) {
key = Console.ReadKey();
if (key.Key == ConsoleKey.R) {
group.Read(group.Items, 1234, new Opc.Da.ReadCompleteEventHandler(group_ReadComplete), out request);
}
}
group.DataChanged -= group_DataChanged;
group.RemoveItems(items);
}
server.Disconnect();
}
static void group_DataChanged(object subscriptionHandle, object requestHandle, Opc.Da.ItemValueResult[] values) {
Console.WriteLine("Data Changed");
foreach (Opc.Da.ItemValueResult readResult in values) {
Console.WriteLine("\t{0}\tvalue:{1}", readResult.ItemName, readResult.Value);
}
Console.WriteLine();
}
谢谢,
JFercan
答案 0 :(得分:1)
您编写的所有内容似乎都不错,但是您可以向我们展示在订阅的至少一个数据更新时调用的 group_DataChanged 方法。