public static LogEntry For(TranslateBrowsePathsToNodeIdsRequest request) { LogEntry entry = new LogEntry("TranslateBrowsePathsToNodeIdsRequest"); entry.Add("RequestHeader", For(request.RequestHeader)); entry.Add("BrowsePaths", For(request.BrowsePaths)); return(entry); }
internal static async Task <Tuple <Argument[], Argument[]> > GetMethodArgumentsFromNodeId(this UaSession session, NodeId nodeId) { var inputArguments = new Argument[0]; var outputArguments = new Argument[0]; var translateRequest = new TranslateBrowsePathsToNodeIdsRequest { BrowsePaths = { new BrowsePath { StartingNode = nodeId, RelativePath = new RelativePath(ReferenceTypeIds.HasProperty, "InputArguments") }, new BrowsePath{ StartingNode = nodeId, RelativePath = new RelativePath(ReferenceTypeIds.HasProperty, "OutputArguments") } } }; var translateResponse = await session.TranslateBrowsePathsToNodeIdsAsync(translateRequest); if (StatusCode.IsGood(translateResponse.Results[0].StatusCode) && translateResponse.Results[0].Targets.Count > 0) { var argNodeId = ExpandedNodeId.ToNodeId(translateResponse.Results[0].Targets[0].TargetId, session.NamespaceUris); var readRequest = new ReadRequest { NodesToRead = { new ReadValueId { NodeId = argNodeId, AttributeId = Attributes.Value } } }; var readResponse = await session.ReadAsync(readRequest); if (StatusCode.IsGood(readResponse.Results[0].StatusCode)) { var value = readResponse.Results[0].GetValue <ExtensionObject[]>(null); if (value != null) { inputArguments = (Argument[])ExtensionObject.ToArray(value, typeof(Argument)); } } } if (StatusCode.IsGood(translateResponse.Results[1].StatusCode) && translateResponse.Results[1].Targets.Count > 0) { var argNodeId = ExpandedNodeId.ToNodeId(translateResponse.Results[1].Targets[0].TargetId, session.NamespaceUris); var readRequest = new ReadRequest { NodesToRead = { new ReadValueId { NodeId = argNodeId, AttributeId = Attributes.Value } } }; var readResponse = await session.ReadAsync(readRequest); if (StatusCode.IsGood(readResponse.Results[0].StatusCode)) { var value = readResponse.Results[0].GetValue <ExtensionObject[]>(null); if (value != null) { outputArguments = (Argument[])ExtensionObject.ToArray(value, typeof(Argument)); } } } return(Tuple.Create(inputArguments, outputArguments)); }
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); }
/// <summary> /// Translates one or more browse paths to NodeIds. /// </summary> /// <param name="channel">A instance of <see cref="IRequestChannel"/>.</param> /// <param name="request">A <see cref="TranslateBrowsePathsToNodeIdsRequest"/>.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation that returns a <see cref="TranslateBrowsePathsToNodeIdsResponse"/>.</returns> public static async Task <TranslateBrowsePathsToNodeIdsResponse> TranslateBrowsePathsToNodeIdsAsync(this IRequestChannel channel, TranslateBrowsePathsToNodeIdsRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } return((TranslateBrowsePathsToNodeIdsResponse)await channel.RequestAsync(request).ConfigureAwait(false)); }
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); }
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); } }
/// <summary> /// Begins an asynchronous invocation of the TranslateBrowsePathsToNodeIds service. /// </summary> public IAsyncResult BeginTranslateBrowsePathsToNodeIds( RequestHeader requestHeader, BrowsePathCollection browsePaths, AsyncCallback callback, object asyncState) { TranslateBrowsePathsToNodeIdsRequest request = new TranslateBrowsePathsToNodeIdsRequest(); request.RequestHeader = requestHeader; request.BrowsePaths = browsePaths; UpdateRequestHeader(request, requestHeader == null, "TranslateBrowsePathsToNodeIds"); if (UseTransportChannel) { return TransportChannel.BeginSendRequest(request, callback, asyncState); } return InnerChannel.BeginTranslateBrowsePathsToNodeIds(new TranslateBrowsePathsToNodeIdsMessage(request), callback, asyncState); }
/// <summary> /// Invokes the TranslateBrowsePathsToNodeIds service. /// </summary> public virtual ResponseHeader TranslateBrowsePathsToNodeIds( RequestHeader requestHeader, BrowsePathCollection browsePaths, out BrowsePathResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { TranslateBrowsePathsToNodeIdsRequest request = new TranslateBrowsePathsToNodeIdsRequest(); TranslateBrowsePathsToNodeIdsResponse response = null; request.RequestHeader = requestHeader; request.BrowsePaths = browsePaths; UpdateRequestHeader(request, requestHeader == null, "TranslateBrowsePathsToNodeIds"); try { if (UseTransportChannel) { IServiceResponse genericResponse = TransportChannel.SendRequest(request); if (genericResponse == null) { throw new ServiceResultException(StatusCodes.BadUnknownResponse); } ValidateResponse(genericResponse.ResponseHeader); response = (TranslateBrowsePathsToNodeIdsResponse)genericResponse; } else { TranslateBrowsePathsToNodeIdsResponseMessage responseMessage = InnerChannel.TranslateBrowsePathsToNodeIds(new TranslateBrowsePathsToNodeIdsMessage(request)); if (responseMessage == null || responseMessage.TranslateBrowsePathsToNodeIdsResponse == null) { throw new ServiceResultException(StatusCodes.BadUnknownResponse); } response = responseMessage.TranslateBrowsePathsToNodeIdsResponse; ValidateResponse(response.ResponseHeader); } results = response.Results; diagnosticInfos = response.DiagnosticInfos; } finally { RequestCompleted(request, response, "TranslateBrowsePathsToNodeIds"); } return response.ResponseHeader; }
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); } }
/// <summary> /// Initializes the message with the body. /// </summary> public TranslateBrowsePathsToNodeIdsMessage(TranslateBrowsePathsToNodeIdsRequest TranslateBrowsePathsToNodeIdsRequest) { this.TranslateBrowsePathsToNodeIdsRequest = TranslateBrowsePathsToNodeIdsRequest; }