internal OPCSessionServer(OPCCliConfiguration.ServersRow server, OpcDa::BrowseFilters filters, OPCEnvironment node) : base(server.Name, null, node) { LastEception = null; try { m_Menu = new ContextMenuServer(this); Opc.URL url = new Opc.URL(server.URL); if (server.GetConnectDataRows().Length > 0) { m_ConnectData = server.GetConnectDataRows()[0].GetConnectData(); } m_Spcification = new Opc.Specification() { ID = server.PreferedSpecyficationID, Description = server.PreferedSpecyficationDsc }; Tag = (Server)Factory.GetServerForURL(url, m_Spcification); server.GetOptions(this); foreach (OPCCliConfiguration.SubscriptionsRow rw in server.GetSubscriptionsRows()) { new SubscriptionTreeNodeSession(rw, this); } State = state.disconnectd; } catch (Exception ex) { ReportException(ex); } }
//protected override IEnumerable<IOpcNode> CreateNodes(OpcNodeReferenceCollection references) //{ // OpcFolderNode machineOne = new OpcFolderNode(new OpcName("Machine_1")); // //references.Add(machineOne, OpcObjectTypes.ObjectsFolder); // return new IOpcNode[] { machineOne }; //} private void Brown_OPC_Server_Click(object sender, EventArgs e) { try { listBox1.Items.Clear(); //OpcFolderNode machineOne = new OpcFolderNode("localhost"); //String ss = machineOne.Parent.ToString(); //Console.WriteLine(ss); System.Net.NetworkCredential mCredentials = new System.Net.NetworkCredential(); Opc.ConnectData mConnectData = new Opc.ConnectData(mCredentials); OpcCom.ServerEnumerator se = new OpcCom.ServerEnumerator(); Opc.Server[] servers = se.GetAvailableServers(Opc.Specification.COM_DA_20, Node.Text.ToString(), mConnectData); for (int i = 0; i < servers.Length; i++) { //Console.WriteLine("Server {0}: >{1}<", i, servers[i].Name); listBox1.Items.Add(servers[i].Name); } } catch (Exception ex) { MessageBox.Show("Error \n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Подключение к серверу OPC. /// </summary> /// <overloads> </overloads> public void Connect(string hostIp, string serverId) { // Создание URL //string url = "opcda://localhost/opcserversim.Instance.1"; string url = "opcda://" + hostIp + "/" + serverId; var opcUrl = new Opc.URL(url); var connectData = new Opc.ConnectData(new System.Net.NetworkCredential()); try { serverHandle.Connect(opcUrl, connectData); isConnected = true; Console.WriteLine("Connected to {0}", url); } catch (Exception exception) { Console.WriteLine("Failed to connect - status {0}", exception); } }
public bool Connect(string serverUrl) { var opcServerUrl = new Opc.URL(serverUrl); Server = new Opc.Da.Server(new OpcCom.Factory(), opcServerUrl); try { //System.Net.NetworkCredential credentials = null; //System.Net.WebProxy webProxy = null; var connectData = new Opc.ConnectData(null, null); Server.Connect(connectData); var status = Server.GetStatus(); VendorInfo = status.VendorInfo; VersionInfo = status.ProductVersion; StatusInfo = status.StatusInfo; // Assign a globally unique handle to the subscription. var state = new Opc.Da.SubscriptionState() { Name = "RSLinxConnectApp", Active = false, UpdateRate = 1000, KeepAlive = 0, Deadband = 0, Locale = null, ClientHandle = Guid.NewGuid().ToString(), ServerHandle = null }; Subscription = Server.CreateSubscription(state) as Opc.Da.Subscription; return(true); } catch (Exception e) { StatusInfo = e.Message; Console.WriteLine(e.Message); } return(false); }
/// <summary> /// Подключение к серверу OPC. Данные для подключения берутся из конфигурационного файла. /// </summary> public void Connect() { // Создание URL string url = "opcda://localhost/" + config.opcServerId; //string url = "opcda://" + config.amicumIp + "/" + config.opcServerId; var opcUrl = new Opc.URL(url); var connectData = new Opc.ConnectData(new System.Net.NetworkCredential()); try { serverHandle.Connect(opcUrl, connectData); isConnected = true; InitTagList(); Console.WriteLine("Connected to {0}", url); } catch (Exception exception) { Console.WriteLine("Failed to connect - status {0}", exception); } }
/// <summary> /// Prompts the user to set the network connectData for the node. /// </summary> private void TSM_SetLogin_Click(object sender, System.EventArgs e) { var node = m_BrowseTV.SelectedNode as IConnectDataNode; switch (node.GetNodeType) { case NodeType.Computer: case NodeType.Network: case NodeType.OPCServer: Opc.ConnectData cd = node.ConnectDataObject == null ? new Opc.ConnectData(null) : node.ConnectDataObject; using (NetworkCredentialsDlg dial = new NetworkCredentialsDlg()) { NetworkCredential res = dial.ShowDialog(cd.Credentials); if (dial.DialogResult == DialogResult.OK) { node.ConnectDataObject = new Opc.ConnectData(res); } } break; default: break; } }
//====================================================================== // IFactory /// <summary> /// Creates a new instance of the server. /// </summary> public override Opc.IServer CreateInstance(Opc.URL url, Opc.ConnectData connectData) { // validate requested type. if (SystemType != null) { // XML-DA 1.00 if (SystemType == typeof(OpcXml.Da.Server)) { OpcXml.Da.Server server = new OpcXml.Da.Server(); try { server.Initialize(url, connectData); } catch { throw new NotSupportedException(SystemType.FullName); } return(server); } #if (UA) // UA 1.00 if (SystemType == typeof(OpcXml.Ua.XmlServiceClient)) { OpcXml.Ua.XmlServiceClient server = new OpcXml.Ua.XmlServiceClient(); try { server.Initialize(url, connectData); } catch { throw new NotSupportedException(SystemType.FullName); } return(server); } #endif // object does not support requested interface type. throw new NotSupportedException(SystemType.FullName); } // auto-detect server type. else { // XML-DA 1.00 if (url.Scheme == Opc.UrlScheme.HTTP) { try { OpcXml.Da.Server server = new OpcXml.Da.Server(); server.Initialize(url, connectData); return(server); } catch (Exception e) { throw new Opc.ResultIDException(Opc.ResultID.E_FAIL, e.Message, e); } } #if (UA) // UA 1.00 over TCP if (url.Scheme == Opc.UrlScheme.UA_TCP) { try { OpcXml.Ua.TcpServiceClient server = new OpcXml.Ua.TcpServiceClient(); server.Initialize(url, connectData); return(server); } catch (Exception e) { throw new Opc.ResultIDException(Opc.ResultID.E_FAIL, e.Message, e); } } // UA 1.00 over HTTP if (url.Scheme == Opc.UrlScheme.UA_HTTP) { try { OpcXml.Ua.XmlServiceClient server = new OpcXml.Ua.XmlServiceClient(); server.Initialize(url, connectData); return(server); } catch (Exception e) { throw new Opc.ResultIDException(Opc.ResultID.E_FAIL, e.Message, e); } } #endif // object does not support requested url scheme. throw new NotSupportedException(url.Scheme); } }
//====================================================================== // IFactory /// <summary> /// Creates a new instance of the server. /// </summary> public override Opc.IServer CreateInstance(Opc.URL url, Opc.ConnectData connectData) { object comServer = Factory.Connect(url, connectData); if (comServer == null) { return(null); } OpcCom.Server server = null; System.Type interfaceType = null; try { // DA if (url.Scheme == Opc.UrlScheme.DA) { // Verify that it is a DA server. if (!typeof(OpcRcw.Da.IOPCServer).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Da.IOPCServer); throw new NotSupportedException(); } // DA 3.00 if (typeof(OpcRcw.Da.IOPCBrowse).IsInstanceOfType(comServer) && typeof(OpcRcw.Da.IOPCItemIO).IsInstanceOfType(comServer)) { server = new OpcCom.Da.Server(url, comServer); } // DA 2.XX else if (typeof(OpcRcw.Da.IOPCItemProperties).IsInstanceOfType(comServer)) { server = new OpcCom.Da20.Server(url, comServer); } else { interfaceType = typeof(OpcRcw.Da.IOPCItemProperties); throw new NotSupportedException(); } } // AE else if (url.Scheme == Opc.UrlScheme.AE) { // Verify that it is a AE server. if (!typeof(OpcRcw.Ae.IOPCEventServer).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Ae.IOPCEventServer); throw new NotSupportedException(); } server = new OpcCom.Ae.Server(url, comServer); } // HDA else if (url.Scheme == Opc.UrlScheme.HDA) { // Verify that it is a HDA server. if (!typeof(OpcRcw.Hda.IOPCHDA_Server).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Hda.IOPCHDA_Server); throw new NotSupportedException(); } server = new OpcCom.Hda.Server(url, comServer); } // DX else if (url.Scheme == Opc.UrlScheme.DX) { // Verify that it is a DX server. if (!typeof(OpcRcw.Dx.IOPCConfiguration).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Dx.IOPCConfiguration); throw new NotSupportedException(); } server = new OpcCom.Dx.Server(url, comServer); } // All other specifications not supported yet. else { throw new NotSupportedException(String.Format("The URL scheme '{0}' is not supported.", url.Scheme)); } } catch (NotSupportedException e) { OpcCom.Interop.ReleaseServer(server); server = null; if (interfaceType != null) { StringBuilder message = new StringBuilder(); message.AppendFormat("The COM server does not support the interface "); message.AppendFormat("'{0}'.", interfaceType.FullName); message.Append("\r\n\r\nThis problem could be caused by:\r\n"); message.Append("- incorrectly installed proxy/stubs.\r\n"); message.Append("- problems with the DCOM security settings.\r\n"); message.Append("- a personal firewall (sometimes activated by default).\r\n"); throw new NotSupportedException(message.ToString()); } throw e; } catch (Exception e) { OpcCom.Interop.ReleaseServer(server); server = null; throw e; } // initialize the wrapper object. if (server != null) { server.Initialize(url, connectData); } return(server); }
/// <summary> /// Connects to the specified COM server server. /// </summary> public static object Connect(Opc.URL url, Opc.ConnectData connectData) { // parse path to find prog id and clsid. string progID = url.Path; string clsid = null; int index = url.Path.LastIndexOf('/'); if (index >= 0) { progID = url.Path.Substring(0, index); clsid = url.Path.Substring(index + 1); } // look up prog id if clsid not specified in the url. Guid guid; if (clsid == null) { // use OpcEnum to lookup the prog id. guid = new ServerEnumerator().CLSIDFromProgID(progID, url.HostName, connectData); // check if prog id is actually a clsid string. if (guid == Guid.Empty) { try { guid = new Guid(progID); } catch { throw new Opc.ConnectFailedException(progID); } } } // convert clsid string to a guid. else { try { guid = new Guid(clsid); } catch { throw new Opc.ConnectFailedException(clsid); } } // get the credentials. NetworkCredential credentials = (connectData != null)?connectData.GetCredential(null, null):null; // instantiate the server using CoCreateInstanceEx. if (connectData == null || connectData.LicenseKey == null) { try { return(OpcCom.Interop.CreateInstance(guid, url.HostName, credentials)); } catch (Exception e) { throw new Opc.ConnectFailedException(e); } } // instantiate the server using IClassFactory2. else { try { return(OpcCom.Interop.CreateInstanceWithLicenseKey(guid, url.HostName, credentials, connectData.LicenseKey)); } catch (Exception e) { throw new Opc.ConnectFailedException(e); } } }
public void Connect_OPC() { //Console.WriteLine("Connect_OPC"); try { servername = Pub_dtTSetting.Rows[0][2].ToString(); if (servername != "") { Opc.URL url = new Opc.URL("opcda://" + Pub_dtTSetting.Rows[0][1].ToString() + "/" + Pub_dtTSetting.Rows[0][2].ToString()); Opc.Da.Server serveropc = null; OpcCom.Factory fact = new OpcCom.Factory(); //Kepware.KEPServerEX.V6 Opc.Da.ServerStatus serverStatus = new Opc.Da.ServerStatus(); //serveropc = new Opc.Da.Server(fact, null); serveropc = new Opc.Da.Server(fact, url); System.Net.NetworkCredential mCredentials = new System.Net.NetworkCredential(); Opc.ConnectData mConnectData = new Opc.ConnectData(mCredentials); try { //2nd: Connect to the created server serveropc.Connect(url, mConnectData); #if DEBUG_ERROR #warning you must install RSLinx server OR Kepware.KEPServerEX.V6 for install important .dll then you can easy test with Kepware.KEPServerEX.V6 #endif //serveropc.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); //ไม่เปิดเซิฟเวอ จะติดตรงนี้ serverStatus = serveropc.GetStatus(); servercurrent_status = serverStatus.ServerState.ToString(); ServerStatusInTime.Text = serverStatus.ServerState.ToString(); //Append Log file if server Status running------------------------------------------------- string CompareServerstatus = "running"; if (serverStatus.ServerState.ToString() == CompareServerstatus) { if (PortStatus.Text.ToString() == "Stop") { //StartPort.Visible = true; } string timeinlog = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd HH:mm:ss= "); if (write_log == false) //First Time Write Log { using (StreamWriter sw = File.AppendText(AppendFilepath)) { sw.WriteLine(timeinlog + Pub_dtTSetting.Rows[0][2].ToString() + " DCOM security The operation completed successfully"); sw.WriteLine(timeinlog + "Connected to OPC server"); sw.WriteLine(timeinlog + "MyGroup Added group to server The operation completed successfully"); } } write_log = true; // 1 mean don't write agian use in ReadCompleteCallback } //---------------------------------------------------------------- //3rd Create a group if items Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState(); groupState.Name = "group"; groupState.Active = true; group = (Opc.Da.Subscription)serveropc.CreateSubscription(groupState); // add items to the group Opc.Da.Item[] items = new Opc.Da.Item[Pub_dtTTAGMapping.Rows.Count]; //Add item by DataTable From Function Get_TagMapping for (int index_Tag = 0; index_Tag < Pub_dtTTAGMapping.Rows.Count; index_Tag++) { items[index_Tag] = new Opc.Da.Item(); //Tag_Name items[index_Tag].ItemName = Pub_dtTTAGMapping.Rows[index_Tag][2].ToString();//Pub_dtTTAGMapping.Rows[Row][Column] } items = group.AddItems(items); this.timerModbus.Interval = (Convert.ToInt32(Pub_dtTSetting.Rows[0][5]) * 100); this.timerModbus.AutoReset = false; this.timerModbus.Start(); }//end try catch (Exception) { servercurrent_status = "Stop"; //Exception Server Not Run string timeinlog = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd HH:mm:ss= "); write_log = false; // 1 mean don't write agian use in ReadCompleteCallback ServerStatusInTime.Text = "Stop"; using (StreamWriter sw = File.AppendText(AppendFilepath)) { //Pub_dtTSetting.Rows[0][2].ToString() => ServerName sw.WriteLine(timeinlog + Pub_dtTSetting.Rows[0][2].ToString() + " DCOM security The operation completed successfully"); sw.WriteLine(timeinlog + "Unable to connect to OPC server"); sw.WriteLine(timeinlog + "MyGroup Unable to add group to server Unspecified error"); sw.WriteLine(timeinlog + "Service will be Reconnect To OPC Server With in 1 minutes"); } this.timerModbus.Interval = (Convert.ToInt32(Pub_dtTSetting.Rows[0][5])) * 1000; this.timerModbus.AutoReset = false; this.timerModbus.Start(); } //end catch } //end if } catch (Exception ex) { using (StreamWriter sw = File.AppendText(indebuglogFolderPath + "\\" + filename + ".txt")) { sw.WriteLine("ERROR : " + ex); } } // 1st: Create a server object and connect to the RSLinx OPC Server }