Exemple #1
0
        public IMqttClientConfigBuilder ConnectViaWebSocket(
            string uri,
            Action <MqttClientOptionsBuilderWebSocketParameters> parametersAction)
        {
            Check.NotNull(uri, nameof(uri));
            Check.NotNull(parametersAction, nameof(parametersAction));

            var parameters = new MqttClientOptionsBuilderWebSocketParameters();

            parametersAction.Invoke(parameters);

            _builder.WithWebSocketServer(uri, parameters);
            return(this);
        }
Exemple #2
0
        public static MqttClientOptionsBuilder WithConnectionUri(this MqttClientOptionsBuilder builder, Uri uri)
        {
            var port = uri.IsDefaultPort ? null : (int?)uri.Port;

            switch (uri.Scheme.ToLower())
            {
            case "tcp":
            case "mqtt":
                builder.WithTcpServer(uri.Host, port);
                break;

            case "mqtts":
                builder.WithTcpServer(uri.Host, port).WithTls();
                break;

            case "ws":
            case "wss":
                builder.WithWebSocketServer(uri.ToString());
                break;

            default:
                throw new ArgumentException("Unexpected scheme in uri.");
            }

            if (!string.IsNullOrEmpty(uri.UserInfo))
            {
                var userInfo = uri.UserInfo.Split(':');
                var username = userInfo[0];
                var password = userInfo.Length > 1 ? userInfo[1] : "";
                builder.WithCredentials(username, password);
            }

            return(builder);
        }
        private IMqttClientOptions GetMqttOption(string clientId)
        {
            var builder = new MqttClientOptionsBuilder()
                          .WithProtocolVersion(MqttProtocolVersion.V311)
                          .WithClientId(clientId);

            /*
             * .WithWillMessage(new MqttApplicationMessage()
             * {
             *  Payload = Encoding.UTF8.GetBytes("Hello World!!!"),
             *  Topic = "/homegenie",
             *  Retain = true,
             *  QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce
             * });
             */
            // TODO: ...
            //.WithKeepAlivePeriod(TimeSpan.FromSeconds(...))
            //.WithCommunicationTimeout(TimeSpan.FromSeconds(...))
            // .WithTls()
            //.WithCleanSession();
            if (usingWebSockets)
            {
                builder.WithWebSocketServer(endPoint.Address + ":" + endPoint.Port + "/mqtt");
            }
            else
            {
                builder.WithTcpServer(endPoint.Address, endPoint.Port);
            }
            if (networkCredential != null)
            {
                builder.WithCredentials(networkCredential.UserName, networkCredential.Password);
            }
            return(builder.Build());
        }
        private static IMqttClientOptions UnwrapOptions(IClientOptions wrappedOptions, IWillMessage willMessage)
        {
            var optionsBuilder = new MqttClientOptionsBuilder();

            if (wrappedOptions.ConnectionType == ConnectionType.Tcp)
            {
                optionsBuilder.WithTcpServer(wrappedOptions.Uri.Host);
            }
            else
            {
                optionsBuilder.WithWebSocketServer(wrappedOptions.Uri.AbsoluteUri);
            }

            return(optionsBuilder
                   .WithWillMessage(WrapWillMessage(willMessage))
                   .WithCleanSession(wrappedOptions.CleanSession)
                   .WithClientId(wrappedOptions.ClientId ?? Guid.NewGuid().ToString().Replace("-", string.Empty))
                   .WithTls(wrappedOptions.AllowUntrustedCertificates, wrappedOptions.IgnoreCertificateChainErrors,
                            wrappedOptions.IgnoreCertificateChainErrors, UnwrapCertificates(wrappedOptions.Certificates))
                   .WithProtocolVersion(UnwrapProtocolVersion(wrappedOptions.ProtocolVersion))
                   .WithCommunicationTimeout(wrappedOptions.DefaultCommunicationTimeout == default(TimeSpan)
                    ? TimeSpan.FromSeconds(10)
                    : wrappedOptions.DefaultCommunicationTimeout)
                   .WithKeepAlivePeriod(wrappedOptions.KeepAlivePeriod == default(TimeSpan)
                    ? TimeSpan.FromSeconds(5)
                    : wrappedOptions.KeepAlivePeriod)
                   .WithCredentials(wrappedOptions.UserName, wrappedOptions.Password)
                   .Build());
        }
Exemple #5
0
        public async Task MQTTClientConnect(string URI)
        {
            MqttClientOptionsBuilder MQOptions = new MqttClientOptionsBuilder();

            MQOptions.WithClientId(MQTT_CLIENT_ID);
            MQOptions.WithWebSocketServer(URI);
            MQOptions.WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311);
            MQOptions.WithTls();

            await mqClient.ConnectAsync(MQOptions.Build()).ConfigureAwait(false);
        }
Exemple #6
0
        private MqttClientOptionsBuilder BuildConnectionOptions()
        {
            var mqttClientOptionsBuilder = new MqttClientOptionsBuilder();

            if (Uri != null && RequestHeaders != null && RequestHeaders.Any())
            {
                return(mqttClientOptionsBuilder.WithWebSocketServer(BuildWebSocketServerOptions));
            }

            return(mqttClientOptionsBuilder.WithTcpServer(BuildTcpServerOptions));
        }
Exemple #7
0
        public Task StartAsync()
        {
            connectingFailedReason = null;

            var mqttClientOptions = new MqttClientOptionsBuilder()
                                    .WithClientId(clientId)
                                    .WithCleanSession();

            if (url.StartsWith("ws://"))
            {
                var subUrl = url.Substring("ws://".Length);
                mqttClientOptions.WithWebSocketServer(subUrl);
            }
            else
            {
                var subUrl = url.StartsWith("tcp://") ? url.Substring("tcp://".Length) : url;
                mqttClientOptions.WithTcpServer(subUrl);
            }

            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(mqttClientOptions.Build())
                          .Build();

            return(Task.Run(async() =>
            {
                if (this.mqttClient != null)
                {
                    await this.mqttClient.StopAsync();
                }
                var mqttClient = new MqttFactory().CreateManagedMqttClient();
                mqttClient.UseApplicationMessageReceivedHandler(e =>
                {
                    var msg = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                    var topic = e.ApplicationMessage.Topic;
                    OnReceivedMessage(topic, msg, e);
                });
                mqttClient.ConnectedHandler = this;
                mqttClient.ConnectingFailedHandler = this;
                mqttClient.DisconnectedHandler = this;
                startWaitEvent.Reset();
                await mqttClient.StartAsync(options);
                startWaitEvent.WaitOne();
                if (!string.IsNullOrEmpty(connectingFailedReason))
                {
                    throw new LogMeException(connectingFailedReason);
                }
                this.mqttClient = mqttClient;
                OnConnected();
            }));
        }
        /// <summary>
        /// Provides the MQTT client options to create an authenticated MQTT
        /// over WebSocket connection to an AWS IoT Device Gateway endpoint.
        /// </summary>
        /// <param name="client">The authenticated AWS IoT Device Gateway client.</param>
        /// <param name="iotEndpointAddress">The AWS account-specific AWS IoT endpoint address.</param>
        /// <param name="cancelToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public static async Task <IMqttClientOptions> CreateMqttWebSocketClientOptionsAsync(this AmazonIoTDeviceGatewayClient client, string iotEndpointAddress, CancellationToken cancelToken = default)
        {
            if (client is null)
            {
                throw new ArgumentNullException(nameof(client));
            }
            var uriDetails = await client.CreateMqttWebSocketUriAsync(new Model.CreateMqttWebSocketUriRequest
            {
                EndpointAddress = iotEndpointAddress
            }, cancelToken).ConfigureAwait(continueOnCapturedContext: false);

            var optionsBuilder = new MqttClientOptionsBuilder();

            optionsBuilder = optionsBuilder.WithTls();
            optionsBuilder = optionsBuilder.WithWebSocketServer(uriDetails.RequestUri?.ToString());

            IWebProxy iProxy = client.Config.GetWebProxy();

            if (!(iProxy is null))
            {
                Uri proxyUri;
                if (iProxy is Amazon.Runtime.Internal.Util.WebProxy awssdkProxy)
                {
                    proxyUri = awssdkProxy.ProxyUri;
                }
                else
                {
                    proxyUri = new Uri("http://" + client.Config.ProxyHost + ":" + client.Config.ProxyPort);
                }
                var iCreds   = iProxy.Credentials ?? client.Config.ProxyCredentials;
                var netCreds = iCreds?.GetCredential(proxyUri, default);
                optionsBuilder = optionsBuilder.WithProxy(proxyUri.ToString(),
                                                          username: netCreds?.UserName, password: netCreds?.Password, domain: netCreds?.Domain,
                                                          bypassOnLocal: iProxy.IsBypassed(localhostUri)
                                                          );
            }

            var options = optionsBuilder.Build();

            if (options.ChannelOptions is MqttClientWebSocketOptions webSocketOptions)
            {
                webSocketOptions.RequestHeaders = uriDetails.Headers;
            }

            return(options);
        }
        /// <summary>
        /// Connects the Sparkplug node to the MQTT broker.
        /// </summary>
        /// <param name="options">The configuration option.</param>
        /// <returns>A <see cref="Task"/> representing any asynchronous operation.</returns>
        private async Task ConnectInternal(SparkplugNodeOptions options)
        {
            options.CancellationToken ??= CancellationToken.None;

            var builder = new MqttClientOptionsBuilder()
                          .WithClientId(options.ClientId)
                          .WithCredentials(options.UserName, options.Password)
                          .WithCleanSession(false)
                          .WithProtocolVersion(MqttProtocolVersion.V311);

            if (options.UseTls)
            {
                builder.WithTls();
            }

            if (options.WebSocketParameters is null)
            {
                builder.WithTcpServer(options.BrokerAddress, options.Port);
            }
            else
            {
                builder.WithWebSocketServer(options.BrokerAddress, options.WebSocketParameters);
            }

            if (options.ProxyOptions != null)
            {
                builder.WithProxy(
                    options.ProxyOptions.Address,
                    options.ProxyOptions.Username,
                    options.ProxyOptions.Password,
                    options.ProxyOptions.Domain,
                    options.ProxyOptions.BypassOnLocal);
            }

            if (this.willMessage != null)
            {
                builder.WithWillMessage(this.willMessage);
            }

            this.ClientOptions = builder.Build();

            await this.Client.ConnectAsync(this.ClientOptions, options.CancellationToken.Value);
        }
        private IMqttClientOptions GetMqttOption(string clientId)
        {
            var builder = new MqttClientOptionsBuilder()
                          .WithProtocolVersion(MqttProtocolVersion.V311)
                          .WithKeepAlivePeriod(TimeSpan.FromSeconds(5))
                          .WithCommunicationTimeout(TimeSpan.FromSeconds(15))
                          .WithClientId(clientId)
                          // this message will be sent to all clients
                          // subscribed to <clientId>/status topic
                          // if this client gets disconnected
                          .WithWillMessage(new MqttApplicationMessage
            {
                Payload = Encoding.UTF8.GetBytes("disconnected"),
                Topic   = String.Format("/{0}/status", clientId),
                Retain  = true,
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce
            });

            // TODO: ?
            // .WithCleanSession();
            if (usingWebSockets)
            {
                builder.WithWebSocketServer(endPoint.Address + ":" + endPoint.Port + "/mqtt");
            }
            else
            {
                builder.WithTcpServer(endPoint.Address, endPoint.Port);
            }
            if (networkCredential != null)
            {
                builder.WithCredentials(networkCredential.UserName, networkCredential.Password);
            }
            if (useSsl)
            {
                var tlsParameters = new MqttClientOptionsBuilderTlsParameters {
                    UseTls = true
                };
                builder.WithTls(tlsParameters);
            }
            return(builder.Build());
        }
Exemple #11
0
        public MqttWorker(EvoHomeSettings evoHomeSettings, ILogger <MqttWorker> logger)
        {
            _settings = evoHomeSettings;
            _logger   = logger;

            if (evoHomeSettings.DisableMqtt)
            {
                _logger.LogInformation("Mqtt Disabled");
                return;
            }

            var builder = new MqttClientOptionsBuilder()
                          .WithClientId(evoHomeSettings.MqttClientName);

            if (!string.IsNullOrWhiteSpace(evoHomeSettings.MqttUser))
            {
                builder.WithCredentials(evoHomeSettings.MqttUser, evoHomeSettings.MqttPassword);
            }

            if (evoHomeSettings.MqttWebSockets)
            {
                builder.WithWebSocketServer($"{evoHomeSettings.MqttConnection}:{evoHomeSettings.MqttPort}");
            }
            else
            {
                builder.WithTcpServer(evoHomeSettings.MqttConnection, evoHomeSettings.MqttPort);
            }

            var options = builder.Build();

            _managedOptions = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(options)
                              .Build();

            var factory = new MqttFactory();

            _mqttClient = factory.CreateManagedMqttClient();
        }
 public static MqttClientOptionsBuilder RunWithWebSocket(this MqttClientOptionsBuilder optionsBuilder, string host = MqttConstants.MqttServer.LocalHost, int port = 8000, string path = "mqtt")
 {
     return(optionsBuilder.WithWebSocketServer($"{host}:{port}/{path}"));
 }
    /// <summary>
    /// Connects the Sparkplug node to the MQTT broker.
    /// </summary>
    /// <exception cref="ArgumentNullException">The options are null.</exception>
    /// <returns>A <see cref="Task"/> representing any asynchronous operation.</returns>
    private async Task ConnectInternal()
    {
        if (this.options is null)
        {
            throw new ArgumentNullException(nameof(this.options));
        }

        // Increment the session number.
        this.IncrementLastSessionNumber();

        // Reset the sequence number.
        this.ResetLastSequenceNumber();

        // Get the will message.
        var willMessage = this.MessageGenerator.GetSparkPlugNodeDeathMessage(
            this.NameSpace,
            this.options.GroupIdentifier,
            this.options.EdgeNodeIdentifier,
            this.LastSessionNumber);

        // Build up the MQTT client and connect.
        this.options.CancellationToken ??= CancellationToken.None;

        var builder = new MqttClientOptionsBuilder()
                      .WithClientId(this.options.ClientId)
                      .WithCredentials(this.options.UserName, this.options.Password)
                      .WithCleanSession(false)
                      .WithProtocolVersion(MqttProtocolVersion.V311);

        if (this.options.UseTls)
        {
            builder.WithTls();
        }

        if (this.options.WebSocketParameters is null)
        {
            builder.WithTcpServer(this.options.BrokerAddress, this.options.Port);
        }
        else
        {
            builder.WithWebSocketServer(this.options.BrokerAddress, this.options.WebSocketParameters);
        }

        if (this.options.ProxyOptions != null)
        {
            builder.WithProxy(
                this.options.ProxyOptions.Address,
                this.options.ProxyOptions.Username,
                this.options.ProxyOptions.Password,
                this.options.ProxyOptions.Domain,
                this.options.ProxyOptions.BypassOnLocal);
        }

        builder.WithWillMessage(willMessage);
        this.ClientOptions = builder.Build();

        // Debug output.
        this.Logger?.Debug("CONNECT Message: {@ClientOptions}", this.ClientOptions);

        await this.Client.ConnectAsync(this.ClientOptions, this.options.CancellationToken.Value);
    }
Exemple #14
0
        private async void Connect_Click(object sender, EventArgs e)
        {
            if (mqttClient == null)
            {
                mqttClient = new MqttFactory().CreateMqttClient();
                mqttClient.UseApplicationMessageReceivedHandler(new
                                                                Action <MqttApplicationMessageReceivedEventArgs>(MqttClient_ApplicationMessageReceived));
                mqttClient.UseDisconnectedHandler(new
                                                  Action <MqttClientDisconnectedEventArgs>(MqttClient_Disconnected));
                mqttClient.UseConnectedHandler(new
                                               Action <MqttClientConnectedEventArgs>(MqttClient_Connected));
            }
            if (mqttClient.IsConnected)
            {
                return;
            }
            status.Text = "Connecting...";
            var clientOptionsBuilder = new MqttClientOptionsBuilder();

            clientOptionsBuilder.WithProtocolVersion((MqttProtocolVersion)version.SelectedValue);
            if (!string.IsNullOrWhiteSpace(username.Text))
            {
                if (!string.IsNullOrWhiteSpace(password.Text))
                {
                    clientOptionsBuilder.WithCredentials(username.Text, password.Text);
                }
                else
                {
                    clientOptionsBuilder.WithCredentials(username.Text);
                }
            }
            if (!string.IsNullOrWhiteSpace(clientId.Text))
            {
                clientOptionsBuilder.WithClientId(clientId.Text);
            }
            if (useTls.Checked)
            {
                clientOptionsBuilder.WithTls();
            }
            if (useWebSocket.Checked)
            {
                clientOptionsBuilder.WithWebSocketServer(host.Text);
            }
            else
            {
                clientOptionsBuilder.WithTcpServer(host.Text, int.Parse(port.Text));
            }
            if (cleanSession.Checked)
            {
                clientOptionsBuilder.WithCleanSession(true);
            }
            else
            {
                clientOptionsBuilder.WithCleanSession(false);
            }
            if (setWill.Checked && !string.IsNullOrWhiteSpace(input.TextValue))
            {
                clientOptionsBuilder.WithWillMessage(BuildMessage());
            }
            try
            {
                await mqttClient.ConnectAsync(clientOptionsBuilder.Build());

                clientId.Text = mqttClient.Options.ClientId;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
        }
Exemple #15
0
        private async void but_start_ClickAsync(object sender, EventArgs even)
        {
            try
            {
                but_Stop_Click(null, null);
                var factory = new MqttFactory();
                mqttClient = factory.CreateManagedMqttClient();
                var mqttClientOptions = new MqttClientOptionsBuilder()
                                        .WithClientId(txt_ClientID.Text?.Trim())
                                        //.WithTcpServer(txt_Address.Text?.Trim(), int.Parse(txt_Port.Text?.Trim()))
                                        .WithCredentials(txt_UserName.Text, txt_Password.Text);

                if (checkBox1.Checked)
                {
                    if (!File.Exists(txt_ca_file.Text))
                    {
                        MessageBox.Show($"没有找到文件:{txt_ca_file.Text}");
                        return;
                    }
                    if (!File.Exists(txt_pfx_file.Text))
                    {
                        MessageBox.Show($"没有找到文件:{txt_pfx_file.Text}");
                        return;
                    }
                    var caCert     = X509Certificate.CreateFromCertFile(txt_ca_file.Text);
                    var clientCert = new X509Certificate2(txt_pfx_file.Text);
                    mqttClientOptions = mqttClientOptions.WithTls(new MqttClientOptionsBuilderTlsParameters()
                    {
                        UseTls      = true,
                        SslProtocol = System.Security.Authentication.SslProtocols.Tls12,
                        CertificateValidationHandler = (o) =>
                        {
                            return(true);
                        },
                        Certificates = new List <X509Certificate>()
                        {
                            caCert, clientCert
                        }
                    });
                }

                if (comboBox1.SelectedIndex == 0)
                {
                    mqttClientOptions = mqttClientOptions.WithTcpServer(txt_Address.Text?.Trim(), int.Parse(txt_Port.Text?.Trim()));
                }
                else if (comboBox1.SelectedIndex == 1)
                {
                    mqttClientOptions = mqttClientOptions.WithWebSocketServer($"{txt_Address.Text?.Trim()}:{txt_Port.Text?.Trim()}/mqtt").WithTls();
                }
                else if (comboBox1.SelectedIndex == 2)
                {
                    mqttClientOptions = mqttClientOptions.WithWebSocketServer($"{txt_Address.Text?.Trim()}:{txt_Port.Text?.Trim()}/mqtt");
                }

                var options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                              .WithClientOptions(mqttClientOptions.Build())
                              .Build();

                await mqttClient.StartAsync(options);

                mqttClient.UseDisconnectedHandler(e =>
                {
                    WriteLine_1("### 服务器断开连接 ###");
                });


                mqttClient.UseApplicationMessageReceivedHandler(e =>
                {
                    WriteLine_1("### 收到消息 ###");
                    WriteLine_1($"+ Topic = {e.ApplicationMessage.Topic}");
                    try
                    {
                        WriteLine_1($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                    }
                    catch { }
                    WriteLine_1($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                    WriteLine_1($"+ Retain = {e.ApplicationMessage.Retain}");
                    WriteLine_1();
                });

                mqttClient.UseConnectedHandler(e =>
                {
                    WriteLine_1("### 连接到服务 ###");

                    but_Start.Enabled     = false;
                    but_Subscribe.Enabled = true;
                    but_Publish.Enabled   = true;
                    but_Stop.Enabled      = true;
                });
            }
            catch (Exception ex)
            {
                WriteLine_1($"err:{ex.Message}");
            }
        }
Exemple #16
0
        private MqttClientOptionsBuilder CreateOptionsBuilder(ClientCredentials credentials = null)
        {
            MqttClientOptionsBuilder clientOptionsBuilder       = new MqttClientOptionsBuilder();
            MqttClientOptionsBuilderTlsParameters tlsParameters = null;
            string hostName = Settings.Client.BrokerHostname;
            int    portNum  = Settings.Client.BrokerPort;

            //check if broker endpoint for local connections is defined in environment, only possible for connections without credentials
            if (credentials == null)
            {
                string brokerEndpoint = Environment.GetEnvironmentVariable("GE_BROKER_CONNECTION_ENDPOINT");
                if (!string.IsNullOrEmpty(brokerEndpoint))
                {
                    string[] tokens = brokerEndpoint.Split(':');
                    if (tokens.Length == 2)
                    {
                        hostName = tokens[0];
                        portNum  = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture);
                    }
                }
            }
            clientOptionsBuilder.WithCleanSession();
            clientOptionsBuilder.WithClientId(ClientId);
            if (portNum == 443)
            {
                clientOptionsBuilder.WithWebSocketServer(hostName);
            }
            else
            {
                clientOptionsBuilder.WithTcpServer(hostName, portNum);
            }
            if (credentials != null)
            {
                if (credentials.HasCertificates())
                {
                    tlsParameters = new MqttClientOptionsBuilderTlsParameters
                    {
                        UseTls = true,
                        AllowUntrustedCertificates        = Settings.Client.AllowUntrustedCertificates,
                        IgnoreCertificateChainErrors      = Settings.Client.IgnoreCertificateChainErrors,
                        IgnoreCertificateRevocationErrors = Settings.Client.IgnoreCertificateRevocationErrors,
                        CertificateValidationHandler      = CertificateValidationCallback,
                        Certificates = credentials.ClientCertAndCaChain,
                        SslProtocol  = SslProtocols.Tls12
                    };
                    clientOptionsBuilder.WithTls(tlsParameters);
                }
                if (credentials.IsUserNameAndPasswordRequired())
                {
                    credentials.GetUserNameAndPassword(ClientId, out string username, out string password);
                    clientOptionsBuilder.WithCredentials(username, password);
                }
            }

            // settings for connection timeout and MQTT kepp alive interval, given in seconds
            // (defaults in MQTTnet stack are CommunicationTimeout = 10 sec and KeepAlivePeriod = 15 sec.,
            //  see in MqttClientOptions.cs of MQTTnet)
            clientOptionsBuilder.WithCommunicationTimeout(new TimeSpan(0, 0, Settings.Client.CommunicationTimeout));
            clientOptionsBuilder.WithKeepAlivePeriod(new TimeSpan(0, 0, Settings.Client.MqttKeepAlivePeriod));
            return(clientOptionsBuilder);
        }
Exemple #17
0
        private void _connect()
        {
            try
            {
                if (_mqttClient != null && _mqttClient.IsConnected)
                {
                    return;
                }

                if (Options == null)
                {
                    return;
                }

                LastWillMessage        lastWillMsg = new LastWillMessage();
                string                 payload     = JsonConvert.SerializeObject(lastWillMsg);
                MqttApplicationMessage msg         = new MqttApplicationMessage()
                {
                    Payload = Encoding.UTF8.GetBytes(payload),
                    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                    Retain = true,
                    Topic  = string.Format(MQTTTopic.ScadaConnTopic, Options.ScadaId)
                };

                string clientId = "EdgeAgent_" + Guid.NewGuid().ToString("N");
                var    ob       = new MqttClientOptionsBuilder();
                ob.WithClientId(clientId)
                .WithCredentials(Options.MQTT.Username, Options.MQTT.Password)
                .WithCleanSession()
                .WithWillMessage(msg);

                switch (Options.MQTT.ProtocolType)
                {
                case Protocol.TCP:
                    ob.WithTcpServer(Options.MQTT.HostName, Options.MQTT.Port);
                    break;

                case Protocol.WebSocket:
                    ob.WithWebSocketServer(Options.MQTT.HostName);
                    break;

                default:
                    ob.WithTcpServer(Options.MQTT.HostName, Options.MQTT.Port);
                    break;
                }

                if (Options.UseSecure)
                {
                    ob.WithTls();
                }

                var mob = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromMilliseconds(Options.ReconnectInterval))
                          .WithClientOptions(ob.Build())
                          .Build();

                _mqttClient.StartAsync(mob);
            }
            catch (Exception ex)
            {
                //_logger.Error( ex.ToString() );
            }
        }