Example #1
0
        /// <summary>
        /// Service Start action. Do not call this directly.
        /// </summary>
        /// <param name="cancellationToken">Cancelation token.</param>
        /// <returns>Awaitable <see cref="Task" />.</returns>
        public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            _serviceLog.LogInformation("Service start initiated");
            _stopping = false;

            // MQTT will message
            var willMessage = new MqttApplicationMessageBuilder()
                              .WithTopic($"{TopicRoot}/connected")
                              .WithPayload(((int)ConnectionStatus.Disconnected).ToString())
                              .WithAtLeastOnceQoS()
                              .WithRetainFlag()
                              .Build();

            // MQTT client options
            var optionsBuilder = new MqttClientOptionsBuilder()
                                 .WithTcpServer(_brokerSettings.BrokerIp, _brokerSettings.BrokerPort)
                                 .WithClientId(MqttClientId.ToString())
                                 .WithCleanSession()
                                 .WithWillMessage(willMessage);

            // MQTT credentials
            if (!string.IsNullOrEmpty(_brokerSettings.BrokerUsername) && !string.IsNullOrEmpty(_brokerSettings.BrokerPassword))
            {
                optionsBuilder.WithCredentials(_brokerSettings.BrokerUsername, _brokerSettings.BrokerPassword);
            }

            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(_brokerSettings.BrokerReconnectDelay))
                                 .WithClientOptions(optionsBuilder.Build())
                                 .Build();

            // Subscribe to MQTT messages
            await SubscribeAsync(cancellationToken)
            .ConfigureAwait(false);

            // Connect to MQTT
            await MqttClient.StartAsync(managedOptions)
            .ConfigureAwait(false);

            // Call startup on inheriting service class
            await StartServiceAsync(cancellationToken)
            .ConfigureAwait(false);

            _serviceLog.LogInformation("Service started successfully");
        }
Example #2
0
        /// <summary>
        /// Service Start action. Do not call this directly.
        /// </summary>
        /// <param name="cancellationToken">Cancelation token.</param>
        /// <returns>Awaitable <see cref="Task" />.</returns>
        public async Task StartAsync(CancellationToken cancellationToken = default)
        {
            _serviceLog.LogInformation("Service start initiated");
            _stopping = false;

            // MQTT will message
            var willMessage = new MqttApplicationMessageBuilder()
                              .WithTopic($"{TopicRoot}/connected")
                              .WithPayload(((int)ConnectionStatus.Disconnected).ToString())
                              .WithAtLeastOnceQoS()
                              .WithRetainFlag()
                              .Build();

            // MQTT client options
            var optionsBuilder = new MqttClientOptionsBuilder()
                                 .WithTcpServer(_brokerSettings.BrokerIp, _brokerSettings.BrokerPort)
                                 .WithClientId(MqttClientId.ToString())
                                 .WithCleanSession()
                                 .WithWillMessage(willMessage);

            // MQTT TLS support
            if (_brokerSettings.BrokerUseTls)
            {
                if (_brokerSettings.BrokerTlsSettings == null)
                {
                    throw new ArgumentNullException(nameof(_brokerSettings.BrokerTlsSettings));
                }

                var tlsOptions = new MqttClientOptionsBuilderTlsParameters
                {
                    UseTls = _brokerSettings.BrokerUseTls,
                    AllowUntrustedCertificates        = _brokerSettings.BrokerTlsSettings.AllowUntrustedCertificates,
                    IgnoreCertificateChainErrors      = _brokerSettings.BrokerTlsSettings.IgnoreCertificateChainErrors,
                    IgnoreCertificateRevocationErrors = _brokerSettings.BrokerTlsSettings.IgnoreCertificateRevocationErrors,
                    SslProtocol  = _brokerSettings.BrokerTlsSettings.SslProtocol,
                    Certificates = _brokerSettings.BrokerTlsSettings.Certificates
                };

                optionsBuilder.WithTls(tlsOptions);
            }

            // MQTT credentials
            if (!string.IsNullOrEmpty(_brokerSettings.BrokerUsername) && !string.IsNullOrEmpty(_brokerSettings.BrokerPassword))
            {
                optionsBuilder.WithCredentials(_brokerSettings.BrokerUsername, _brokerSettings.BrokerPassword);
            }

            var managedOptions = new ManagedMqttClientOptionsBuilder()
                                 .WithAutoReconnectDelay(TimeSpan.FromSeconds(_brokerSettings.BrokerReconnectDelay))
                                 .WithClientOptions(optionsBuilder.Build())
                                 .Build();

            // Subscribe to MQTT messages
            await SubscribeAsync(cancellationToken)
            .ConfigureAwait(false);

            // Connect to MQTT
            await MqttClient.StartAsync(managedOptions)
            .ConfigureAwait(false);

            // Call startup on inheriting service class
            await StartServiceAsync(cancellationToken)
            .ConfigureAwait(false);

            _serviceLog.LogInformation("Service started successfully");
        }