我每隔10秒钟从OPC服务器KepServer V5读取一个OPC项目到一个文件,但它每两秒读取两次!! (我不想每10秒阅读2次,但只有1次!)
这是我的代码。
OPCController类:
public void AddItems(string plcPath)
{
if (server.IsConnected || group.Active)
{
try
{
Opc.Da.Item[] items = new Opc.Da.Item[3];
items[0] = new Opc.Da.Item();
items[0].ItemName = “PLC1.Value1″;
items[1] = new Opc.Da.Item();
items[1].ItemName = “PLC1.Value2″;
items[2] = new Opc.Da.Item();
items[2].ItemName = “PLC1.Value3″;
group.AddItems(items);
}
catch (Exception e)
{
MessageBox.Show("Tags not read.");
}
}
}
public void ReadItems()
{
Opc.IRequest req;
group.Read(group.Items, 123, new Opc.Da.ReadCompleteEventHandler(ReadCompleteCallback), out req);
Console.ReadLine();
}
static void ReadCompleteCallback( object clientHandle, Opc.Da. ItemValueResult[] results)
{
Console.WriteLine( "Read complete" );
DateTime dataTimeNow = DateTime.Now;
foreach (Opc.Da.ItemValueResult readResult in results)
{
Console.WriteLine( "\Timestamp{0}\tValue:{1}" , (dataTimeNow.ToString("")), readResult.Value);
}
Console.WriteLine();
}
表单类:
private void startRead_btn_Click(object sender, EventArgs e)
{
int setTimerInterval = (int)this.numSetTimer.Value;
timer1.Enabled = true;
timer1.Interval = (setTimerInterval) * (1000);
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
startRead_btn.Enabled = false;
endRead_btn.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
opcController.ReadItems();
}
输出文件:
TimeStamp: 3/2/2015 3:10:15 PM Value: 12159
TimeStamp: 3/2/2015 3:10:15 PM Value: 12162
TimeStamp: 3/2/2015 3:10:25 PM Value: 12168
TimeStamp: 3/2/2015 3:10:25 PM Value: 12169
TimeStamp: 3/2/2015 3:10:35 PM Value: 12177
TimeStamp: 3/2/2015 3:10:35 PM Value: 12178
答案 0 :(得分:2)
您实际上已经两次添加了相同的组:
try
{
//...
items = group.AddItems(items); //you add them HERE
group.AddItems(items); //and HERE
}
通过将每个对象添加两次,它们将在一个刷新周期内从服务器读取两次。
删除任一行,它只能读一次。
答案 1 :(得分:0)
您只能获得2个项目的阅读结果! 您的控制台正在编写它读取的每个项目,它只读取2您确定您发布的代码是生成输出的代码吗?
将ReadResult.ItemName作为另一个字符串输出放在console.Writeline方法中 - 您将看到这种情况。
foreach (Opc.Da.ItemValueResult readResult in results)
{
Console.WriteLine( "\Timestamp{0}\tValue:{1}" , (dataTimeNow.ToString("")), readResult.Value);
}
另请注意:
try{ ...
group.AddItems(items);
}
catch (Exception e)
{
MessageBox.Show("Tags not read.");
}
您只在此处向组添加项目,没有READ方法。错误应该是别的。