private static IMqttClientOptions MakeMqttOptions(string certDir, MqttConfig config, string suffix)
        {
            string clientID = $"{config.ClientIDPrefix}_{suffix}_{TheGuid}";

            var builder = new MqttClientOptionsBuilder()
                          .WithClientId(clientID)
                          .WithTcpServer(config.Endpoint);

            if (config.CertFileCA != "")
            {
                var caCert     = X509Certificate.CreateFromCertFile(Path.Combine(certDir, config.CertFileCA));
                var clientCert = new X509Certificate2(Path.Combine(certDir, config.CertFileClient), "");

                builder = builder
                          .WithTls(new MqttClientOptionsBuilderTlsParameters()
                {
                    UseTls       = true,
                    SslProtocol  = System.Security.Authentication.SslProtocols.Tls12,
                    Certificates = new List <X509Certificate>()
                    {
                        clientCert,
                        caCert
                    },
                    IgnoreCertificateRevocationErrors = config.IgnoreCertificateRevocationErrors,
                    IgnoreCertificateChainErrors      = config.IgnoreCertificateChainErrors,
                    AllowUntrustedCertificates        = config.AllowUntrustedCertificates,
                });
            }

            return(builder
                   .WithCleanSession()
                   .Build());
        }
Exemple #2
0
        private IMqttClientOptions CreateMqttClientOptions()
        {
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(_settings.ClientId)
                          .WithCredentials(_settings.Username, _settings.Password);

            if (_settings.TcpEndPoint.Enabled)
            {
                if (_settings.TcpEndPoint.Port > 0)
                {
                    options.WithTcpServer(_settings.TcpEndPoint.Server, _settings.TcpEndPoint.Port);
                }
                else
                {
                    options.WithTcpServer(_settings.TcpEndPoint.Server);
                }
            }
            else
            {
                options.WithTcpServer("localhost");
            }

            if (_settings.CommunicationTimeout > 0)
            {
                options.WithCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout));
            }

            if (_settings.EnableCleanSessions)
            {
                options.WithCleanSession();
            }

            return(options.Build());
        }
Exemple #3
0
 /// <summary>
 /// 连接mqtt服务器
 /// </summary>
 public static void Connect()
 {
     if (mqttClient == null)
     {
         return;
     }
     if (mqttClient.IsConnected)
     {
         Log.Info(moudle, "已连接,无需再次连接");
         return;
     }
     //var options = new MqttClientOptionsBuilder()
     //    .WithTcpServer("lbsmqtt.airm2m.com", 1884)
     //    .Build();
     //Task.Run(() =>
     //{
     //    try
     //    {
     //        mqttClient.ConnectAsync(options, CancellationToken.None).Wait();
     //        Log.Info("mqtt", $"=======连上了");
     //    }
     //    catch (Exception e)
     //    {
     //        Log.Info("mqtt", $"=======炸了:{e}");
     //    }
     //});
     Task.Run(async() =>
     {
         try
         {
             var op = new MqttClientOptionsBuilder()
                      .WithClientId(Utils.Setting.ClientID)
                      .WithTcpServer(Utils.Setting.MqttBroker, Utils.Setting.MqttPort)
                      .WithCredentials(Utils.Setting.MqttUser, Utils.Setting.MqttPassword)
                      .WithKeepAlivePeriod(new TimeSpan(0, 0, Utils.Setting.KeepAlive));
             if (Utils.Setting.MqttTLS)
             {
                 op.WithTls();
             }
             var options = op.WithCleanSession().Build();
             await mqttClient.ConnectAsync(options, CancellationToken.None);
         }
         catch (Exception e)
         {
             Log.Warn(moudle, $"服务器连接失败:{Utils.Setting.MqttBroker}:{Utils.Setting.MqttPort}" +
                      $",{Utils.Setting.MqttUser},{Utils.Setting.MqttPassword},{Utils.Setting.MqttTLS}");
             Log.Warn(moudle, $"原因:{e.Message}");
         }
     });
 }
Exemple #4
0
 private void ConnectButton_Click(object sender, RoutedEventArgs e)
 {
     if (mqttClient.IsConnected)
     {
         Task.Run(async() =>
         {
             try
             {
                 await mqttClient.DisconnectAsync();
             }
             catch { }
         });
     }
     else
     {
         MqttIsConnected = true;
         var temp = new MqttClientOptionsBuilder()
                    .WithClientId(Tools.Global.setting.mqttClientID)
                    .WithTcpServer(Tools.Global.setting.mqttServer, Tools.Global.setting.mqttPort)
                    .WithCredentials(Tools.Global.setting.mqttUser, Tools.Global.setting.mqttPassword)
                    .WithKeepAlivePeriod(new TimeSpan(0, 0, Tools.Global.setting.mqttKeepAlive));
         if (Tools.Global.setting.mqttTLS)
         {
             temp.WithTls();
         }
         if (Tools.Global.setting.mqttCleanSession)
         {
             temp.WithCleanSession();
         }
         var options = temp.Build();
         Task.Run(async() =>
         {
             try
             {
                 await mqttClient.ConnectAsync(options, CancellationToken.None);
             }
             catch { }
         });
     }
 }
Exemple #5
0
        public void Connect(out string errMsg)
        {
            errMsg = "";
            if (this.mqttClient != null && this.mqttClient.IsConnected)
            {
                return;
            }

            if (this.param == null)
            {
                errMsg = "连接MQTT服务端失败,没有指明服务参数";
                return;
            }
            try
            {
                mqttClient = new MqttFactory().CreateMqttClient() as MqttClient;
                this.OnloadEvents();

                MqttClientOptionsBuilder optionsBuilder = new MqttClientOptionsBuilder();

                optionsBuilder.WithCommunicationTimeout(TimeSpan.FromSeconds(10));// 只连接等待10秒
                optionsBuilder.WithTcpServer(this.param.ip, this.param.port);
                optionsBuilder.WithCredentials(this.param.userName, this.param.password);
                optionsBuilder.WithClientId(this.param.clientID);
                optionsBuilder.WithCleanSession(true);// 临时会话

                Task task = mqttClient.ConnectAsync(optionsBuilder.Build());
                task.Wait(5000);

                if (!this.IsConnected)
                {
                    errMsg = "连接MQTT服务器失败";
                }
            }
            catch (Exception ex)
            {
                errMsg = "连接到MQTT服务器失败!" + ex.Message;
            }
        }
Exemple #6
0
 /// <inheritdoc cref="IMqttClientConfigBuilder.RequestCleanSession" />
 public IMqttClientConfigBuilder RequestCleanSession()
 {
     _builder.WithCleanSession();
     return(this);
 }
Exemple #7
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 #8
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 #9
0
        /// <summary>
        /// 初始化各个参数
        /// </summary>
        public static void Initial()
        {
            if (mqttClient != null)
            {
                return;
            }
            mqttClient = factory.CreateMqttClient();
            //连接成功
            mqttClient.UseConnectedHandler(e =>
            {
                Log.Info(moudle, "已连接");
                LuaEnv.LuaStates.Run("MQTT", "MQTT", new
                {
                    t = "connected"
                });
            });

            //收到消息
            mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                Log.Debug(moudle,
                          $"收到消息:{e.ApplicationMessage.Topic} {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                LuaEnv.LuaStates.Run("MQTT", "MQTT", new
                {
                    t       = "receive",
                    topic   = e.ApplicationMessage.Topic,
                    payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload),
                    qos     = (int)e.ApplicationMessage.QualityOfServiceLevel
                });
            });

            //断线重连
            mqttClient.UseDisconnectedHandler(async e =>
            {
                Log.Warn(moudle, "MQTT连接已断开");
                if (!Utils.Setting.MqttEnable)
                {
                    return;
                }
                await Task.Delay(TimeSpan.FromSeconds(5));
                Log.Warn(moudle, "MQTT尝试重连");
                try
                {
                    var op = new MqttClientOptionsBuilder()
                             .WithClientId(Utils.Setting.ClientID)
                             .WithTcpServer(Utils.Setting.MqttBroker, Utils.Setting.MqttPort)
                             .WithCredentials(Utils.Setting.MqttUser, Utils.Setting.MqttPassword)
                             .WithKeepAlivePeriod(new TimeSpan(0, 0, Utils.Setting.KeepAlive));
                    if (Utils.Setting.MqttTLS)
                    {
                        op.WithTls();
                    }
                    var options = op.WithCleanSession().Build();
                    await mqttClient.ConnectAsync(options, CancellationToken.None);
                }
                catch (Exception ee)
                {
                    Log.Warn(moudle, $"MQTT重连失败");
                    Log.Warn(moudle, $"原因: {ee.Message}");
                }
            });
        }