问题
I can not read items synchronously from OPC
server. My code always gives this error:
Object reference not set to an instance of an object. I created my object with new method but it doesn't work.
I'm using VS2010
and Interop.OPCAutomation
.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OPCAutomation;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OPCServer oServer;
OPCGroup oGroup;
Array handles = new Array[2];
public int temp1;
public int temp2;
public Form1()
{
InitializeComponent();
}
public void set_opc()
{
//add server - reference the kepserver that should already be setup
oServer = new OPCServer();
oServer.Connect("Kepware.KEPServerEX.V5", null);
oServer.OPCGroups.DefaultGroupIsActive = true;
oServer.OPCGroups.DefaultGroupDeadband = 0f; //the percentage change required before a change is reported, used to filter noise
oServer.OPCGroups.DefaultGroupUpdateRate = 10; //the rate is ms before item is updated
//set up group - this is an arbitrary container to place OPC items
oGroup = oServer.OPCGroups.Add("g1");
oGroup.IsSubscribed = false; //dont need to be subscribed to data change events
oGroup.OPCItems.DefaultIsActive = false; //the item does not need to be active, it will only be refreshed with the latest value after we synch read
//add group items - items can capture the values of registers from the device, the item is setup within the kepserver
int[] h = new int[3];
//index starts at 1
h[1] = oGroup.OPCItems.AddItem("Channel1.s7-300.sayi0", 1).ServerHandle; //the handle is a server generated value that we use to reference the item for further operations
h[2] = oGroup.OPCItems.AddItem("Channel1.s7-300.sayi1", 2).ServerHandle;
handles = (Array)h;
}
public void synch_read() //reads device
{
System.Array values; //opc server will store the values in this array
System.Array errors; //opc server will store any errors in this array
object qualities = new object(); //opc server will store the quality of the item
object timestamps = new object(); //store the timestamp of the read
//read directly from device
oGroup.SyncRead((short)OPCAutomation.OPCDataSource.OPCDevice, 2, ref handles, out values, out errors, out qualities, out timestamps);
temp1 = (int)values.GetValue(1);
temp2 = (int)values.GetValue(2);
}
private void button1_Click(object sender, EventArgs e)
{
synch_read();
textBox1.Text = temp1.ToString();
textBox2.Text = temp2.ToString();
}
}
}
回答1:
You have to call
set_opc();
before you call
synch_read();
unless both oGroup
and oServer
wont be initialized. As a result a exception was thrown.
来源:https://stackoverflow.com/questions/30866803/read-synchronously-from-opc-server