//################ Sub procedure to initialize OPC Server ###### private void StopOPCClient() { // == // Description : 断开连接OPCServer,返回值False为断开失败,True为断开成功 // Created : 2009/01/19 // Author : zgh // Update : // Updater : // == //bool value = false; try { ObjOPCGroup.IsActive = false; //ObjOPCGroup.Remove(ObjOPCGroup.ServerHandle) ObjOPCGroups.RemoveAll(); ObjOPCItems = null; ObjOPCGroups = null; ObjOPCGroup = null; //ObjOPCGroup.AsyncReadComplete += ObjOPCGroup_AsyncReadComplete; ObjOPCServer.Disconnect(); ObjOPCServer = null; //colTagName = Nothing //value = true; //MessageLog("clsDeviceOPC.StopOPCClient(): Disconnected from OPC device \'" + DeviceName + "\'"); LOG.Info("断开OPC连接 \'" + SourceName + "\'"); } catch (Exception ex) { //value = false; //WarnLog(ex.StackTrace + "\r\n" + ex.Message); // MsgBox(ex.Message) LOG.Error(string.Format("OPCDataSource断开连接出错行:{0},", ex.Message)); } finally { System.GC.Collect(); //强制垃圾回收 } }
//################ Sub procedure to initialize OPC Server ###### private bool StartOPCClient() { int liCounter = 0; Array gpServerHandlers = null; Array gsErrors = null; string GroupName = SourceName; try { ObjOPCServer = new OPCServer(); //##### Initialize OPC Server ################################ ObjOPCServer.Connect(OPCServerName, ""); ObjOPCGroups = ObjOPCServer.OPCGroups; ObjOPCGroup = ObjOPCGroups.Add(GroupName); ObjOPCGroup.AsyncReadComplete += ObjOPCGroup_AsyncReadComplete; //Add OPCGroup ObjOPCGroup.UpdateRate = UpdateInterval; ObjOPCGroup.IsActive = false; ObjOPCGroup.IsSubscribed = ObjOPCGroup.IsActive; ObjOPCItems = ObjOPCGroup.OPCItems; //Create opc items Array_Address = Array.CreateInstance(typeof(string), NoOfItems + 1); Array_ClientHanlers = Array.CreateInstance(typeof(int), NoOfItems + 1); Array_ServerHandlers = Array.CreateInstance(typeof(int), NoOfItems + 1); //Build OPCItems Array for (liCounter = 1; liCounter <= NoOfItems; liCounter++) { Array_Address.SetValue(List_Address[liCounter - 1], liCounter); Array_ClientHanlers.SetValue(liCounter, liCounter); } ObjOPCItems.AddItems(NoOfItems, ref Array_Address, ref Array_ClientHanlers, out gpServerHandlers, out gsErrors); //Get the server handlers bool HasError = false; for (liCounter = 1; liCounter <= NoOfItems; liCounter++) { if ((int)gsErrors.GetValue(liCounter) == 0) { Array_ServerHandlers.SetValue((int)gpServerHandlers.GetValue(liCounter), liCounter); } else { LOG.Error("Tag \'" + List_Address[liCounter - 1] + "\' has problem连接失败错误"); HasError = true; } } if (!HasError) { LOG.Info(" 启动OPC组 \'" + SourceName + "\'"); } return(!HasError); } catch (Exception ex) { LOG.Error(string.Format("连接OPC出错:读取资源{0}{1}", GroupName, ex.Message)); return(false); } }