接上文,继续写OPC的应用..

     拿到从codeproject上下载的代码后,就开始迫不及待的研究代码的使用方法..在代码中,发现有很多示例程序,在里面找到了C#的源码..仔细的研究修改之后,程序可以完美运行,为此兴奋了很久..

    说了这么多的废话,开始说说具体的代码应用...

    最先开始的,当然是连接OPC服务器...在连接服务器之前,添加命名空间的引用,然后定义几个变量...

using OPC.Common; using OPC.Data.Interface; using OPC.Data;

 
//OPC服务器所在的IP地址
const string serverProgID = "PCAUTO.OPCServer";//OPC服务器名称
string[] items;
public static OpcServer theSrv;//服务器
 public static OpcGroup theGrp;//服务器组
OPCItemResult[] rItem;//服务器返回项
private OPCItemDef[] itemDefs;//客户端项属性
private int[] handlesSrv;//服务器端句柄
 
 
bool Connect() { theSrv = new OpcServer(); //theSrv.Connect(serverProgID, "192.168.157.130");//这个是重载的方法,codeproject上的代码没有这个方法,这个方法需要自己来添加,或者使用前面提供的dll也可以 theSrv.Connect(serverProgID);//如果服务器在本机,直接连接 Thread.Sleep(500);//等待服务器响应 dtPoint = dl.SelPoint(serverAdress);//获取数据库中保存的OPC项的表 Count = dtPoint.Rows.Count; theGrp = theSrv.AddGroup("OPCServer", false, 900); itemDefs = new OPCItemDef[dtPoint.Rows.Count]; for (int i = 0; i < Count; i++)// 从OPC项表中,读取数据,并赋给 itemDefs数组 { itemDefs[i] = new OPCItemDef(dtPoint.Rows[i]["PointName"].ToString() + ".PV", true, Convert.ToInt32(dtPoint.Rows[i]["ClientHandel"]), VarEnum.VT_EMPTY); } theGrp.AddItems(itemDefs, out rItem);//添加OPC项 if (rItem == null) return false; bool res = true; for (int i = 0; i < Count; i++) { if (HRESULTS.Failed(rItem[i].Error)) { res = false; //如果符合,则修改 break; } } if (!res) { this.lblErr.Text = "OPC服务器:添加组错误!"; theGrp.Remove(true); theSrv.Disconnect(); return false; } handlesSrv = new int[Count]; for (int i = 0; i < Count; i++) { handlesSrv[i] = rItem[i].HandleServer; dtPoint.Rows[i]["ServerHandel"] = (object)handlesSrv[i];// 服务器句柄保存在项表中,供以后使用. } theGrp.SetEnable(true); theGrp.Active = true; theGrp.DataChanged += new DataChangeEventHandler(theGrp_DataChanged); theGrp.ReadCompleted += new ReadCompleteEventHandler(theGrp_ReadCompleted); theGrp.WriteCompleted += new WriteCompleteEventHandler(theGrp_WriteCompleted); return true; }

 

可以通过修改OPC_Data_Srv.cs中的方法来访问远程计算机上的OPC Server,添加如下代码:

string computerName) { Disconnect(); Type typeofOPCserver = Type.GetTypeFromProgID(progidOPCServer, computerName); if (typeofOPCserver == null) Marshal.ThrowExceptionForHR(HRESULTS.OPC_E_NOTFOUND); OPCserverObj = Activator.CreateInstance(typeofOPCserver); ifServer = (IOPCServer)OPCserverObj; if (ifServer == null) Marshal.ThrowExceptionForHR(HRESULTS.CONNECT_E_NOCONNECTION); // connect all interfaces ifCommon = (IOPCCommon)OPCserverObj; ifBrowse = (IOPCBrowseServerAddressSpace)ifServer; ifItmProps = (IOPCItemProperties)ifServer; cpointcontainer = (UCOMIConnectionPointContainer)OPCserverObj; AdviseIOPCShutdown(); }

至此,OPC Server已经建立连接,接下来的就需要和OPC Server进行数据交换...

相关文章:

  • 2022-12-23
  • 2022-01-12
  • 2022-12-23
  • 2022-12-23
  • 2022-03-04
  • 2022-12-23
猜你喜欢
  • 2022-01-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-23
  • 2022-02-06
  • 2021-10-29
相关资源
相似解决方案