问题
Here is the code to get the multiple values from OPC Server.
private void getData()
{
try
{
int count = 1;
opcServer.Connect("OPCTechs.SiemensNet30DA", "");
opcGroup = opcServer.OPCGroups.Add("MP");
opcGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(opcGroup_DataChange);
//Get First String
for (int i = 40; i <= 47; i++)
opcGroup.OPCItems.AddItem("D104.B" + i, count++);
//Get Second String
for (int i = 80; i <= 91; i++)
opcGroup.OPCItems.AddItem("D104.B" + i, count++);
opcGroup.OPCItems.DefaultIsActive = true;
opcGroup.UpdateRate = 1000;
opcGroup.IsSubscribed = opcGroup.IsActive;
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Alert");
}
}
private void opcGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
{
try
{
string temp = "";
int count = 1;
for (count = 1; count <= NumItems; count++)
{
if (Convert.ToInt32(ClientHandles.GetValue(count)) == 47)
temp += ItemValues.GetValue(count).ToString();
}
Textbox1.Text = temp.ToString();
temp = "";
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Alert");
}
}
As you can see in the code, I am trying to get the value if (Convert.ToInt32(ClientHandles.GetValue(count)) == 47)
of ClientHandle
47, but everytime I get some other values instead of this. When I printed all the values, I saw, the value at 47
was coming at random places. I don't understand why it is coming random ?
The value at place 47 should come on that place only. Is this the good way of getting multiple values from OPC server ?
回答1:
This is how OPC works. You specify a client handle for each item you are subscribing to. Whenever server has a new data for some items, you receive a notification with one or more items. Because it cannot be predicted which data change when, it also cannot be specified which items will be contained in the notification and it which order.
You need to go through all the items contained in the notification, and based on their client handles, decide what to do with each of them. The order may change each time, but that is not a problem: Let's say you are looking for a client handle 47. In the first notification, you will find it in ClientHandles at index 10; in the second notification, it may not be there at all; in the third notification, it may be at index 15. You just determine the position, and then you find the data for that at the same position in the other arrays: That is, for the first notification, at index 10 in arrays ItemValues, Qualities, and TimeStamps; and for the third notification, at index 15 in the same arrays.
来源:https://stackoverflow.com/questions/32710350/get-multiple-opc-values