Exemplo n.º 1
0
        public void TranslateBrowsePathsToNodeIdsAsyncNull()
        {
            var response = new TranslateBrowsePathsToNodeIdsResponse();
            var channel  = new TestRequestChannel(response);

            channel.Invoking(c => c.TranslateBrowsePathsToNodeIdsAsync(null))
            .Should().Throw <ArgumentNullException>();
        }
Exemplo n.º 2
0
        public async Task TranslateBrowsePathsToNodeIdsAsync()
        {
            var response = new TranslateBrowsePathsToNodeIdsResponse();
            var request  = new TranslateBrowsePathsToNodeIdsRequest();
            var channel  = new TestRequestChannel(response);

            var ret = await channel.TranslateBrowsePathsToNodeIdsAsync(request);

            ret
            .Should().BeSameAs(response);

            channel.Request
            .Should().BeSameAs(request);
        }
Exemplo n.º 3
0
        public async Task <TranslateBrowsePathsToNodeIdsResponse> TranslateBrowsePathsToNodeIdsAsync(TranslateBrowsePathsToNodeIdsRequest translateRequest)
        {
            UpdateRequestHeader(translateRequest, true, "TranslateBrowsePathsToNodeIds");
            TranslateBrowsePathsToNodeIdsResponse translateResponse = null;

            try
            {
                if (UseTransportChannel)
                {
                    var serviceResponse = await Task <IServiceResponse> .Factory.FromAsync(TransportChannel.BeginSendRequest, TransportChannel.EndSendRequest, translateRequest, null).ConfigureAwait(false);

                    if (serviceResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }
                    ValidateResponse(serviceResponse.ResponseHeader);
                    translateResponse = (TranslateBrowsePathsToNodeIdsResponse)serviceResponse;
                }
                else
                {
                    var browseResponseMessage = await Task <TranslateBrowsePathsToNodeIdsResponseMessage> .Factory.FromAsync(InnerChannel.BeginTranslateBrowsePathsToNodeIds, InnerChannel.EndTranslateBrowsePathsToNodeIds, new TranslateBrowsePathsToNodeIdsMessage(translateRequest), null).ConfigureAwait(false);

                    if (browseResponseMessage == null || browseResponseMessage.TranslateBrowsePathsToNodeIdsResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }
                    translateResponse = browseResponseMessage.TranslateBrowsePathsToNodeIdsResponse;
                    ValidateResponse(translateResponse.ResponseHeader);
                }
            }
            finally
            {
                RequestCompleted(translateRequest, translateResponse, "TranslateBrowsePathsToNodeIds");
            }
            return(translateResponse);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Invokes the TranslateBrowsePathsToNodeIds service.
        /// </summary>
        public IServiceResponse TranslateBrowsePathsToNodeIds(IServiceRequest incoming)
        {
            TranslateBrowsePathsToNodeIdsResponse response = null;

            TranslateBrowsePathsToNodeIdsRequest request = (TranslateBrowsePathsToNodeIdsRequest)incoming;

            BrowsePathResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            response = new TranslateBrowsePathsToNodeIdsResponse();

            response.ResponseHeader = ServerInstance.TranslateBrowsePathsToNodeIds(
               request.RequestHeader,
               request.BrowsePaths,
               out results,
               out diagnosticInfos);

            response.Results         = results;
            response.DiagnosticInfos = diagnosticInfos;

            return response;
        }
Exemplo n.º 5
0
        private async Task <bool> TryConnect()
        {
            if (connection != null)
            {
                return(true);
            }

            if (config == null || string.IsNullOrEmpty(config.Address))
            {
                lastConnectErrMsg = "No address configured";
                return(false);
            }

            try {
                if (certificateStore == null)
                {
                    var pkiPath = Path.Combine(
                        Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                        "ifakFAST.IO.OPC_UA",
                        "pki");

                    Console.WriteLine($"Location of OPC UA certificate store: {pkiPath}");

                    certificateStore    = new DirectoryStore(pkiPath, acceptAllRemoteCertificates: true, createLocalCertificateIfNotExist: true);
                    certificateLocation = Path.Combine(pkiPath, "own", "certs");
                }

                const string Config_Security = "Security";
                string       sec             = "None";
                if (config.Config.Any(nv => nv.Name == Config_Security))
                {
                    sec = config.Config.First(nv => nv.Name == Config_Security).Value;
                }

                var mapSecurityPolicies = new Dictionary <string, string>()
                {
                    { "None", SecurityPolicyUris.None },
                    { "Basic128Rsa15", SecurityPolicyUris.Basic128Rsa15 },
                    { "Basic256", SecurityPolicyUris.Basic256 },
                    { "Https", SecurityPolicyUris.Https },
                    { "Basic256Sha256", SecurityPolicyUris.Basic256Sha256 },
                    { "Aes128_Sha256_RsaOaep", SecurityPolicyUris.Aes128_Sha256_RsaOaep },
                    { "Aes256_Sha256_RsaPss", SecurityPolicyUris.Aes256_Sha256_RsaPss },
                };

                if (!mapSecurityPolicies.ContainsKey(sec))
                {
                    string[] keys    = mapSecurityPolicies.Keys.ToArray();
                    string   strKeys = string.Join(", ", keys);
                    throw new Exception($"Invalid value for config setting '{Config_Security}': {sec}. Expected any of: {strKeys}");
                }

                var endpoint = new EndpointDescription {
                    EndpointUrl       = config.Address,
                    SecurityPolicyUri = mapSecurityPolicies[sec],
                };

                IUserIdentity identity = GetIdentity();

                var channel = new UaTcpSessionChannel(
                    localDescription: appDescription,
                    certificateStore: certificateStore,
                    userIdentity: identity,
                    remoteEndpoint: endpoint);

                await channel.OpenAsync();

                this.connection   = channel;
                lastConnectErrMsg = "";

                PrintLine($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
                PrintLine($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
                PrintLine($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
                PrintLine($"UserIdentityToken: '{channel.UserIdentity}'.");

                ItemInfo[] nodesNeedingResolve = mapId2Info.Values.Where(n => n.Node == null).ToArray();
                if (nodesNeedingResolve.Length > 0)
                {
                    PrintLine($"Resolving node ids for {nodesNeedingResolve.Length} items...");

                    TranslateBrowsePathsToNodeIdsRequest req = new TranslateBrowsePathsToNodeIdsRequest()
                    {
                        BrowsePaths = nodesNeedingResolve.Select(n => new BrowsePath()
                        {
                            StartingNode = n.StartingNode,
                            RelativePath = n.RelativePath
                        }).ToArray()
                    };
                    TranslateBrowsePathsToNodeIdsResponse resp = await connection.TranslateBrowsePathsToNodeIdsAsync(req);

                    if (resp.Results == null || resp.Results.Length != nodesNeedingResolve.Length)
                    {
                        LogWarn("Mismatch", "TranslateBrowsePathsToNodeIds failed");
                    }
                    else
                    {
                        for (int i = 0; i < resp.Results.Length; ++i)
                        {
                            BrowsePathResult?x = resp.Results[i];
                            if (x != null && StatusCode.IsGood(x.StatusCode) && x.Targets != null && x.Targets.Length > 0)
                            {
                                BrowsePathTarget?target = x.Targets[0];
                                if (target != null && target.TargetId != null)
                                {
                                    NodeId id = target.TargetId.NodeId;
                                    nodesNeedingResolve[i].Node = id;
                                    PrintLine($"Resolved item '{nodesNeedingResolve[i].Name}' => {id}");
                                }
                                else
                                {
                                    PrintLine($"Could not resolve item '{nodesNeedingResolve[i].Name}': StatusCode: {x.StatusCode}");
                                }
                            }
                            else
                            {
                                string statusCode = x == null ? "?" : x.StatusCode.ToString();
                                PrintLine($"Could not resolve item '{nodesNeedingResolve[i].Name}': StatusCode: {statusCode}");
                            }
                        }
                    }
                }
                ReturnToNormal("OpenChannel", $"Connected to OPC UA server at {config.Address}");
                return(true);
            }
            catch (Exception exp) {
                Exception baseExp = exp.GetBaseException() ?? exp;
                lastConnectErrMsg = baseExp.Message;
                LogWarn("OpenChannel", "Open channel error: " + baseExp.Message, dataItem: null, details: baseExp.StackTrace);
                await CloseChannel();

                return(false);
            }
        }
Exemplo n.º 6
0
        private async Task <bool> TryConnect()
        {
            if (connection != null)
            {
                return(true);
            }

            if (string.IsNullOrEmpty(config.Address))
            {
                return(false);
            }

            try {
                var getEndpointsRequest = new GetEndpointsRequest {
                    EndpointUrl = config.Address,
                    ProfileUris = new[] { TransportProfileUris.UaTcpTransport }
                };

                GetEndpointsResponse endpoints = await UaTcpDiscoveryService.GetEndpointsAsync(getEndpointsRequest);

                EndpointDescription[] noSecurityEndpoints = endpoints.Endpoints.Where(e => e.SecurityPolicyUri == SecurityPolicyUris.None).ToArray();

                var(endpoint, userIdentity) = FirstEndpointWithLogin(noSecurityEndpoints);

                if (endpoint == null || userIdentity == null)
                {
                    throw new Exception("No matching endpoint");
                }

                var channel = new UaTcpSessionChannel(
                    this.appDescription,
                    null,
                    userIdentity,
                    endpoint,
                    loggerFactory);

                await channel.OpenAsync();

                this.connection = channel;

                PrintLine($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
                PrintLine($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
                PrintLine($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
                PrintLine($"UserIdentityToken: '{channel.UserIdentity}'.");

                ItemInfo[] nodesNeedingResolve = mapId2Info.Values.Where(n => n.Node == null).ToArray();
                if (nodesNeedingResolve.Length > 0)
                {
                    PrintLine($"Resolving node ids for {nodesNeedingResolve.Length} items...");

                    TranslateBrowsePathsToNodeIdsRequest req = new TranslateBrowsePathsToNodeIdsRequest()
                    {
                        BrowsePaths = nodesNeedingResolve.Select(n => new BrowsePath()
                        {
                            StartingNode = n.StartingNode,
                            RelativePath = n.RelativePath
                        }).ToArray()
                    };
                    TranslateBrowsePathsToNodeIdsResponse resp = await connection.TranslateBrowsePathsToNodeIdsAsync(req);

                    if (resp.Results.Length != nodesNeedingResolve.Length)
                    {
                        LogWarn("Mismatch", "TranslateBrowsePathsToNodeIds failed");
                    }
                    else
                    {
                        for (int i = 0; i < resp.Results.Length; ++i)
                        {
                            BrowsePathResult x = resp.Results[i];
                            if (StatusCode.IsGood(x.StatusCode) && x.Targets.Length > 0)
                            {
                                NodeId id = x.Targets[0].TargetId.NodeId;
                                nodesNeedingResolve[i].Node = id;
                                PrintLine($"Resolved item '{nodesNeedingResolve[i].Name}' => {id}");
                            }
                            else
                            {
                                PrintLine($"Could not resolve item '{nodesNeedingResolve[i].Name}'!");
                            }
                        }
                    }
                }
                return(true);
            }
            catch (Exception exp) {
                Exception baseExp = exp.GetBaseException() ?? exp;
                LogWarn("OpenChannel", "Open channel error: " + baseExp.Message, dataItem: null, details: baseExp.StackTrace);
                await CloseChannel();

                return(false);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes the message with a service fault.
        /// </summary>
        public TranslateBrowsePathsToNodeIdsResponseMessage(ServiceFault ServiceFault)
        {
            this.TranslateBrowsePathsToNodeIdsResponse = new TranslateBrowsePathsToNodeIdsResponse();

            if (ServiceFault != null)
            {
                this.TranslateBrowsePathsToNodeIdsResponse.ResponseHeader = ServiceFault.ResponseHeader;
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// Initializes the message with the body.
 /// </summary>
 public TranslateBrowsePathsToNodeIdsResponseMessage(TranslateBrowsePathsToNodeIdsResponse TranslateBrowsePathsToNodeIdsResponse)
 {
     this.TranslateBrowsePathsToNodeIdsResponse = TranslateBrowsePathsToNodeIdsResponse;
 }
Exemplo n.º 9
0
        /// <summary cref="IServiceMessage.CreateResponse" />
        public object CreateResponse(IServiceResponse response)
        {
            TranslateBrowsePathsToNodeIdsResponse body = response as TranslateBrowsePathsToNodeIdsResponse;

            if (body == null)
            {
                body = new TranslateBrowsePathsToNodeIdsResponse();
                body.ResponseHeader = ((ServiceFault)response).ResponseHeader;
            }

            return new TranslateBrowsePathsToNodeIdsResponseMessage(body);
        }