/// <summary> /// This removes the OPC group items, opc group and disconnects and nulls the OPC server connection. /// </summary> public void Disconnect() { try { if (_opcserver == null) { return; } if (!IsConnected()) { return; } agent.StoreEvent(DateTime.Now.ToString("s"), device, "power", "OFF", null, null, null, null, null, null); if (opcgroup != null) { opcgroup.RemoveItems(handlesSrv, out aE); opcgroup.Remove(false); } _opcserver.Disconnect(); opcgroup = null; _opcserver = null; } catch (Exception e) { LogMessage("OPC Disconnect Error: " + e.Message, Logger.ERROR); _opcserver = null; } }
/// <summary> /// This removes the OPC group iutem, opc group and disconnects and nulls the OPC server connection. /// </summary> public void Disconnect() { try { if (_opcserver == null) { return; } if (!IsConnected()) { return; } if (opcgroup != null) { opcgroup.RemoveItems(handlesSrv, out aE); opcgroup.Remove(false); } _opcserver.Disconnect(); opcgroup = null; _opcserver = null; } catch (Exception e) { LogMessage("OPC Disconnect Error: " + e.Message, LogLevel.ERROR); _opcserver = null; } }
/// <summary> /// 与OPC服务断开 /// </summary> public void DisconnectRemoteServer() { if (Thread_Reconn != null) { Thread_Reconn.Abort(); Thread_Reconn = null; } if (!OpcConnected) { return; } if (OpcServer != null) { OpcServer.OPCGroups.RemoveAll(); OpcServer.Disconnect(); OpcServer = null; ListGroupInfo.ForEach(g => g.Dispose()); ListGroupInfo.Clear(); } OpcConnected = false; }
/// <summary> /// OPC服务枚举 /// </summary> /// <param name="ipAddress">IP地址</param> /// <param name="message">返回信息</param> /// <returns></returns> public string[] ServerEnum(string ipAddress, out string message) { Array array = null; message = string.Empty; try { if (string.IsNullOrWhiteSpace(ipAddress)) { message = "IP地址为空"; return(null); } if (OpcServer == null) { OpcServer = new OPCServer(); } array = (Array)(object)OpcServer.GetOPCServers(ipAddress); } //假如获取OPC Server过程中引发COMException,即代表无法连接此IP的OPC Server catch (Exception ex) { message = "无法连接此IP地址的OPC Server!" + ex.Message; } return(array?.Cast <string>().ToArray()); }
/// <summary> /// Initialize Potential OPC Tag names to canonical ids (ints). /// </summary> public void Init() { // declarations- not a savvy enough C# programmer not to just hard code array sizes updateditems = new Hashtable(); itemvalues = new string[1000]; tags = new OPCItemDef[1000]; _status = "Reading OPC configuration"; Logger.LogMessage("OPCMgr - Reading OPC configuration\n", Logger.DEBUG); // Read App.config file for OPC and Exe options try { // ShdrService4Opc Settings bSynchronous = Convert.ToBoolean(ConfigurationManager.AppSettings["Synchronous"]); nPriority = Convert.ToInt32(ConfigurationManager.AppSettings["ProcessPriority"]); bAutoConnect = Convert.ToBoolean(ConfigurationManager.AppSettings["AutoConnect"]); nServerUpdatePeriod = Convert.ToInt32(ConfigurationManager.AppSettings["ServerUpdatePeriod"]); nServerRetryPeriod = Convert.ToInt32(ConfigurationManager.AppSettings["ServerRetryPeriod"]); // OPC Settings sOPCProgId = ConfigurationManager.AppSettings["OPCServer"]; //n This works is obsolete by why risk it??? serveritems = (System.Collections.IDictionary)ConfigurationSettings.GetConfig(sOPCProgId); sCNCProcessName = (string)serveritems["CNCProcessName"]; sOpcClsid = (string)serveritems["OpcServerClsid"]; clsid = new System.Guid(sOpcClsid); //myurl = new Opc.URL("opcda://" + sOPCMachine + "/" + sOPCProgId); sUser = ConfigurationManager.AppSettings["User"]; sPassword = ConfigurationManager.AppSettings["Password"]; sDomain = ConfigurationManager.AppSettings["Domain"]; string sRpcAuthzSrv = ConfigurationManager.AppSettings["RpcAuthzSrv"]; string sRpcAuthnLevel = ConfigurationManager.AppSettings["RpcAuthnLevel"]; string sRpcImpersLevel = ConfigurationManager.AppSettings["RpcImpersLevel"]; // MyEnum oMyEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "stringValue"); OpcServer.eRpcAuthzSrv = (RpcAuthnSrv)Enum.Parse(typeof(RpcAuthnSrv), sRpcAuthzSrv); OpcServer.eRpcAuthnLevel = (RpcAuthnLevel)Enum.Parse(typeof(RpcAuthnLevel), sRpcAuthnLevel); OpcServer.eRpcImpersLevel = (RpcImpersLevel)Enum.Parse(typeof(RpcImpersLevel), sRpcImpersLevel); OpcServer.sUser = sUser; OpcServer.sPassword = sPassword; OpcServer.sDomain = sDomain; OpcServer.nSimpleOPCActivate = Convert.ToInt32(ConfigurationManager.AppSettings["SimpleOPCActivate"]); // Map OPC Server data names into canonical names/ids agent.AddDatum("power"); agent.AddDatum("heartbeat"); int i = 0; foreach (DictionaryEntry de in serveritems) { Symbol symbol = new Symbol(); string id = (string)de.Key; if (!id.StartsWith("Tag.")) continue; id = id.Substring(4); symbol.bEnum = false; if (id.StartsWith("Enum.")) { symbol.bEnum = true; id = id.Substring(5); } if (id.StartsWith("Event.")) { symbol.type = "Event"; id = id.Substring(6); } if (id.StartsWith("Sample.")) { symbol.type = "Sample"; id = id.Substring(7); } symbol.name = (string)id; symbol.opcalias = (string)de.Value; symbol.nKey = i; // symbols[i] = symbol; symbols.Add(symbol); agent.AddDatum((string)id); tags[i] = new OPCItemDef(symbol.opcalias, true, i, VarEnum.VT_EMPTY); i++; } ChangeProcessPriority(nPriority); Array.Resize<OPCItemDef>(ref tags, i); Array.Resize<int>(ref handlesSrv, i); Array.Resize<string>(ref itemvalues, i); _opcserver = new OpcServer(); } catch (Exception e) { LogMessage("App.config Initialization Error: " + e.Message, Logger.FATAL); throw e; }; }
/// <summary> /// This removes the OPC group items, opc group and disconnects and nulls the OPC server connection. /// </summary> public void Disconnect() { try { if (_opcserver == null) return; if (!IsConnected()) return; agent.StoreEvent(DateTime.Now.ToString("s"), device, "power", "OFF", null, null, null, null, null, null); if (opcgroup != null) { opcgroup.RemoveItems(handlesSrv, out aE); opcgroup.Remove(false); } _opcserver.Disconnect(); opcgroup = null; _opcserver = null; } catch (Exception e) { LogMessage("OPC Disconnect Error: " + e.Message, Logger.ERROR); _opcserver = null; } }
public void Connect() { int i; try { #if CREDENTIALS LogMessage("Test if CNC Exe IsExecuting()", 1); if ((sCNCProcessName.Length > 0) && !IsExecuting(sOPCMachine, sCNCProcessName)) { throw new Exception("Cannot start OPC Server" + sCNCProcessName + " not running"); } LogMessage("Connect to CNC", 1); // This is used as credentials to logon ont remote pc to see if CNC running System.Net.NetworkCredential credential; if (sDomain.Length > 0) credential = new System.Net.NetworkCredential(sUser, sPassword, sDomain); else credential = new System.Net.NetworkCredential(sUser, sPassword); // , sDomain); #endif _opcserver = new OpcServer(); LogMessage("Attempt OPC Server Connection", Logger.DEBUG); // _opcserver will be null if failed... _opcserver.Connect(this.clsid, this.sIpAddress); LogMessage("Create OPC Group", Logger.DEBUG); opcgroup = _opcserver.AddGroup("OPCCSharp-Group", false, 900); if (opcgroup == null) throw new Exception("Connect - AddGroup failed"); // FIXME: this only works if OPC item exists. // Add items to OPC Group LogMessage("Add OPC Items", Logger.DEBUG); OPCItemResult[] itemresult; opcgroup.AddItems(tags, out itemresult); if (itemresult == null) throw new Exception("Connect - OPC AddItems failed"); LogMessage("Check OPC items for errors.", Logger.DEBUG); for (i = 0; i < itemresult.Length; i++) { // If the OPC item failed - remove it from the tags to be updated. if (HRESULTS.Failed(itemresult[i].Error)) { LogMessage("OPC AddItems Error: " + tags[i].ItemID, Logger.DEBUG); itemresult = (OPCItemResult[])RemoveAt(itemresult, i); tags = (OPCItemDef[])RemoveAt(tags, i); handlesSrv = (int[])RemoveAt(handlesSrv, i); continue; } handlesSrv[i] = itemresult[i].HandleServer; } // read group LogMessage("OPC ReadStatus", Logger.DEBUG); ReadStatus(); LogMessage("OPC ReadGroup", Logger.DEBUG); ReadGroup(); } catch (Exception e) { LogMessage("OPC Connect Error: " + e.Message, Logger.ERROR); Disconnect(); } }
public void Connect() { int i; try { #if CREDENTIALS LogMessage("Test if CNC Exe IsExecuting()", 1); if ((sCNCProcessName.Length > 0) && !IsExecuting(sOPCMachine, sCNCProcessName)) { throw new Exception("Cannot start OPC Server" + sCNCProcessName + " not running"); } LogMessage("Connect to CNC", 1); // This is used as credentials to logon ont remote pc to see if CNC running System.Net.NetworkCredential credential; if (sDomain.Length > 0) { credential = new System.Net.NetworkCredential(sUser, sPassword, sDomain); } else { credential = new System.Net.NetworkCredential(sUser, sPassword); // , sDomain); } #endif _opcserver = new OpcServer(); LogMessage("Attempt OPC Server Connection", Logger.DEBUG); // _opcserver will be null if failed... _opcserver.Connect(this.clsid, this.sIpAddress); LogMessage("Create OPC Group", Logger.DEBUG); opcgroup = _opcserver.AddGroup("OPCCSharp-Group", false, 900); if (opcgroup == null) { throw new Exception("Connect - AddGroup failed"); } // FIXME: this only works if OPC item exists. // Add items to OPC Group LogMessage("Add OPC Items", Logger.DEBUG); OPCItemResult[] itemresult; opcgroup.AddItems(tags, out itemresult); if (itemresult == null) { throw new Exception("Connect - OPC AddItems failed"); } LogMessage("Check OPC items for errors.", Logger.DEBUG); for (i = 0; i < itemresult.Length; i++) { // If the OPC item failed - remove it from the tags to be updated. if (HRESULTS.Failed(itemresult[i].Error)) { LogMessage("OPC AddItems Error: " + tags[i].ItemID, Logger.DEBUG); itemresult = (OPCItemResult[])RemoveAt(itemresult, i); tags = (OPCItemDef[])RemoveAt(tags, i); handlesSrv = (int[])RemoveAt(handlesSrv, i); continue; } handlesSrv[i] = itemresult[i].HandleServer; } // read group LogMessage("OPC ReadStatus", Logger.DEBUG); ReadStatus(); LogMessage("OPC ReadGroup", Logger.DEBUG); ReadGroup(); } catch (Exception e) { LogMessage("OPC Connect Error: " + e.Message, Logger.ERROR); Disconnect(); } }
/// <summary> /// Initialize Potential OPC Tag names to canonical ids (ints). /// </summary> public void Init() { // declarations- not a savvy enough C# programmer not to just hard code array sizes updateditems = new Hashtable(); itemvalues = new string[1000]; tags = new OPCItemDef[1000]; _status = "Reading OPC configuration"; Logger.LogMessage("OPCMgr - Reading OPC configuration\n", Logger.DEBUG); // Read App.config file for OPC and Exe options try { // ShdrService4Opc Settings bSynchronous = Convert.ToBoolean(ConfigurationManager.AppSettings["Synchronous"]); nPriority = Convert.ToInt32(ConfigurationManager.AppSettings["ProcessPriority"]); bAutoConnect = Convert.ToBoolean(ConfigurationManager.AppSettings["AutoConnect"]); nServerUpdatePeriod = Convert.ToInt32(ConfigurationManager.AppSettings["ServerUpdatePeriod"]); nServerRetryPeriod = Convert.ToInt32(ConfigurationManager.AppSettings["ServerRetryPeriod"]); // OPC Settings sOPCProgId = ConfigurationManager.AppSettings["OPCServer"]; //n This works is obsolete by why risk it??? serveritems = (System.Collections.IDictionary)ConfigurationSettings.GetConfig(sOPCProgId); sCNCProcessName = (string)serveritems["CNCProcessName"]; sOpcClsid = (string)serveritems["OpcServerClsid"]; clsid = new System.Guid(sOpcClsid); //myurl = new Opc.URL("opcda://" + sOPCMachine + "/" + sOPCProgId); sUser = ConfigurationManager.AppSettings["User"]; sPassword = ConfigurationManager.AppSettings["Password"]; sDomain = ConfigurationManager.AppSettings["Domain"]; string sRpcAuthzSrv = ConfigurationManager.AppSettings["RpcAuthzSrv"]; string sRpcAuthnLevel = ConfigurationManager.AppSettings["RpcAuthnLevel"]; string sRpcImpersLevel = ConfigurationManager.AppSettings["RpcImpersLevel"]; // MyEnum oMyEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "stringValue"); OpcServer.eRpcAuthzSrv = (RpcAuthnSrv)Enum.Parse(typeof(RpcAuthnSrv), sRpcAuthzSrv); OpcServer.eRpcAuthnLevel = (RpcAuthnLevel)Enum.Parse(typeof(RpcAuthnLevel), sRpcAuthnLevel); OpcServer.eRpcImpersLevel = (RpcImpersLevel)Enum.Parse(typeof(RpcImpersLevel), sRpcImpersLevel); OpcServer.sUser = sUser; OpcServer.sPassword = sPassword; OpcServer.sDomain = sDomain; OpcServer.nSimpleOPCActivate = Convert.ToInt32(ConfigurationManager.AppSettings["SimpleOPCActivate"]); // Map OPC Server data names into canonical names/ids agent.AddDatum("power"); agent.AddDatum("heartbeat"); int i = 0; foreach (DictionaryEntry de in serveritems) { Symbol symbol = new Symbol(); string id = (string)de.Key; if (!id.StartsWith("Tag.")) { continue; } id = id.Substring(4); symbol.bEnum = false; if (id.StartsWith("Enum.")) { symbol.bEnum = true; id = id.Substring(5); } if (id.StartsWith("Event.")) { symbol.type = "Event"; id = id.Substring(6); } if (id.StartsWith("Sample.")) { symbol.type = "Sample"; id = id.Substring(7); } symbol.name = (string)id; symbol.opcalias = (string)de.Value; symbol.nKey = i; // symbols[i] = symbol; symbols.Add(symbol); agent.AddDatum((string)id); tags[i] = new OPCItemDef(symbol.opcalias, true, i, VarEnum.VT_EMPTY); i++; } ChangeProcessPriority(nPriority); Array.Resize <OPCItemDef>(ref tags, i); Array.Resize <int>(ref handlesSrv, i); Array.Resize <string>(ref itemvalues, i); _opcserver = new OpcServer(); } catch (Exception e) { LogMessage("App.config Initialization Error: " + e.Message, Logger.FATAL); throw e; }; }