示例#1
0
        private List <EndpointDescription> ListEndpoints(string serverUrl)
        {
            List <EndpointDescription> endPointsList = new List <EndpointDescription>();

            try
            {
                ApplicationDescriptionCollection servers = FindServers(serverUrl);

                foreach (ApplicationDescription ad in servers)
                {
                    foreach (string url in ad.DiscoveryUrls)
                    {
                        EndpointDescriptionCollection endpoints = GetEndpoints(url);
                        foreach (EndpointDescription ep in endpoints)
                        {
                            endPointsList.Add(ep);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                endPointsList?.Clear();
                endPointsList = null;
                System.Diagnostics.Debug.WriteLine("OpcUaClient::ListEndpoints" + ex.Message);
            }

            return(endPointsList);
        }
示例#2
0
        public static ApplicationDescriptionCollection  getServersDescr(string aDiscoveryUrl)
        {
            Uri lDiscoveryUrl;

            if (String.IsNullOrWhiteSpace(aDiscoveryUrl))
            {
                lDiscoveryUrl = new Uri("opc.tcp://localhost:4840");
            }
            else
            {
                lDiscoveryUrl = new Uri(aDiscoveryUrl);
            }

            var lAllServers = DiscoveryClient.Create(lDiscoveryUrl).FindServers(null);
            var lResult     = new ApplicationDescriptionCollection();

            foreach (var lServer in lAllServers)
            {
                if (lServer.ApplicationType == ApplicationType.ClientAndServer || lServer.ApplicationType == ApplicationType.Server)
                {
                    lResult.Add(lServer);
                }
            }

            return(lResult);
        }
示例#3
0
        public List <EndpointDes> FindServer(string serverUrl)
        {
            List <EndpointDes> endpointListView = new List <EndpointDes>();

            _EndpointDescriptions.Clear();
            ApplicationDescriptionCollection servers = uAClient.FindServers(serverUrl);

            foreach (ApplicationDescription ad in servers)
            {
                foreach (string url in ad.DiscoveryUrls)
                {
                    EndpointDescriptionCollection endpoints = uAClient.GetEndpoints(url);
                    foreach (EndpointDescription ep in endpoints)
                    {
                        string      securityPolicy = ep.SecurityPolicyUri.Remove(0, 42);
                        EndpointDes endpointDes    = new EndpointDes()
                        {
                            ID                     = Guid.NewGuid().ToString(),
                            Description            = "[" + ad.ApplicationName + "] " + " [" + ep.SecurityMode + "] " + " [" + securityPolicy + "] " + " [" + ep.EndpointUrl + "]",
                            OpcEndpointDescription = ep
                        };
                        endpointListView.Add(endpointDes);
                        _EndpointDescriptions.Add(endpointDes.ID, endpointDes);
                    }
                }
            }
            return(endpointListView);
        }
示例#4
0
        private void EndpointButton_Click(object sender, EventArgs e)
        {
            endpointListView.Items.Clear();
            //The local discovery URL for the discovery server
            string discoveryUrl = discoveryTextBox.Text;

            try
            {
                ApplicationDescriptionCollection servers = myClientHelperAPI.FindServers(discoveryUrl);
                foreach (ApplicationDescription ad in servers)
                {
                    foreach (string url in ad.DiscoveryUrls)
                    {
                        EndpointDescriptionCollection endpoints = myClientHelperAPI.GetEndpoints(url);
                        foreach (EndpointDescription ep in endpoints)
                        {
                            string securityPolicy = ep.SecurityPolicyUri.Remove(0, 42);
                            endpointListView.Items.Add("[" + ad.ApplicationName + "] " + " [" + ep.SecurityMode + "] " + " [" + securityPolicy + "] " + " [" + ep.EndpointUrl + "]").Tag = ep;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (BGW_OPCUA.IsBusy)
                {
                    BGW_OPCUA.CancelAsync();
                }
                MessageBox.Show(ex.Message, "Error");
            }
        }
示例#5
0
        /// <summary>
        /// Updates the list of servers displayed in the control.
        /// </summary>
        private void OnUpdateServers(object state)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new WaitCallback(OnUpdateServers), state);
                return;
            }

            ItemsLV.Items.Clear();

            ApplicationDescriptionCollection servers = state as ApplicationDescriptionCollection;

            if (servers != null)
            {
                foreach (ApplicationDescription server in servers)
                {
                    if (server.ApplicationType == ApplicationType.DiscoveryServer)
                    {
                        continue;
                    }

                    AddItem(server);
                }
            }

            if (ItemsLV.Items.Count == 0)
            {
                this.Instructions = Utils.Format("No servers to display.");
            }

            AdjustColumns();
        }
示例#6
0
        /// <summary>
        /// Fetches the servers from the discovery server.
        /// </summary>
        private bool DiscoverServers(Uri discoveryUrl)
        {
            // use a short timeout.
            EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration);

            configuration.OperationTimeout = m_discoveryTimeout;

            DiscoveryClient client = null;

            try
            {
                client = DiscoveryClient.Create(
                    discoveryUrl,
                    BindingFactory.Create(m_configuration, m_configuration.CreateMessageContext()),
                    EndpointConfiguration.Create(m_configuration));

                ApplicationDescriptionCollection servers = client.FindServers(null);
                m_discoveryUrl = discoveryUrl.ToString();
                OnUpdateServers(servers);
                return(true);
            }
            catch (Exception e)
            {
                Utils.Trace("DISCOVERY ERROR - Could not fetch servers from url: {0}. Error=({2}){1}", discoveryUrl, e.Message, e.GetType());
                return(false);
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }
        }
示例#7
0
        private void DiscoveryB_Click(object sender, EventArgs e)
        {
            bool foundEndpoints = false;

            DiscoveredServersLV.Items.Clear();

            //Create discovery URL for the discovery client
            string serverUrl = null;

            if (!String.IsNullOrEmpty(DiscoveryUrlTB.Text) & !String.IsNullOrEmpty(DiscoveryPortTB.Text))
            {
                serverUrl = "opc.tcp://" + DiscoveryUrlTB.Text + ":" + DiscoveryPortTB.Text;
            }
            else if (String.IsNullOrEmpty(DiscoveryUrlTB.Text) & !String.IsNullOrEmpty(DiscoveryPortTB.Text))
            {
                serverUrl = "opc.tcp://localhost:" + DiscoveryPortTB.Text;
            }
            else if (!String.IsNullOrEmpty(DiscoveryUrlTB.Text) & String.IsNullOrEmpty(DiscoveryPortTB.Text))
            {
                serverUrl = "opc.tcp://" + DiscoveryUrlTB.Text + ":" + "4840";
            }
            else
            {
                serverUrl = "opc.tcp://localhost:4840";
            }

            //Get the endpoints
            try
            {
                ApplicationDescriptionCollection servers = myHelperApi.FindServers(serverUrl);
                foreach (ApplicationDescription ad in servers)
                {
                    foreach (string url in ad.DiscoveryUrls)
                    {
                        EndpointDescriptionCollection endpoints = myHelperApi.GetEndpoints(url);
                        foundEndpoints = foundEndpoints || endpoints.Count > 0;
                        foreach (EndpointDescription ep in endpoints)
                        {
                            string securityPolicy = ep.SecurityPolicyUri.Remove(0, 43);
                            if (!DiscoveredServersLV.Items.ContainsKey(ep.Server.ApplicationName.Text))
                            {
                                string[]     row          = { ep.Server.ApplicationName.Text, ep.EndpointUrl, ep.SecurityMode + "-" + securityPolicy };
                                ListViewItem listViewItem = new ListViewItem(row);
                                DiscoveredServersLV.Items.Add(listViewItem).Tag = ep;
                                DiscoveredServersLV.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                            }
                        }
                    }
                    if (!foundEndpoints)
                    {
                        MessageBox.Show("Could not get any Endpoints", "Error");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
示例#8
0
        /// <summary>
        /// Gets the endpoints for the host.
        /// </summary>
        /// <param name="hostName">Name of the host.</param>
        private string[] GetEndpoints(string hostName)
        {
            List <string> urls = new List <string>();

            try
            {
                Cursor = Cursors.WaitCursor;

                // set a short timeout because this is happening in the drop down event.
                EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration);
                configuration.OperationTimeout = 20000;

                // Connect to the local discovery server and find the available servers.
                using (DiscoveryClient client = DiscoveryClient.Create(new Uri(Utils.Format("opc.tcp://{0}:4840", hostName)), configuration))
                {
                    ApplicationDescriptionCollection servers = client.FindServers(null);

                    // populate the drop down list with the discovery URLs for the available servers.
                    for (int ii = 0; ii < servers.Count; ii++)
                    {
                        // don't show discovery servers.
                        if (servers[ii].ApplicationType == ApplicationType.DiscoveryServer)
                        {
                            continue;
                        }

                        for (int jj = 0; jj < servers[ii].DiscoveryUrls.Count; jj++)
                        {
                            string discoveryUrl = servers[ii].DiscoveryUrls[jj];

                            // Many servers will use the '/discovery' suffix for the discovery endpoint.
                            // The URL without this prefix should be the base URL for the server.
                            if (discoveryUrl.EndsWith("/discovery"))
                            {
                                discoveryUrl = discoveryUrl.Substring(0, discoveryUrl.Length - "/discovery".Length);
                            }

                            // remove duplicates.
                            if (!urls.Contains(discoveryUrl))
                            {
                                urls.Add(discoveryUrl);
                            }
                        }
                    }
                }

                return(urls.ToArray());
            }
            catch (Exception)
            {
                return(urls.ToArray());
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
示例#9
0
        public BrowseMachine_Result BrowseLocalDiscoveryServer_UA(string Host, int Port)
        {
            List <string> serverUrls = new List <string>();

            List <OPCServerNode> OPCServers = new List <OPCServerNode>();

            try
            {
                EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(_Config);
                endpointConfiguration.OperationTimeout = 25000;
                using (DiscoveryClient client = DiscoveryClient.Create(new Uri("opc.tcp://" + Host + ":" + Port), endpointConfiguration))
                {
                    ApplicationDescriptionCollection servers = client.FindServers(null);
                    for (int ii = 0; ii < servers.Count; ii++)
                    {
                        if (servers[ii].ApplicationType == ApplicationType.DiscoveryServer)
                        {
                            continue;
                        }
                        for (int jj = 0; jj < servers[ii].DiscoveryUrls.Count; jj++)
                        {
                            string discoveryUrl = servers[ii].DiscoveryUrls[jj];

                            // Many servers will use the '/discovery' suffix for the discovery endpoint.
                            // The URL without this prefix should be the base URL for the server.
                            if (discoveryUrl.EndsWith("/discovery"))
                            {
                                discoveryUrl = discoveryUrl.Substring(0, discoveryUrl.Length - "/discovery".Length);
                            }

                            // ensure duplicates do not get added.
                            if (!serverUrls.Contains(discoveryUrl))
                            {
                                if (discoveryUrl.StartsWith("http"))
                                {
                                    continue;
                                }
                                OPCServers.Add(new OPCServerNode(discoveryUrl, discoveryUrl, OPCSpecification.UA_10));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(new BrowseMachine_Result()
                {
                    success = false, result = null, error = ex.ToString()
                });
            }
            return(new BrowseMachine_Result()
            {
                success = true, result = OPCServers
            });
        }
示例#10
0
        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);
            }
        }
示例#11
0
 protected void GetEnpoints_Click(object sender, EventArgs e)
 {
     if (discoveryTextBox.Text != "")
     {
         bool foundEndpoints = false;
         endpointListView.Items.Clear();
         Session["Urltext"] = discoveryTextBox.Text;
         //The local discovery URL for the discovery server
         string discoveryUrl = discoveryTextBox.Text;
         try
         {
             ApplicationDescriptionCollection servers = myClientHelperAPI.FindServers(discoveryUrl);
             foreach (ApplicationDescription ad in servers)
             {
                 foreach (string url in ad.DiscoveryUrls)
                 {
                     try
                     {
                         EndpointDescriptionCollection endpoints = myClientHelperAPI.GetEndpoints(url);
                         foundEndpoints = foundEndpoints || endpoints.Count > 0;
                         List <string> enps = new List <string>();
                         foreach (EndpointDescription ep in endpoints)
                         {
                             string securityPolicy = ep.SecurityPolicyUri.Remove(0, 42);
                             string key            = "[" + ad.ApplicationName + "] " + " [" + ep.SecurityMode + "] " + " [" + securityPolicy + "] " + " [" + ep.EndpointUrl + "]";
                             enps.Add(key);
                             endpointListView.Items.Add(key);
                         }
                         Session["endpointlist"] = enps;
                     }
                     catch (ServiceResultException sre)
                     {
                         //If an url in ad.DiscoveryUrls can not be reached, myClientHelperAPI will throw an Exception
                         ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('error','Oops...'," + sre.ToString() + ")", true);
                     }
                 }
                 if (!foundEndpoints)
                 {
                     ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('warning','Oops...','Could not get any Endpoints!')", true);
                 }
             }
         }
         catch (Exception ex)
         {
             ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('error','Oops...'," + ex.ToString() + ")", true);
         }
     }
     else
     {
         ClientScript.RegisterStartupScript(this.GetType(), "Alert", "mess('warning','Warning...','You forget write endpoint Url!')", true);
     }
 }
        /// <summary>
        /// Invokes the FindServers service.
        /// </summary>
        /// <param name="serverUris">The collection of server URIs.</param>
        /// <returns></returns>
        public virtual ApplicationDescriptionCollection FindServers(StringCollection serverUris)
        {
            ApplicationDescriptionCollection servers = null;

            FindServers(
                null,
                this.Endpoint.EndpointUrl,
                null,
                serverUris,
                out servers);

            return(servers);
        }
示例#13
0
        //private ApplicationConfiguration m_configuration;
        private void GetEndpoints()
        {
            try
            {
                // set a short timeout because this is happening in the drop down event.
                EndpointConfiguration configuration = EndpointConfiguration.Create();
                configuration.OperationTimeout = 20000;

                // Connect to the local discovery server and find the available servers.
                using (DiscoveryClient client = DiscoveryClient.Create(new Uri(Utils.Format("opc.tcp://{0}:4840", MyBaseThing.Address)), configuration))
                {
                    ApplicationDescriptionCollection servers = client.FindServers(null);

                    // populate the drop down list with the discovery URLs for the available servers.
                    for (int ii = 0; ii < servers.Count; ii++)
                    {
                        // don't show discovery servers.
                        if (servers[ii].ApplicationType == ApplicationType.DiscoveryServer)
                        {
                            continue;
                        }

                        for (int jj = 0; jj < servers[ii].DiscoveryUrls.Count; jj++)
                        {
                            string discoveryUrl = servers[ii].DiscoveryUrls[jj];

                            // Many servers will use the '/discovery' suffix for the discovery endpoint.
                            // The URL without this prefix should be the base URL for the server.
                            if (discoveryUrl.EndsWith("/discovery"))
                            {
                                discoveryUrl = discoveryUrl.Substring(0, discoveryUrl.Length - "/discovery".Length);
                            }

                            TheThing tDev = TheThingRegistry.GetThingByFunc(MyBaseEngine.GetEngineName(), s => s.GetProperty("Address", false).ToString() == discoveryUrl);
                            if (tDev == null)
                            {
                                TheOPCUARemoteServer tS = new TheOPCUARemoteServer(null, this, discoveryUrl);
                                TheThingRegistry.RegisterThing(tS);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
            }
        }
示例#14
0
        public override ResponseHeader FindServers(RequestHeader requestHeader, string endpointUrl, StringCollection localeIds, StringCollection serverUris, out ApplicationDescriptionCollection servers)
        {
            lock (_ServerLock)
            {
                servers = new ApplicationDescriptionCollection(_Cache.OfType <ApplicationDescription>());

                ResponseHeader responseHeader = new ResponseHeader();

                responseHeader.Timestamp     = DateTime.UtcNow;
                responseHeader.RequestHandle = requestHeader.RequestHandle;
                responseHeader.ServiceResult = new StatusCode(StatusCodes.Good);

                return(responseHeader);
            }
        }
示例#15
0
        /// <summary>
        /// Returns a list of OPC UA servers.
        /// </summary>
        /// <param name="discoveryUrl">The discovery URL.</param>
        /// <param name="servers">The servers being found.</param>
        public void FindServers(Uri discoveryUrl, ref ApplicationDescriptionCollection servers)
        {
            try
            {
                // Create Discovery Client.
                DiscoveryClient client = DiscoveryClient.Create(discoveryUrl);

                // Look for servers.
                servers = client.FindServers(null);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#16
0
        /// <summary>
        /// Invokes the FindServers service.
        /// </summary>
        public virtual ResponseHeader FindServers(
            RequestHeader requestHeader,
            string endpointUrl,
            StringCollection localeIds,
            StringCollection serverUris,
            out ApplicationDescriptionCollection servers)
        {
            servers = null;

            ValidateRequest(requestHeader);

            // Insert implementation.

            return(CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported));
        }
示例#17
0
        /// <summary>
        /// 发现服务(由客户端请求)
        /// </summary>
        /// <param name="requestHeader"></param>
        /// <param name="endpointUrl"></param>
        /// <param name="localeIds"></param>
        /// <param name="serverUris"></param>
        /// <param name="servers"></param>
        /// <returns></returns>
        public override ResponseHeader FindServers(
            RequestHeader requestHeader,
            string endpointUrl,
            StringCollection localeIds,
            StringCollection serverUris,
            out ApplicationDescriptionCollection servers)
        {
            servers = new ApplicationDescriptionCollection();

            ValidateRequest(requestHeader);

            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":请求查找服务...");
            string hostName = Dns.GetHostName();

            lock (_serverTable)
            {
                foreach (var item in _serverTable)
                {
                    StringCollection urls = new StringCollection();
                    foreach (var url in item.DiscoveryUrls)
                    {
                        if (url.Contains("localhost"))
                        {
                            string str = url.Replace("localhost", hostName);
                            urls.Add(str);
                        }
                        else
                        {
                            urls.Add(url);
                        }
                    }

                    servers.Add(new ApplicationDescription()
                    {
                        ApplicationName     = item.ServerNames.FirstOrDefault(),
                        ApplicationType     = item.ServerType,
                        ApplicationUri      = item.ServerUri,
                        DiscoveryProfileUri = item.SemaphoreFilePath,
                        DiscoveryUrls       = urls,
                        ProductUri          = item.ProductUri,
                        GatewayServerUri    = item.GatewayServerUri
                    });
                }
            }

            return(CreateResponse(requestHeader, StatusCodes.Good));
        }
示例#18
0
        /// <summary>
        /// Discovers the servers on the local machine.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="discoverTimeout">Operation timeout in milliseconds.</param>
        /// <returns>A list of server urls.</returns>
        public static IList <string> DiscoverServers(
            ApplicationConfiguration configuration,
            int discoverTimeout
            )
        {
            List <string> serverUrls = new List <string>();

            // set a short timeout because this is happening in the drop down event.
            var endpointConfiguration = EndpointConfiguration.Create(configuration);

            endpointConfiguration.OperationTimeout = discoverTimeout;

            // Connect to the local discovery server and find the available servers.
            using (DiscoveryClient client = DiscoveryClient.Create(new Uri(String.Format(Utils.DiscoveryUrls[0], "localhost")), endpointConfiguration))
            {
                ApplicationDescriptionCollection servers = client.FindServers(null);

                // populate the drop down list with the discovery URLs for the available servers.
                for (int ii = 0; ii < servers.Count; ii++)
                {
                    if (servers[ii].ApplicationType == ApplicationType.DiscoveryServer)
                    {
                        continue;
                    }

                    for (int jj = 0; jj < servers[ii].DiscoveryUrls.Count; jj++)
                    {
                        string discoveryUrl = servers[ii].DiscoveryUrls[jj];

                        // Many servers will use the '/discovery' suffix for the discovery endpoint.
                        // The URL without this prefix should be the base URL for the server.
                        if (discoveryUrl.EndsWith("/discovery"))
                        {
                            discoveryUrl = discoveryUrl.Substring(0, discoveryUrl.Length - "/discovery".Length);
                        }

                        // ensure duplicates do not get added.
                        if (!serverUrls.Contains(discoveryUrl))
                        {
                            serverUrls.Add(discoveryUrl);
                        }
                    }
                }
            }

            return(serverUrls);
        }
示例#19
0
        /// <summary>
        /// Event handlers called by the UI
        /// </summary>,
        #region UserInteractionHandlers
        private void EndpointButton_Click(object sender, EventArgs e)
        {
            bool foundEndpoints = false;

            endpointListView.Items.Clear();
            //The local discovery URL for the discovery server
            string discoveryUrl = discoveryTextBox.Text;

            try
            {
                ApplicationDescriptionCollection servers = myClientHelperAPI.FindServers(discoveryUrl);
                foreach (ApplicationDescription ad in servers)
                {
                    foreach (string url in ad.DiscoveryUrls)
                    {
                        try
                        {
                            EndpointDescriptionCollection endpoints = myClientHelperAPI.GetEndpoints(url);
                            foundEndpoints = foundEndpoints || endpoints.Count > 0;
                            foreach (EndpointDescription ep in endpoints)
                            {
                                string securityPolicy = ep.SecurityPolicyUri.Remove(0, 42);
                                string key            = "[" + ad.ApplicationName + "] " + " [" + ep.SecurityMode + "] " + " [" + securityPolicy + "] " + " [" + ep.EndpointUrl + "]";
                                if (!endpointListView.Items.ContainsKey(key))
                                {
                                    endpointListView.Items.Add(key, key, 0).Tag = ep;
                                }
                            }
                        }
                        catch (ServiceResultException sre)
                        {
                            //If an url in ad.DiscoveryUrls can not be reached, myClientHelperAPI will throw an Exception
                            MessageBox.Show(sre.Message, "Error");
                        }
                    }
                    if (!foundEndpoints)
                    {
                        MessageBox.Show("Could not get any Endpoints", "Error");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
        private void OnFindServersComplete(IAsyncResult result)
        {
            FindServersData data = result.AsyncState as FindServersData;

            try
            {
                ApplicationDescriptionCollection servers = null;
                data.DiscoveryClient.EndFindServers(result, out servers);

                data.Servers = servers;
                data.OperationCompleted();
            }
            catch (Exception e)
            {
                data.Exception = e;
                data.OperationCompleted();
            }
        }
示例#21
0
        /// <summary>Finds Servers based on a discovery url</summary>
        /// <param name="discoveryUrl">The discovery url</param>
        /// <returns>ApplicationDescriptionCollection containing found servers</returns>
        /// <exception cref="Exception">Throws and forwards any exception with short error description.</exception>
        public ApplicationDescriptionCollection FindServers(string discoveryUrl)
        {
            //Create a URI using the discovery URL
            Uri uri = new Uri(discoveryUrl);

            try
            {
                //Ceate a DiscoveryClient
                DiscoveryClient client = DiscoveryClient.Create(uri);
                //Find servers
                ApplicationDescriptionCollection servers = client.FindServers(null);
                return(servers);
            }
            catch (Exception e)
            {
                //handle Exception here
                throw e;
            }
        }
示例#22
0
        private ApplicationDescriptionCollection FindServers(string url)
        {
            ApplicationDescriptionCollection servers = null;

            //Create a URI using the discovery URL
            Uri uri = new Uri(url);

            try
            {
                //Ceate a DiscoveryClient
                DiscoveryClient client = DiscoveryClient.Create(uri);

                //Find servers
                servers = client.FindServers(null);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("OpcUaClient::FindServers" + ex.Message);
            }

            return(servers);
        }
        /// <summary>
        /// Updates the list of servers displayed in the control.
        /// </summary>
        private async void OnUpdateServers(object state)
        {
            if (!Dispatcher.HasThreadAccess)
            {
                await Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    () =>
                {
                    OnUpdateServers(state);
                });

                return;
            }

            ItemsLV.Items.Clear();

            ApplicationDescriptionCollection servers = state as ApplicationDescriptionCollection;

            if (servers != null)
            {
                foreach (ApplicationDescription server in servers)
                {
                    if (server.ApplicationType == ApplicationType.DiscoveryServer)
                    {
                        continue;
                    }

                    AddItem(server);
                }
            }

            if (ItemsLV.Items.Count == 0)
            {
                this.Instructions.Text = Utils.Format("No servers to display.");
            }
        }
示例#24
0
        /// <summary>
        /// Updates the list of servers displayed in the control.
        /// </summary>
        private void OnUpdateServers(object state)
        {
            ItemsLV.Items.Clear();

            ApplicationDescriptionCollection servers = state as ApplicationDescriptionCollection;

            if (servers != null)
            {
                foreach (ApplicationDescription server in servers)
                {
                    if (server.ApplicationType == ApplicationType.DiscoveryServer)
                    {
                        continue;
                    }

                    AddItem(server);
                }
            }

            if (ItemsLV.Items.Count == 0)
            {
                this.Instructions.Text = Utils.Format("No servers to display.");
            }
        }
示例#25
0
        private void UrlCB_DropDown(object sender, EventArgs e)
        {
            try
            {
                Uri discoveryUrl = null;


                // Create the uri from hostname.
                string sUrl = "opc.tcp://" + label1.Text + textBox1.Text + ":4840";

                // Has the port been entered by the user?



                // Create the uri itself.
                discoveryUrl = new Uri(sUrl);



                // Clear all items of the ComboBox.
                UrlCB.Items.Clear();
                UrlCB.Text = "";

                // Look for servers
                ApplicationDescriptionCollection servers = null;
                //Discovery discovery = new Discovery();

                servers = m_Server.FindServers(discoveryUrl.ToString());

                // Populate the drop down list with the endpoints for the available servers.
                for (int iServer = 0; iServer < servers.Count; iServer++)
                {
                    try
                    {
                        // Create discovery client and get the available endpoints.
                        EndpointDescriptionCollection endpoints = null;
                        sUrl         = servers[iServer].DiscoveryUrls[0];
                        discoveryUrl = new Uri(sUrl);

                        endpoints = m_Server.GetEndpoints(discoveryUrl.ToString());

                        // Create wrapper and fill the combobox.
                        for (int i = 0; i < endpoints.Count; i++)
                        {
                            // Create endpoint wrapper.
                            EndpointWrapper wrapper = new EndpointWrapper(endpoints[i]);

                            // Add it to the combobox.
                            UrlCB.Items.Add(wrapper);
                        }

                        // Update status label.
                        toolStripStatusLabel.Text = "GetEndpoints succeeded for " + servers[iServer].ApplicationName;
                        btn_Connect.Enabled       = true;
                    }
                    catch (Exception)
                    {
                        // Update status label.
                        toolStripStatusLabel.Text = "GetEndpoints failed for " + servers[iServer].ApplicationName;
                    }
                }
            }
            catch (Exception ex)
            {
                // Update status label.
                toolStripStatusLabel.Text = "FindServers failed:" + ex.ToString();
            }
        }
示例#26
0
        /// <summary>
        /// Expands the drop down list of the ComboBox to display available servers and endpoints.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void UrlCB_DropDown(object sender, EventArgs e)
        {
            try
            {
                Uri discoveryUrl = null;

                // Check the text property of the Server textbox
                if (NodeTB.Text.Length == 0)
                {
                    // Set the uri of the local discovery server by default.
                    discoveryUrl = new Uri("opc.tcp://localhost:48010");
                }
                else
                {
                    // Create the uri from hostname.
                    string sUrl;

                    // Has the port been entered by the user?
                    char     seperator    = ':';
                    string[] strPortCheck = NodeTB.Text.Split(seperator);
                    if (strPortCheck.Length > 1)
                    {
                        sUrl = "opc.tcp://" + NodeTB.Text;
                    }
                    else
                    {
                        sUrl = "opc.tcp://" + NodeTB.Text + ":48010";
                    }

                    // Create the uri itself.
                    discoveryUrl = new Uri(sUrl);
                }

                // Set wait cursor.
                Cursor = Cursors.WaitCursor;

                // Clear all items of the ComboBox.
                UrlCB.Items.Clear();
                UrlCB.Text = "";

                // Look for servers
                ApplicationDescriptionCollection servers = null;
                Discovery discovery = new Discovery();

                discovery.FindServers(discoveryUrl, ref servers);

                // Populate the drop down list with the endpoints for the available servers.
                for (int iServer = 0; iServer < servers.Count; iServer++)
                {
                    try
                    {
                        // Create discovery client and get the available endpoints.
                        EndpointDescriptionCollection endpoints = null;

                        string sUrl;
                        sUrl         = servers[iServer].DiscoveryUrls[0];
                        discoveryUrl = new Uri(sUrl);

                        discovery.GetEndpoints(discoveryUrl, ref endpoints);

                        // Create wrapper and fill the combobox.
                        for (int i = 0; i < endpoints.Count; i++)
                        {
                            // Create endpoint wrapper.
                            EndpointWrapper wrapper = new EndpointWrapper(endpoints[i]);

                            // Add it to the combobox.
                            UrlCB.Items.Add(wrapper);
                        }

                        // Update status label.
                        toolStripStatusLabel.Text  = "GetEndpoints succeeded for " + servers[iServer].ApplicationName;
                        toolStripStatusLabel.Image = global::Siemens.OpcUA.Client.Properties.Resources.success;
                    }
                    catch (Exception)
                    {
                        // Update status label.
                        toolStripStatusLabel.Text  = "GetEndpoints failed for " + servers[iServer].ApplicationName;
                        toolStripStatusLabel.Image = global::Siemens.OpcUA.Client.Properties.Resources.error;
                    }
                }

                // Set default cursor.
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                // Update status label.
                toolStripStatusLabel.Text  = "FindServers failed:" + ex.ToString();
                toolStripStatusLabel.Image = global::Siemens.OpcUA.Client.Properties.Resources.error;
            }
        }
        /// <summary>
        /// Invokes the FindServers service.
        /// </summary>
        public virtual ResponseHeader FindServers(
            RequestHeader                        requestHeader,
            string                               endpointUrl,
            StringCollection                     localeIds,
            StringCollection                     serverUris,
            out ApplicationDescriptionCollection servers)
        {
            servers = null;

            ValidateRequest(requestHeader);

            // Insert implementation.

            return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported);
        }
        /// <summary>
        /// Invokes the FindServers service.
        /// </summary>
        /// <param name="requestHeader">The request header.</param>
        /// <param name="endpointUrl">The endpoint URL.</param>
        /// <param name="localeIds">The locale ids.</param>
        /// <param name="serverUris">The server uris.</param>
        /// <param name="servers">List of Servers that meet criteria specified in the request.</param>
        /// <returns>
        /// Returns a <see cref="ResponseHeader"/> object
        /// </returns>
        public override ResponseHeader FindServers(
            RequestHeader                        requestHeader,
            string                               endpointUrl,
            StringCollection                     localeIds,
            StringCollection                     serverUris,
            out ApplicationDescriptionCollection servers)
        {
            servers = new ApplicationDescriptionCollection();
            
            ValidateRequest(requestHeader);
            
            lock (m_lock)
            {
                // parse the url provided by the client.
                IList<BaseAddress> baseAddresses = BaseAddresses;

                Uri parsedEndpointUrl = Utils.ParseUri(endpointUrl);

                if (parsedEndpointUrl != null)
                {
                    baseAddresses = FilterByEndpointUrl(parsedEndpointUrl, baseAddresses);
                }

                // check if nothing to do.
                if (baseAddresses.Count == 0)
                {
                    servers = new ApplicationDescriptionCollection();
                    return CreateResponse(requestHeader, StatusCodes.Good);
                }

                // build list of unique servers.
                Dictionary<string,ApplicationDescription> uniqueServers = new Dictionary<string,ApplicationDescription>();

                foreach (EndpointDescription description in GetEndpoints())
                {
                    ApplicationDescription server = description.Server;

                    // skip servers that have been processed.
                    if (uniqueServers.ContainsKey(server.ApplicationUri))
                    {
                        continue;
                    }

                    // check client is filtering by server uri.
                    if (serverUris != null && serverUris.Count > 0)
                    {
                        if (!serverUris.Contains(server.ApplicationUri))
                        {
                            continue;
                        }
                    }

                    // localize the application name if requested.
                    LocalizedText applicationName = server.ApplicationName;

                    if (localeIds != null && localeIds.Count > 0)
                    {
                        applicationName = m_serverInternal.ResourceManager.Translate(localeIds, applicationName);
                    }

                    // get the application description.
                    ApplicationDescription application = TranslateApplicationDescription(
                        parsedEndpointUrl,
                        server,
                        baseAddresses,
                        applicationName);

                    uniqueServers.Add(server.ApplicationUri, application);

                    // add to list of servers to return.
                    servers.Add(application);
                }
            }
                            
            return CreateResponse(requestHeader, StatusCodes.Good);
        }
示例#29
0
        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);
            }
        }
示例#30
0
        /// <summary>
        /// Invokes the FindServers service.
        /// </summary>
        public virtual ResponseHeader FindServers(
            RequestHeader                        requestHeader,
            string                               endpointUrl,
            StringCollection                     localeIds,
            StringCollection                     serverUris,
            out ApplicationDescriptionCollection servers)
        {
            FindServersRequest request = new FindServersRequest();
            FindServersResponse response = null;

            request.RequestHeader = requestHeader;
            request.EndpointUrl   = endpointUrl;
            request.LocaleIds     = localeIds;
            request.ServerUris    = serverUris;

            UpdateRequestHeader(request, requestHeader == null, "FindServers");

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.SendRequest(request);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (FindServersResponse)genericResponse;
                }
                else
                {
                    FindServersResponseMessage responseMessage = InnerChannel.FindServers(new FindServersMessage(request));

                    if (responseMessage == null || responseMessage.FindServersResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.FindServersResponse;
                    ValidateResponse(response.ResponseHeader);
                }

                servers = response.Servers;
            }
            finally
            {
                RequestCompleted(request, response, "FindServers");
            }

            return response.ResponseHeader;
        }
示例#31
0
        /// <summary>
        /// Finishes an asynchronous invocation of the FindServers service.
        /// </summary>
        public ResponseHeader EndFindServers(
            IAsyncResult                         result,
            out ApplicationDescriptionCollection servers)
        {
            FindServersResponse response = null;

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.EndSendRequest(result);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (FindServersResponse)genericResponse;
                }
                else
                {
                    FindServersResponseMessage responseMessage = InnerChannel.EndFindServers(result);

                    if (responseMessage == null || responseMessage.FindServersResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.FindServersResponse;
                    ValidateResponse(response.ResponseHeader);
                }

                servers = response.Servers;
            }
            finally
            {
                RequestCompleted(null, response, "FindServers");
            }

            return response.ResponseHeader;
        }