using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Reflection;
using System.Runtime.CompilerServices;
using OpcRcw.Da;
using OpcRcw.Comn;
namespace OPC
{
public partial class Form1 : Form, IOPCDataCallback
{
public Form1()
{
InitializeComponent();
}
internal const string NODE_NAME = "home-7f692c6457";        //名字
//internal const string NODE_NAME = "6e228ad0c99645d";  // node name结点名
internal const string SERVER_NAME = "OPCServer.WinCC";  // server name服务器名
internal const string ITEM1_NAME = "TankLevel1";  // First item name第一个项的名字
internal const string ITEM2_NAME = "TankLevel2";  // First item name第一个项的名字
internal const string ITEM3_NAME = "temp1";  // First item name第一个项的名字
internal const string ITEM4_NAME = "temp2";  // First item name第一个项的名字
internal const string ITEM5_NAME = "press1";  // First item name第一个项的名字
internal const string GROUP_NAME = "Internal tags";    // Group name 组名
internal const int LOCALE_ID = 0;      // LOCALE ID FOR ENGLISH.
/* Global variables */
IOPCServer pIOPCServer;
IOPCAsyncIO2 pIOPCAsyncIO2 = null;      // instance pointer for asynchronous IO.
IOPCGroupStateMgt pIOPCGroupStateMgt = null;
typeof array
IConnectionPointContainer pIConnectionPointContainer = null;
IConnectionPoint pIConnectionPoint = null;
Object pobjGroup1 = null;
int pSvrGroupHandle = 0;        // server group handle for the added group
int nTransactionID = 0;
int[] ItemSvrHandleArray;
Int32 dwCookie = 0;
/* Global variables */
//IOPCServer pIOPCServer;  // OPC server interface pointer &  opc服务器接口指针
//Object pobjGroup1;    // Pointer to group object 指向组对象的指针
int nSvrGroupID;    // server group handle for the added group 为添加的组的服务器组的句柄
IOPCSyncIO pIOPCSyncIO;  // instance pointer for synchronous IO.  为同步输入输出事例化指针
//int[] nItemSvrID;    // array for server handles for  服务器句柄数组
private Guid iidRequiredInterface = Guid.Empty;
private void button2_Click(object sender, EventArgs e)//连接服务器
{
// Local variables局部变量
Type  svrComponenttyp ;  //服务器类型
//Type  svrNode;     //服务器的名字
OPCITEMDEF[] ItemDefArray;
// Initialise Group properties初始化组属性
int bActive = 0;
int dwRequestedUpdateRate = 0;
int hClientGroup = 0;
//int dwLCID = LOCALE_ID;
int pRevUpdateRate;
floa
t deadband = 0;
// Access unmanaged COM memory
GCHandle hDeadband;
IntPtr pTimeBias = IntPtr.Zero;
hDeadband = GCHandle.Alloc(deadband,GCHandleType.Normal);
//commonInterface.GetLocaleID(out LOCALE_ID);
/
/ 1. Connect to the local server.连接到服务器
// Get the Type from the progID and create instance of the OPC Server COM 得到服务器名并事例化com 组件
// component
//GUID Guid = new Guid("{75D00BBB-DDA5-11D1-B944-9E614D000000}");
iidRequiredInterface = typeof(IOPCItemMgt ).GUID; //返回一个用于标识表达式的数据类型的字符串
//iidRequiredInterface = new Guid("{63D5F432-CFE4-11d1-B2C8-0060083BA1FB}");//typeof(IOPCItemMgt).GUID;
svrComponenttyp = System.Type.GetTypeFromProgID(SERVER_NAME);
try
{
pIOPCServer =(IOPCServer)System.Activator.CreateInstance(svrComponenttyp);//创建服务器对象
try
{
/* 2. Add a new group 添加一个新组
Add a group object and querry for interface IOPCItemMgt
Parameter as following:
[in] not active, so no OnDataChange callback //不活动,不引发数据改变事件
[in] Request this Update Rate from Server  服务器的刷新频率
[in] Client Handle, not necessary in this sample   客户端的句柄,在本例子中不必要
[in] No time interval to system UTC time   无系统时间的时间间隔 
[in] No Deadband, so all data changes are reported   无死区,所以所有数据的改变被报告
[in] Server uses english language to for text values 服务器用英文的文本值
[out] Server handle to identify this group in later calls 服务器的句柄为了确保该组之后被访问
[out] The answer from Server to the requested Update Rate 服务器的应答刷新率
[in] requested interface type of the group object  组对象的接口类型
[out] pointer to the requested interface   指向接口的指针
*/
pIOPCServer.AddGroup(GROUP_NAME,
bActive,
dwRequestedUpdateRate,
hClientGroup,
pTimeBias,
(IntPtr)hDeadband,
LOCALE_ID,
out nSvrGroupID,
out pRevUpdateRate,
ref iidRequiredInterface,
out pobjGroup1);
// Initialize all IO interface pointers. 初始化所有输入输出接口指针 
InitReqIOInterfaces();
// Get the IOPOCSyncIO interface pointer from the group pointer.
//从组指针得到输入输出接口的指针
// pIOPCSyncIO also needs to be released when not in use.不用时要释放
pIOPCSyncIO =(IOPCSyncIO)pobjGroup1;
/
* 3. Add items to the group 添加项到组*/
// This example shows adding of only one item in the group本例子只添加一个项到该组
ItemDef
Array = new OPCITEMDEF[5];
ItemDefArray[0].szAccessPath  = "";    // Accesspath not needed for this sample本例不需要路径
ItemDefArray[0].szItemID  = ITEM1_NAME;  // ItemID, see above
ItemDefArray[0].bActive    = 1;    // item is active项是活动的
ItemDefArray[0].hClient    = 1;    // client handle 客户端句柄
ItemDefArray[0].dwBlobSize  = 0;              // blob size
ItemDefArray[0].pBlob    = IntPtr.Zero;    // pointer to blob
ItemDefArray[0].vtRequestedDataType = 2;    // return values in native (cannonical) datatype
ItemDefArray[1].szAccessPath = "";    // Accesspath not needed for this sample本例不需要路径
ItemDefArray[1].szItemID = ITEM2_NAME;  // ItemID, see above
ItemDefArray[1].bActive = 1;    // item is active项是活动的
ItemDefArray[1].hClient = 2;    // client handle 客户端句柄
ItemDefArray[1].dwBlobSize = 0;              // blob size
ItemDefArray[1].pBlob = IntPtr.Zero;    // pointer to blob
ItemDefArray[1].vtRequestedDataType = 2;    // return values in native (cannonical) datatype
ItemDefArray[2].szAccessPath = "";    // Accesspath not needed for this sample本例不需要路径
ItemDefArray[2].szItemID = ITEM3_NAME;  // ItemID, see above
ItemDefArray[2].bActive = 1;    // item is active项是活动的
ItemDefArray[2].hClient = 3;    // client handle 客户端句柄
ItemDefArray[2].dwBlobSize = 0;              // blob size
ItemDefArray[2].pBlob = IntPtr.Zero;    // pointer to blob
ItemDefArray[2].vtRequestedDataType = 2;    // return values in native (cannonical) datatype
ItemDefArray[3].szAccessPath = "";    // Accesspath not needed for this sample本例不需要路径
ItemDefArray[3].szItemID = ITEM4_NAME;  // ItemID, see above
ItemDefArray[3].bActive = 1;    // item is active项是活动的
ItemDefArray[3].hClient = 4;    // client handle 客户端句柄
ItemDefArray[3].dwBlobSize = 0;              // blob size
ItemDefArray[3].pBlob = IntPtr.Zero;    // pointer to blob
ItemDefArray[3].vtRequestedDataType = 2;    // return values in native (cannonical) datatype
ItemDefArray[4].szAccessPath = "";    // Accesspath not needed for this sample本例不需要路径
ItemDefArray[4].szItemID = ITEM5_NAME;  // ItemID, see above
ItemDefArray[4].bActive = 1;    // item is active项是活动的
ItemDefArray[4].hClient = 5;    // client handle 客户端句柄
ItemDefArray[4].dwBlobSize =
0;              // blob size
ItemDefArray[4].pBlob = IntPtr.Zero;    // pointer to blob
ItemDefArray[4].vtRequestedDataType = 2;    // return values in native (cannonical) datatype
// initialize output parameters.初始化输出参数
IntPtr pResults = IntPtr.Zero;
IntPtr pErrors  = IntPtr.Zero;
try 
{
// Add items to group添加项到组
((IOPCItemMgt)pobjGroup1).AddItems(5,ItemDefArray,out pResults,out pErrors);
// Unmarshal to get the server handles out fom the m_pItemResult 得到服务器的句柄
// after checking the errors
int[] errors = new int[5];
IntPtr pos = pResults;
ItemSvrHandleArray = new int[5];
Marshal.Copy(pErrors, errors, 0,5);
if (errors[0] == 0)
{
OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
ItemSvrHandleArray[0] = result.hServer;
}
else
{
String strError;
pIOPCServer.GetErrorString(errors[0], LOCALE_ID, out strError);
MessageBox.Show(strError, "Result - Adding Item 0", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (errors[1] == 0)
{
pos = new IntPtr(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
ItemSvrHandleArray[1] = result.hServer;
}
else
{
String strError;
pIOPCServer.GetErrorString(errors[1], LOCALE_ID, out strError);
MessageBox.Show(strError, "Result - Adding Item 1", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (errors[2] == 0)
{
pos = new IntPtr(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
ItemSvrHandleArray[2] = result.hServer;
}
else
{
String strError;
pIOPCServer.GetErrorString(errors[2], LOCALE_ID, out strError);
MessageBox.Show(strError, "Result - Adding Item 1", MessageBoxButto
ns.OK, MessageBoxIcon.Error);
}
if (errors[3] == 0)
{
pos = new IntPtr(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
ItemSvrHandleArray[3] = result.hServer;
}
else
{
String strError;
pIOPCServer.GetErrorString(errors[3], LOCALE_ID, out strError);
MessageBox.Show(strError, "Result - Adding Item 1", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (errors[4] == 0)
{
pos = new IntPtr(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
ItemSvrHandleArray[4] = result.hServer;
}
else
{
String strError;
pIOPCServer.GetErrorString(errors[4], LOCALE_ID, out strError);
MessageBox.Show(strError, "Result - Adding Item 1", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (System.Exception error) // catch for error in adding items.
{
MessageBox.Show(error.Message,"Result - Adding Items",MessageBoxButtons.OK,MessageBoxIcon.Error);   
}
finally
{
// Free the unmanaged memory
if(pResults != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pResults);
pResults = IntPtr.Zero;
}
if(pErrors != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pErrors);
pErrors = IntPtr.Zero; 
}
}
}
catch (System.ArgumentException error) // catch for error in creation group
{
MessageBox.Show(String.Format("Error while creating group object:-{0}" ,
error.ParamName),"Result-Add Group",MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
if (hDeadband.IsAllocated) hDeadband.Free();
}
}
catch (System.Exception error) // catch for error in creating server
{
MessageBox.Show(String.Format("Error while creating server object:-{0}" ,error.Message),
"Result - Create Server Instance",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
MessageBox.Show("连接已建立!");
button1.Enabled = true;
button2.Enabled = false ;
button3.Enabled = true ;
button4.Enabled = true ;
chkGroupActive.Enabled = true;
}
private void button1_Click(o
bject sender, EventArgs e)//写
{
IntPtr pErrors = IntPtr.Zero;
int nCancelid;
object[] values = new object[5];
values[0] = textbox1.Text;
values[1] = textBox2.Text;
values[2] = textBox3.Text;
values[3] = textBox4.Text;
values[4] = textBox5.Text;
try
{
//pIOPCSyncIO.Write(5, ItemSvrHandleArray, values, out pErrors);
pIOPCAsyncIO2.Write(5, ItemSvrHandleArray, values, nTransactionID + 1, out nCancelid, out pErrors);
int[] errors = new int[5];
Marshal.Copy(pErrors, errors, 0, 5);
String pstrError;
pIOPCServer.GetErrorString(errors[0], LOCALE_ID, out pstrError);
//strSyncWriteStatus.Text = pstrError;
}
catch (System.Exception error)
{
MessageBox.Show(error.Message, "Result - WriteItem", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (pErrors != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pErrors);
pErrors = IntPtr.Zero;
}
}
}
private void button4_Click(object sender, EventArgs e)//读
{
IntPtr pItemValues = IntPtr.Zero;
IntPtr pErrors = IntPtr.Zero;
try
{
// Sync read from device
pIOPCSyncIO.Read(OPCDATASOURCE.OPC_DS_DEVICE, 5, ItemSvrHandleArray, out pItemValues, out pErrors);
// Unmarshal the returned memory to get the item state out fom the ppItemValues
// after checking errors
int[] errors = new int[5];
IntPtr posr = pItemValues;
Marshal.Copy(pErrors, errors, 0, 5);
if (errors[0] == 0)
{
OPCITEMSTATE pItemState = (OPCITEMSTATE)Marshal.PtrToStructure(posr, typeof(OPCITEMSTATE));
// update the UI
textBox12.Text = String.Format("{0}", pItemState.vDataValue);
// quality
//strSncQuality.Text = GetQuality(pItemState.wQuality);
// Time stamp - Date and time
//DateTime dt = ToDateTime(pItemState.ftTimeStamp);
//strSycTimeStamp.Text = dt.ToString();
}
else
{
String pstrError;
pIOPCServer.GetErrorString(errors[0], LOCALE_ID, out pstrError);
MessageBox.Show(pstrError, "Result - Read Items", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (errors[1] == 0)
{
posr = new IntPtr(posr.ToInt32() + Marsh

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。