Ejemplo n.º 1
0
        /// <summary>
        /// Load the application configuration.
        /// </summary>
        public async Task LoadAsync(string applicationName, string configSectionName)
        {
            try
            {
                ExitCode = ExitCode.ErrorNotStarted;

                ApplicationInstance.MessageDlg = new ApplicationMessageDlg(m_output);
                CertificatePasswordProvider PasswordProvider = new CertificatePasswordProvider(Password);
                m_application = new ApplicationInstance {
                    ApplicationName             = applicationName,
                    ApplicationType             = ApplicationType.Server,
                    ConfigSectionName           = configSectionName,
                    CertificatePasswordProvider = PasswordProvider
                };

                // load the application configuration.
                await m_application.LoadApplicationConfiguration(false).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                throw new ErrorExitException(ex.Message, ExitCode);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Main entry point.
        /// </summary>
        public static async Task Main(string[] args)
        {
            TextWriter output = Console.Out;

            output.WriteLine("OPC UA Console Reference Client");

            output.WriteLine("OPC UA library: {0} @ {1} -- {2}",
                             Utils.GetAssemblyBuildNumber(),
                             Utils.GetAssemblyTimestamp().ToString("G", CultureInfo.InvariantCulture),
                             Utils.GetAssemblySoftwareVersion());

            // The application name and config file names
            var applicationName   = "ConsoleReferenceClient";
            var configSectionName = "Quickstarts.ReferenceClient";
            var usage             = $"Usage: dotnet {applicationName}.dll [OPTIONS]";

            // command line options
            bool   showHelp         = false;
            bool   autoAccept       = false;
            bool   logConsole       = false;
            bool   appLog           = false;
            bool   renewCertificate = false;
            string password         = null;
            int    timeout          = Timeout.Infinite;

            Mono.Options.OptionSet options = new Mono.Options.OptionSet {
                usage,
                { "h|help", "show this message and exit", h => showHelp = h != null },
                { "a|autoaccept", "auto accept certificates (for testing only)", a => autoAccept = a != null },
                { "c|console", "log to console", c => logConsole = c != null },
                { "l|log", "log app output", c => appLog = c != null },
                { "p|password="******"optional password for private key", (string p) => password = p },
                { "r|renew", "renew application certificate", r => renewCertificate = r != null },
                { "t|timeout=", "timeout in seconds to exit application", (int t) => timeout = t * 1000 },
            };

            try
            {
                // parse command line and set options
                var extraArg = ConsoleUtils.ProcessCommandLine(output, args, options, ref showHelp, false);

                // connect Url?
                Uri serverUrl = new Uri("opc.tcp://localhost:62541/Quickstarts/ReferenceServer");
                if (!string.IsNullOrEmpty(extraArg))
                {
                    serverUrl = new Uri(extraArg);
                }

                // log console output to logger
                if (logConsole && appLog)
                {
                    output = new LogWriter();
                }

                // Define the UA Client application
                ApplicationInstance.MessageDlg = new ApplicationMessageDlg(output);
                CertificatePasswordProvider PasswordProvider = new CertificatePasswordProvider(password);
                ApplicationInstance         application      = new ApplicationInstance {
                    ApplicationName             = applicationName,
                    ApplicationType             = ApplicationType.Client,
                    ConfigSectionName           = configSectionName,
                    CertificatePasswordProvider = PasswordProvider
                };

                // load the application configuration.
                var config = await application.LoadApplicationConfiguration(silent : false);

                // setup the logging
                ConsoleUtils.ConfigureLogging(config, applicationName, logConsole, LogLevel.Information);

                // delete old certificate
                if (renewCertificate)
                {
                    await application.DeleteApplicationInstanceCertificate().ConfigureAwait(false);
                }

                // check the application certificate.
                bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, minimumKeySize : 0).ConfigureAwait(false);

                if (!haveAppCertificate)
                {
                    throw new ErrorExitException("Application instance certificate invalid!", ExitCode.ErrorCertificate);
                }

                // wait for timeout or Ctrl-C
                var quitEvent = ConsoleUtils.CtrlCHandler();

                // connect to a server until application stopped
                bool     quit     = false;
                DateTime start    = DateTime.UtcNow;
                int      waitTime = int.MaxValue;
                do
                {
                    if (timeout > 0)
                    {
                        waitTime = timeout - (int)DateTime.UtcNow.Subtract(start).TotalMilliseconds;
                        if (waitTime <= 0)
                        {
                            break;
                        }
                    }

                    // create the UA Client object and connect to configured server.
                    UAClient uaClient = new UAClient(application.ApplicationConfiguration, output, ClientBase.ValidateResponse)
                    {
                        AutoAccept = autoAccept
                    };

                    bool connected = await uaClient.ConnectAsync(serverUrl.ToString());

                    if (connected)
                    {
                        // Run tests for available methods.
                        uaClient.ReadNodes();
                        uaClient.WriteNodes();
                        uaClient.Browse();
                        uaClient.CallMethod();

                        uaClient.SubscribeToDataChanges();

                        // Wait for some DataChange notifications from MonitoredItems
                        quit = quitEvent.WaitOne(Math.Min(30_000, waitTime));

                        uaClient.Disconnect();
                    }
                    else
                    {
                        output.WriteLine("Could not connect to server! Retry in 10 seconds or Ctrl-C to quit.");
                        quit = quitEvent.WaitOne(Math.Min(10_000, waitTime));
                    }
                } while (!quit);

                output.WriteLine("\nClient stopped.");
            }
            catch (Exception ex)
            {
                output.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 3
0
        private async Task StartConsoleReferenceServerAsync()
        {
            ApplicationInstance.MessageDlg = new ApplicationMessageDlg();
            CertificatePasswordProvider PasswordProvider = new CertificatePasswordProvider(Password);
            ApplicationInstance         application      = new ApplicationInstance {
                ApplicationName             = "Quickstart Reference Server",
                ApplicationType             = ApplicationType.Server,
                ConfigSectionName           = Utils.IsRunningOnMono() ? "Quickstarts.MonoReferenceServer" : "Quickstarts.ReferenceServer",
                CertificatePasswordProvider = PasswordProvider
            };

            // load the application configuration.
            ApplicationConfiguration config = await application.LoadApplicationConfiguration(false).ConfigureAwait(false);

            var loggerConfiguration = new Serilog.LoggerConfiguration();

            if (LogConsole)
            {
                loggerConfiguration.WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning);
            }
#if DEBUG
            else
            {
                loggerConfiguration.WriteTo.Debug(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning);
            }
#endif
            SerilogTraceLogger.Create(loggerConfiguration, config);

            // check the application certificate.
            bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(
                false, CertificateFactory.DefaultKeySize, CertificateFactory.DefaultLifeTime).ConfigureAwait(false);

            if (!haveAppCertificate)
            {
                throw new Exception("Application instance certificate invalid!");
            }

            if (!config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
            {
                config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);
            }

            // start the server.
            m_server = new ReferenceServer();
            await application.Start(m_server).ConfigureAwait(false);

            // print endpoint info
            var endpoints = application.Server.GetEndpoints().Select(e => e.EndpointUrl).Distinct();
            foreach (var endpoint in endpoints)
            {
                Console.WriteLine(endpoint);
            }

            // start the status thread
            m_status = Task.Run(new Action(StatusThreadAsync));

            // print notification on session events
            m_server.CurrentInstance.SessionManager.SessionActivated += EventStatus;
            m_server.CurrentInstance.SessionManager.SessionClosing   += EventStatus;
            m_server.CurrentInstance.SessionManager.SessionCreated   += EventStatus;
        }