2015-06-16 7 views
2

Я не могу читать данные синхронно с сервера OPC. Мой код всегда дает эту ошибку:Прочитать синхронно с сервера opc

Object reference not set to an instance of an object. I created my object with new method but it doesn't work.

Я использую VS2010 и Interop.OPCAutomation.

Код:

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(); 
     } 
    } 
} 
+0

где ошибка, указывающая на? где код останавливается? – cramopy

+0

Код останавливается при вызове функции SyncRead: oGroup.SyncRead ((short) OPCAutomation.OPCDataSource.OPCDevice, 2, ref обрабатывает, выводит значения, выводит ошибки, выводит качества, выводит временные метки); – tebdilikiyafet

+1

Вы уверены, что вызываете 'set_opc', прежде чем вы вызываете' sync_read' ?? Мне кажется, что ни 'oServer', ни' oGroup' не были инициализированы. Вы должны добавить это в первую строку в 'button1_Click' или в' Form1_Load'! – cramopy

ответ

3

Вы должны вызвать

set_opc(); 

перед вызовом

synch_read(); 

если оба oGroup и oServer обыкновение быть инициализирован. В результате было выброшено исключение.

 Смежные вопросы

  • Нет связанных вопросов^_^