Example #1
0
        public static LogEntry For(RegisterNodesRequest request)
        {
            LogEntry entry = new LogEntry("RegisterNodesRequest");

            entry.Add("RequestHeader", For(request.RequestHeader));
            entry.Add("NodesToRegister", For(request.NodesToRegister));
            return(entry);
        }
Example #2
0
        public async Task RegisterNodesAsync()
        {
            var response = new RegisterNodesResponse();
            var request  = new RegisterNodesRequest();
            var channel  = new TestRequestChannel(response);

            var ret = await channel.RegisterNodesAsync(request);

            ret
            .Should().BeSameAs(response);

            channel.Request
            .Should().BeSameAs(request);
        }
Example #3
0
        /// <summary>
        /// Registers the Nodes that will be accessed repeatedly (e.g. Write, Call).
        /// </summary>
        /// <param name="channel">A instance of <see cref="IRequestChannel"/>.</param>
        /// <param name="request">A <see cref="RegisterNodesRequest"/>.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation that returns a <see cref="RegisterNodesResponse"/>.</returns>
        public static async Task <RegisterNodesResponse> RegisterNodesAsync(this IRequestChannel channel, RegisterNodesRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            return((RegisterNodesResponse)await channel.RequestAsync(request).ConfigureAwait(false));
        }
Example #4
0
        private static async Task Write(List <NodeId> nodesIds, DataValue dataval)
        {
            // setup logger
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddDebug(LogLevel.Debug);

            // Describe this app.
            var appDescription = new ApplicationDescription()
            {
                ApplicationName = "DataLoggingConsole",
                ApplicationUri  = $"urn:{System.Net.Dns.GetHostName()}:DataLoggingConsole",
                ApplicationType = ApplicationType.Client,
            };

            // Create a certificate store on disk.

            // Create array of NodeIds to log.
            var nodeIds = nodesIds.ToArray();

            try
            {
                // Discover endpoints.
                var getEndpointsRequest = new GetEndpointsRequest
                {
                    EndpointUrl = discoveryUrl,
                    ProfileUris = new[] { TransportProfileUris.UaTcpTransport }
                };
                var getEndpointsResponse = await UaTcpDiscoveryService.GetEndpointsAsync(getEndpointsRequest).ConfigureAwait(false);

                if (getEndpointsResponse.Endpoints == null || getEndpointsResponse.Endpoints.Length == 0)
                {
                    throw new InvalidOperationException($"'{discoveryUrl}' returned no endpoints.");
                }

                // Choose the endpoint with highest security level.
                var remoteEndpoint = getEndpointsResponse.Endpoints.OrderBy(e => e.SecurityLevel).Last();
                // Create a session with the server.
                var session = new UaTcpSessionChannel(appDescription, certificateStore, async e => GetIUserIdentity(remoteEndpoint).GetAwaiter().GetResult(), remoteEndpoint, loggerFactory);
                try
                {
                    await session.OpenAsync();

                    RegisterNodesResponse registerNodesResponse = null;

                    if (true)     // True registers the nodeIds to improve performance of the server.
                    {
                        // Register array of nodes to read.
                        var registerNodesRequest = new RegisterNodesRequest
                        {
                            NodesToRegister = nodeIds
                        };
                        registerNodesResponse = await session.RegisterNodesAsync(registerNodesRequest);
                    }

                    WriteRequest writeRequest = new WriteRequest();
                    writeRequest.NodesToWrite = new WriteValue[1]
                    {
                        new WriteValue()
                        {
                            NodeId      = nodeIds[0],
                            AttributeId = AttributeIds.Value,
                            Value       = dataval
                        }
                    };
                    WriteRequest request = writeRequest;
                    StatusCode   statusCode;
                    // write the nodes.
                    statusCode = (await session.WriteAsync(request).ConfigureAwait(false)).Results[0];;
                }
                catch
                {
                    await session.AbortAsync();

                    throw;
                }
                await session.AbortAsync();
            }

            catch (Exception e)
            {
                // ignored
            }
        }
Example #5
0
        /// <summary>
        /// Begins an asynchronous invocation of the RegisterNodes service.
        /// </summary>
        public IAsyncResult BeginRegisterNodes(
            RequestHeader    requestHeader,
            NodeIdCollection nodesToRegister,
            AsyncCallback    callback,
            object           asyncState)
        {
            RegisterNodesRequest request = new RegisterNodesRequest();

            request.RequestHeader   = requestHeader;
            request.NodesToRegister = nodesToRegister;

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

            if (UseTransportChannel)
            {
                return TransportChannel.BeginSendRequest(request, callback, asyncState);
            }

            return InnerChannel.BeginRegisterNodes(new RegisterNodesMessage(request), callback, asyncState);
        }
Example #6
0
        /// <summary>
        /// Invokes the RegisterNodes service.
        /// </summary>
        public virtual ResponseHeader RegisterNodes(
            RequestHeader        requestHeader,
            NodeIdCollection     nodesToRegister,
            out NodeIdCollection registeredNodeIds)
        {
            RegisterNodesRequest request = new RegisterNodesRequest();
            RegisterNodesResponse response = null;

            request.RequestHeader   = requestHeader;
            request.NodesToRegister = nodesToRegister;

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

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

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

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (RegisterNodesResponse)genericResponse;
                }
                else
                {
                    RegisterNodesResponseMessage responseMessage = InnerChannel.RegisterNodes(new RegisterNodesMessage(request));

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

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

                registeredNodeIds = response.RegisteredNodeIds;
            }
            finally
            {
                RequestCompleted(request, response, "RegisterNodes");
            }

            return response.ResponseHeader;
        }
        /// <summary>
        /// Registers the Nodes that will be accessed repeatedly (e.g. Write, Call).
        /// </summary>
        /// <param name="channel">A instance of <see cref="IRequestChannel"/>.</param>
        /// <param name="request">A <see cref="RegisterNodesRequest"/>.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation that returns a <see cref="RegisterNodesResponse"/>.</returns>
        /// <seealso href="https://reference.opcfoundation.org/v104/Core/docs/Part4/5.8.5/">OPC UA specification Part 4: Services, 5.8.5</seealso>
        public static async Task <RegisterNodesResponse> RegisterNodesAsync(this IRequestChannel channel, RegisterNodesRequest request, CancellationToken token = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            return((RegisterNodesResponse)await channel.RequestAsync(request, token).ConfigureAwait(false));
        }
Example #8
0
        private static async Task TestAsync(CancellationToken token = default(CancellationToken))
        {
            var discoveryUrl = $"opc.tcp://localhost:26543";
            var cycleTime    = 5000;

            // setup logger
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddConsole(LogLevel.Information);
            var logger = loggerFactory?.CreateLogger <Program>();

            // Describe this app.
            var appDescription = new ApplicationDescription()
            {
                ApplicationName = "DataLoggingConsole",
                ApplicationUri  = $"urn:{System.Net.Dns.GetHostName()}:DataLoggingConsole",
                ApplicationType = ApplicationType.Client,
            };

            // Create a certificate store on disk.
            var certificateStore = new DirectoryStore(
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DataLoggingConsole", "pki"));

            // Create array of NodeIds to log.
            var nodeIds = new[]
            {
                NodeId.Parse("i=2258")
            };

            while (!token.IsCancellationRequested)
            {
                try
                {
                    // Discover endpoints.
                    var getEndpointsRequest = new GetEndpointsRequest
                    {
                        EndpointUrl = discoveryUrl,
                        ProfileUris = new[] { TransportProfileUris.UaTcpTransport }
                    };
                    var getEndpointsResponse = await UaTcpDiscoveryService.GetEndpointsAsync(getEndpointsRequest).ConfigureAwait(false);

                    if (getEndpointsResponse.Endpoints == null || getEndpointsResponse.Endpoints.Length == 0)
                    {
                        throw new InvalidOperationException($"'{discoveryUrl}' returned no endpoints.");
                    }

                    // Choose the endpoint with highest security level.
                    var remoteEndpoint = getEndpointsResponse.Endpoints.OrderBy(e => e.SecurityLevel).Last();

                    // Choose a User Identity.
                    IUserIdentity userIdentity = null;
                    if (remoteEndpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.Anonymous))
                    {
                        userIdentity = new AnonymousIdentity();
                    }
                    else if (remoteEndpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.UserName))
                    {
                        // If a username / password is requested, provide from .config file.
                        userIdentity = new UserNameIdentity("root", "secret");
                    }
                    else
                    {
                        throw new InvalidOperationException("Server must accept Anonymous or UserName identity.");
                    }

                    // Create a session with the server.
                    var session = new UaTcpSessionChannel(appDescription, certificateStore, async e => userIdentity, remoteEndpoint, loggerFactory);
                    try
                    {
                        await session.OpenAsync();

                        RegisterNodesResponse registerNodesResponse = null;

                        if (true) // True registers the nodeIds to improve performance of the server.
                        {
                            // Register array of nodes to read.
                            var registerNodesRequest = new RegisterNodesRequest
                            {
                                NodesToRegister = nodeIds
                            };
                            registerNodesResponse = await session.RegisterNodesAsync(registerNodesRequest);
                        }

                        // Prepare read request.
                        var readRequest = new ReadRequest
                        {
                            NodesToRead = (registerNodesResponse?.RegisteredNodeIds ?? nodeIds)
                                          .Select(n => new ReadValueId {
                                NodeId = n, AttributeId = AttributeIds.Value
                            })
                                          .ToArray()
                        };

                        while (!token.IsCancellationRequested)
                        {
                            // Read the nodes.
                            var readResponse = await session.ReadAsync(readRequest).ConfigureAwait(false);

                            // Write the results.
                            for (int i = 0; i < readRequest.NodesToRead.Length; i++)
                            {
                                logger?.LogInformation($"{nodeIds[i]}; value: {readResponse.Results[i]}");
                            }

                            try
                            {
                                await Task.Delay(cycleTime, token);
                            }
                            catch { }
                        }
                        await session.CloseAsync();
                    }
                    catch
                    {
                        await session.AbortAsync();

                        throw;
                    }
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex.Message);
                }

                try
                {
                    await Task.Delay(cycleTime, token);
                }
                catch { }
            }
        }
Example #9
0
 /// <summary>
 /// Initializes the message with the body.
 /// </summary>
 public RegisterNodesMessage(RegisterNodesRequest RegisterNodesRequest)
 {
     this.RegisterNodesRequest = RegisterNodesRequest;
 }