private void ConnectB_Click(object sender, EventArgs e) { //Use connect with endpoint object if (mySelectedEndpoint != null) { try { myHelperApi.Connect(mySelectedEndpoint, true, UserNameRB.Checked, UserNameTB.Text, PasswordTB.Text).Wait(); mySession = myHelperApi.Session; AddEndpoint(mySelectedEndpoint); ConnectionStatusLabel.Text = "Connected"; ConnectionStatusLabel.ForeColor = Color.Green; DisconnectB.Enabled = true; ConnectB.Enabled = false; // AddLogCallback("Client", "Connected to " + mySession.Endpoint.Server.ApplicationUri, true); AddListIpConfig(DiscoveryUrlTB.Text, DiscoveryPortTB.Text); RetrieveEndpointsAndPopulateLV(); } catch (Exception ex) { MessageBox.Show(ex.InnerException.Message); // AddLogCallback("Client", "Stack error: " + ex.InnerException.Message, false); } } //Use connect without endpoint object else { MessageBox.Show("Please retrieve and selecte Endpoint first.", "Error"); } }
private void btn_Connect_Click(object sender, EventArgs e) { EndpointWrapper wrapper; string endpointUrl; object item = UrlCB.SelectedItem; wrapper = (EndpointWrapper)item; endpointUrl = wrapper.Endpoint.EndpointUrl; m_Server.Connect(wrapper.Endpoint, true, "OpcUaClient", "SUNRISE"); UrlCB.Enabled = false; List <string> readList = new List <string>(); List <string> rest = new List <string>(); readList.Add("ns=2;s=/Channel/State/actToolLength1"); readList.Add("ns=2;s=/Channel/GeometricAxis/actToolBasePos[u1,2]"); rest = m_Server.ReadValues(readList); while (true) { rest = m_Server.ReadValues(readList); label2.Text = rest[1].ToString(); //label2.Update(); label2.Refresh(); } }
// Подключение к считывателю по OPC UA public void connectOPC() { // Точка подключения EndpointDescription eds = new EndpointDescription("opc.tcp://" + url + "/"); myHelperApi.CertificateValidationNotification += new CertificateValidationEventHandler(Notification_ServerCertificate); myHelperApi.KeepAliveNotification += new KeepAliveEventHandler(Notification_KeepAlive); try { myHelperApi.Connect(eds, true, false, "", "").Wait(); Debug.WriteLine("___Success connection___"); } catch { Debug.WriteLine("___Error connection___"); } // Проверка результатов подключения if (myHelperApi.Session != null && myHelperApi.Session.Connected) { mySubscribe = myHelperApi.Subscribe(1000); myHelperApi.CertificateValidationNotification += new CertificateValidationEventHandler(Notification_ServerCertificate); myHelperApi.KeepAliveNotification += new KeepAliveEventHandler(Notification_KeepAlive); // Запрос методов и пространства имен myRfidMethodIdentifiers = new UARfidMethodIdentifiers(myHelperApi); rfidNamespaceIdx = GetRfidNamespaceIndex(); } this.connected = (myHelperApi.Session != null && myHelperApi.Session.Connected); }
/// <summary> /// Connect to the UA server and read the namespace table. /// The connect is based on the Server URL entered in the Form /// The read of the namespace table is used to detect the namespace index /// of the namespace URI entered in the Form and used for the variables to read /// </summary> private void btnConnect_Click(object sender, EventArgs e) { // Connect to the server try { // Connect with URL from Server URL text box m_Server.Connect(txtServerUrl.Text, "none", MessageSecurityMode.None, false, "", ""); // Toggle enable flag of buttons toggleButtons(true); } catch (Exception ex) { MessageBox.Show("Connect failed:\n\n" + ex.Message); return; } // Read Namespace Table try { List <string> nodesToRead = new List <string>(); List <string> results = new List <string>(); nodesToRead.Add("ns=0;i=" + Variables.Server_NamespaceArray.ToString()); // Read the namespace array results = m_Server.ReadValues(nodesToRead); if (results.Count != 1) { throw new Exception("Reading namespace table returned unexptected result"); } // Try to find the namespace URI entered by the user string[] nameSpaceArray = results[0].Split(';'); ushort i; for (i = 0; i < nameSpaceArray.Length; i++) { if (nameSpaceArray[i] == txtNamespaceUri.Text) { m_NameSpaceIndex = i; } } // Check if the namespace was found if (m_NameSpaceIndex == 0) { throw new Exception("Namespace " + txtNamespaceUri.Text + " not found in server namespace table"); } } catch (Exception ex) { MessageBox.Show("Reading namespace table failed:\n\n" + ex.Message); } }
private void EpConnectButton_Click(object sender, EventArgs e) { //Check if sessions exists; If yes > delete subscriptions and disconnect if (mySession != null && !mySession.Disposed) { try { //mySubscription.Delete(true); } catch { ; } myClientHelperAPI.Disconnect(); mySession = myClientHelperAPI.Session; ResetUI(); } else { try { //Register mandatory events (cert and keep alive) myClientHelperAPI.KeepAliveNotification += new KeepAliveEventHandler(Notification_KeepAlive); myClientHelperAPI.CertificateValidationNotification += new CertificateValidationEventHandler(Notification_ServerCertificate); //Check for a selected endpoint if (mySelectedEndpoint != null) { //Call connect myClientHelperAPI.Connect(mySelectedEndpoint, userPwButton.Checked, userTextBox.Text, pwTextBox.Text).Wait(); //Extract the session object for further direct session interactions mySession = myClientHelperAPI.Session; //UI settings epConnectServerButton.Text = "Disconnect from server"; browsePage.Enabled = true; monitoringPage.Enabled = true; myCertForm = null; } else { MessageBox.Show("Please select an endpoint before connecting", "Error"); return; } } catch (Exception ex) { myCertForm = null; ResetUI(); MessageBox.Show(ex.InnerException.Message, "Error"); } } }
public int Connect() { try { List <object> Listtmp = new List <object>(); ApplicationDescriptionCollection servers = null; servers = m_Server.FindServers(discoveryUrl.ToString()); //for (int i = 0; i < servers.Count; i++) //{ // // Create discovery client and get the available endpoints. EndpointDescriptionCollection endpoints = null; // string sUrl; // sUrl = servers[i].DiscoveryUrls[0]; // discoveryUrl = new Uri(sUrl); endpoints = m_Server.GetEndpoints(discoveryUrl.ToString()); // Create wrapper and fill the combobox. for (int j = 0; j < endpoints.Count; j++) { // Create endpoint wrapper. EndpointWrapper wrapper = new EndpointWrapper(endpoints[j]); Listtmp.Add(wrapper); // Add it to the combobox. // UrlCB.Items.Add(wrapper); } if (Listtmp != null) { // Call connect with URL //m_Server.Connect(Listtmp[0].ToString(), "none", MessageSecurityMode.None, false, "", ""); m_Server.Connect(((EndpointWrapper)Listtmp[0]).Endpoint, false, "", ""); } else { m_Connected = false; return(-1); } //} //servers[i].ApplicationName; m_Connected = true; return(0); } catch { //MessageBox.Show(ex.Message); if (m_Connected) { // Disconnect from server. Disconnect(); } m_Connected = false; return(-1); } }
/// <summary> /// 连接服务器 /// </summary> /// <param name="server"></param> /// <returns></returns> public bool Connect(OpcServer server) { var uaServer = server as OpcUaServer; if (uaServer == null) { return(false); } uAClient.Connect((EndpointDescription)uaServer.EndpointDesCription.OpcEndpointDescription, uaServer.UserAuth, uaServer.UserName, uaServer.Password); _Subscription = uAClient.Subscribe(uaServer.SubscriptionPublishingInterval); return(true); }
private void connectBtn_Click(object sender, EventArgs e) { myHelperApi.ItemChangedNotification -= new MonitoredItemNotificationEventHandler(Notification_MonitoredItem); myHelperApi.ItemEventNotification -= new MonitoredItemNotificationEventHandler(Notification_EventItem); myHelperApi.KeepAliveNotification -= new KeepAliveEventHandler(Notification_KeepAlive); myHelperApi.CertificateValidationNotification += new CertificateValidationEventHandler(Notification_ServerCertificate); myHelperApi.KeepAliveNotification += new KeepAliveEventHandler(Notification_KeepAlive); string url = "opc.tcp://" + txtIpPort.Text + "/"; EndpointDescription eds = new EndpointDescription(url); try { myHelperApi.Connect(eds, true, false, "", "").Wait(); txtIpPort.BackColor = Color.Green; MessageBox.Show("Connection Success", "Inform", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("Connection Error", "Inform", MessageBoxButtons.OK, MessageBoxIcon.Error); txtIpPort.BackColor = Color.Red; } mySession = myHelperApi.Session; if (mySession != null && mySession.Connected) { Debug.WriteLine("Session success connected"); try { mySubscription = myHelperApi.Subscribe(1000); myEventSubscription = myHelperApi.Subscribe(1000); } catch { Debug.WriteLine("Error subscribe connection"); } myHelperApi.CertificateValidationNotification -= new CertificateValidationEventHandler(Notification_ServerCertificate); myHelperApi.KeepAliveNotification -= new KeepAliveEventHandler(Notification_KeepAlive); myHelperApi.ItemChangedNotification += new MonitoredItemNotificationEventHandler(Notification_MonitoredItem); myHelperApi.ItemEventNotification += new MonitoredItemNotificationEventHandler(Notification_EventItem); myHelperApi.KeepAliveNotification += new KeepAliveEventHandler(Notification_KeepAlive); myRfidNamespaceIndex = GetRfidNamespaceIndex(); myRfidMethodIdentifiers = new UARfidMethodIdentifiers(myHelperApi); } }
public void init() { try { /* * log.Debug * log.Info * log.Error * log.Fatal */ myClientHelperAPI = new UAClientHelperAPI(); EndpointDescription mySelectedEndpoint = null; log.Info("Start OPC connection..."); //mySelectedEndpoint = CreateEndpointDescription(endpointUrl, secPolicy, MessageSecurityMode.None); mySelectedEndpoint = getEndpointDescription(endpointUrl); if (opcSession == null && mySelectedEndpoint != null) { myClientHelperAPI.KeepAliveNotification += new Opc.Ua.Client.KeepAliveEventHandler(plcKeepAliveEventHandler); //myClientHelperAPI.CertificateValidationNotification += new CertificateValidationEventHandler(Notification_ServerCertificate); //Call connect myClientHelperAPI.Connect(mySelectedEndpoint, opcuser.Length > 0, opcuser, opcpwd); //myClientHelperAPI.Connect(mySelectedEndpoint.EndpointUrl, mySelectedEndpoint.SecurityPolicyUri, MessageSecurityMode.None, false, null, null); opcSession = myClientHelperAPI.Session; log.Info("OPC connect successfull"); //load jobs from database loadJobsFromDb(); //Új szál indítása this.plcMaxQSize = int.Parse(ConfigurationManager.AppSettings["plc_max_q_size"]); this.sleepMillis = int.Parse(ConfigurationManager.AppSettings["thread_sleepmillis"]); this.isRunning = true; this.mainThread = new Thread(this.Ciklus); this.mainThread.Start(); } } catch (Exception exp) { log.Info("OPC not connected" + exp); } }
public static void OPC() { m_Server = new UAClientHelperAPI(); m_Server.CertificateValidationNotification += new CertificateValidationEventHandler(m_Server_CertificateEvent); try { m_Server.Connect("opc.tcp://192.168.90.39:4840", "none", MessageSecurityMode.SignAndEncrypt, true, "OpcUaClient", "12345678"); } catch { Console.WriteLine("Wrong connections data, check opc address and credentials"); return; } List <string> nodesToRead = new List <string>(); nodesToRead.Add("ns=0;i=" + Variables.Server_NamespaceArray.ToString()); }
public void init(String endpointUrl, String opcuser, String opcpwd) { log.Debug("PLCHandler.init() begin"); myClientHelperAPI = new UAClientHelperAPI(); EndpointDescription mySelectedEndpoint = null; //mySelectedEndpoint = CreateEndpointDescription(endpointUrl, secPolicy, MessageSecurityMode.None); mySelectedEndpoint = getEndpointDescription(endpointUrl); if (opcSession == null && mySelectedEndpoint != null) { myClientHelperAPI.KeepAliveNotification += new Opc.Ua.Client.KeepAliveEventHandler(plcKeepAliveEventHandler); //myClientHelperAPI.CertificateValidationNotification += new CertificateValidationEventHandler(Notification_ServerCertificate); //Call connect myClientHelperAPI.Connect(mySelectedEndpoint, opcuser.Length > 0, opcuser, opcpwd); //myClientHelperAPI.Connect(mySelectedEndpoint.EndpointUrl, mySelectedEndpoint.SecurityPolicyUri, MessageSecurityMode.None, false, null, null); opcSession = myClientHelperAPI.Session; log.Debug("PLCHandler.init() end"); } }
// Подключение к считывателю по OPC UA public void connectOPC() { // Точка подключения EndpointDescription eds = new EndpointDescription("opc.tcp://" + url + "/"); try { myHelperApi.Connect(eds, true, false, "", "").Wait(); rfidKey.SetValue("Debug", url + " | Success connected"); } catch { rfidKey.SetValue("Debug", url + " | Error connected"); } // Проверка результатов подключения if (myHelperApi.Session != null && myHelperApi.Session.Connected) { // Запрос методов и пространства имен myRfidMethodIdentifiers = new UARfidMethodIdentifiers(myHelperApi); rfidNamespaceIdx = GetRfidNamespaceIndex(); } this.connected = (myHelperApi.Session != null && myHelperApi.Session.Connected); }
protected void Connect_Click(object sender, EventArgs e) { if (ConnectBtn.Text == "Connect") { if (discoveryTextBox.Text != "") { bool foundEndpoints = false; for (int a = 0; a < endpointListView.Items.Count; a++) { if (endpointListView.Items[a].Selected == true) { cnt = a; break; } } string discoveryUrl = discoveryTextBox.Text; ApplicationDescriptionCollection servers = myClientHelperAPI.FindServers(discoveryUrl); foreach (ApplicationDescription ad in servers) { foreach (string url in ad.DiscoveryUrls) { EndpointDescriptionCollection endpoints = myClientHelperAPI.GetEndpoints(url); foundEndpoints = foundEndpoints || endpoints.Count > 0; if (cnt != -1) { mySelectedEndpoint = endpoints[cnt]; } else { ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('warning','Warning...','Please select an endpoint before connecting')", true); return; } } } //Check if sessions exists; If yes > delete subscriptions and disconnect try { //Register mandatory events (cert and keep alive) myClientHelperAPI.KeepAliveNotification += new KeepAliveEventHandler(Notification_KeepAlive); myClientHelperAPI.CertificateValidationNotification += new CertificateValidationEventHandler(Notification_ServerCertificate); //Check for a selected endpoint //Call connect myClientHelperAPI.Connect(mySelectedEndpoint, RadioButtonList1.Items.FindByValue("User/Password").Selected, userTextBox.Text, pwTextBox.Text).Wait(); //Extract the session object for further direct session interactions mySession = myClientHelperAPI.Session; SerName.Text = mySelectedEndpoint.Server.ApplicationName.ToString(); SerUri.Text = mySelectedEndpoint.Server.ApplicationUri.ToString(); Serc.Text = mySelectedEndpoint.SecurityLevel.ToString(); Status.Text = "Connected"; Sinced.Text = DateTime.Now.ToString(); //Data save Page Reload Session["endpoint"] = mySelectedEndpoint; Session["sinced"] = DateTime.Now.ToString(); //UI settings ConnectBtn.Text = "Disconnect from server"; ControlEnable(); ClientScript.RegisterStartupScript(this.GetType(), "Success", "messtimer('success','Connect Successful')", true); //myCertForm = null; } catch (Exception ex) { //myCertForm = null; //ResetUI(); ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('error','Opps...'," + ex.ToString() + ")", true); } } else { ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('warning','Warning...','You forget write endpoint Url!')", true); } } else { Disconnect(); //mySubscription.Delete(true); } }
/// <summary> /// Connect to server. /// </summary> private int Connect() { // Check the content of the combobox. if (UrlCB.Text.Length == 0) { return(-1); } // Set wait cursor. Cursor = Cursors.WaitCursor; int result = 0; try { EndpointWrapper wrapper; string endpointUrl; // Extract Url from combobox text. object item = UrlCB.SelectedItem; if ((item == null) || (item.GetType() == typeof(string))) { // The URL has been entered as text. endpointUrl = UrlCB.Text; // Call connect with URL m_Server.Connect(endpointUrl, "none", MessageSecurityMode.None, false, "", ""); } else { // The endpoint was provided through discovery. wrapper = (EndpointWrapper)item; endpointUrl = wrapper.Endpoint.EndpointUrl; // Call connect with endpoint m_Server.Connect(wrapper.Endpoint, false, "", ""); } // Connect succeeded. m_Connected = true; // Aggregate the UserControls. browseControl.Server = m_Server; attributeListControl.Server = m_Server; monitoredItemsControl.Server = m_Server; // State is connected now. ConnectDisconnectBTN.Text = "Disconnect"; // Update status label. toolStripStatusLabel.Text = "Connected to " + endpointUrl; toolStripStatusLabel.Image = global::Siemens.OpcUA.Client.Properties.Resources.success; UrlCB.Enabled = false; } catch (Exception e) { if (m_Connected) { // Disconnect from server. Disconnect(); } result = -1; m_Connected = false; // Update status label. toolStripStatusLabel.Text = "Connect failed. Error: " + e.Message; toolStripStatusLabel.Image = global::Siemens.OpcUA.Client.Properties.Resources.error; } // Set default cursor. Cursor = Cursors.Default; return(result); }
private void EpConnectServerButton_Click(object sender, EventArgs e) { var classOPCUA = new OPCUA(); //Check if sessions exists; If yes > delete subscriptions and disconnect if (mySession != null && !mySession.Disposed) { myClientHelperAPI.Disconnect(); mySession = myClientHelperAPI.Session; ResetUI(); } else { try { //Register mandatory events (cert and keep alive) myClientHelperAPI.KeepAliveNotification += new KeepAliveEventHandler(classOPCUA.Notification_KeepAlive); myClientHelperAPI.CertificateValidationNotification += new CertificateValidationEventHandler(classOPCUA.Notification_ServerCertificate); //Check for a selected endpoint if (mySelectedEndpoint != null) { //Call connect myClientHelperAPI.Connect(mySelectedEndpoint, userPwButton.Checked, userTextBox.Text, pwTextBox.Text); //Extract the session object for further direct session interactions mySession = myClientHelperAPI.Session; //UI settings epConnectServerButton.Text = "Disconnect from server"; //myCertForm = null; if (descriptionGridView.Enabled == false) { descriptionGridView.Enabled = true; descriptionGridView.BackgroundColor = SystemColors.Window; nodeTreeView.Enabled = true; nodeTreeView.BackColor = SystemColors.Window; numericS7RecordsCount.Enabled = true; numericS7RecordsCount.BackColor = SystemColors.Window; textBoxSQLTableName.Enabled = true; textBoxSQLTableName.BackColor = SystemColors.Window; textBoxSQLIDColName.BackColor = SystemColors.Window; textBoxSQLIDColName.Enabled = true; textBoxSQLValColName.BackColor = SystemColors.Window; textBoxSQLValColName.Enabled = true; textBoxSQLDATColName.BackColor = SystemColors.Window; textBoxSQLDATColName.Enabled = true; } if (Config.Sets.Primary_ODBC_DSN != "") { connStringBuilder.Dsn = Config.Sets.Primary_ODBC_DSN; connStringBuilder.Add("Uid", Config.Sets.Primary_ODBC_User); connStringBuilder.Add("Pwd", Config.Sets.Primary_ODBC_Pass); } if (Config.Sets.Primary_OPCUA_Node != "") { //discoveryTextBox.Text = Config.Sets.Primary_OPCUA_Node; textBoxS7DBName.Text = Config.Sets.Primary_S7_DBName; textBoxS7RecArrayName.Text = Config.Sets.Primary_OPCUA_RecArray; textBoxS7RecResetCountName.Text = Config.Sets.Primary_OPCUA_RecResetCount; } if (Config.Sets.Primary_SQL_NumberOfRec != 0) { numericS7RecordsCount.Value = Config.Sets.Primary_SQL_NumberOfRec; textBoxSQLTableName.Text = Config.Sets.Primary_SQL_TableName; textBoxSQLIDColName.Text = Config.Sets.Primary_SQL_IDColName; textBoxSQLValColName.Text = Config.Sets.Primary_SQL_ValColName; textBoxSQLDATColName.Text = Config.Sets.Primary_SQL_DATColName; buttonSaveConfig.Enabled = true; buttonSaveConfig.BackColor = Color.Transparent; } if (myReferenceDescriptionCollection == null) { try { myReferenceDescriptionCollection = myClientHelperAPI.BrowseRoot(); foreach (ReferenceDescription refDesc in myReferenceDescriptionCollection) { nodeTreeView.Nodes.Add(refDesc.DisplayName.ToString()).Tag = refDesc; foreach (TreeNode node in nodeTreeView.Nodes) { node.Nodes.Add(""); } } } catch (Exception ex) { if (BGW_OPCUA.IsBusy) { BGW_OPCUA.CancelAsync(); } MessageBox.Show(ex.Message, "Error"); } } } else { MessageBox.Show("Please select an endpoint before connecting", "Error"); return; } } catch (Exception ex) { if (BGW_OPCUA.IsBusy) { BGW_OPCUA.CancelAsync(); } //myCertForm = null; MessageBox.Show(ex.Message, "Error"); } } }