Example #1
0
        /// <inheritdoc cref="IMqttClientConfigBuilder.WithCommunicationTimeout" />
        public IMqttClientConfigBuilder WithCommunicationTimeout(TimeSpan timeout)
        {
            Check.Range(timeout, nameof(timeout), TimeSpan.Zero, TimeSpan.MaxValue);

            _builder.WithCommunicationTimeout(timeout);
            return(this);
        }
Example #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());
        }
Example #3
0
        /// <summary>
        /// Converts the connection options to client options.
        /// </summary>
        public IMqttClientOptions ToMqttClientOptions()
        {
            MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder()
                                               .WithTcpServer(Server, Port > 0 ? Port : null);

            if (!string.IsNullOrEmpty(ClientID))
            {
                builder.WithClientId(ClientID);
            }

            if (!string.IsNullOrEmpty(Username))
            {
                builder.WithCredentials(Username, Password);
            }

            if (Timeout > 0)
            {
                builder.WithCommunicationTimeout(TimeSpan.FromMilliseconds(Timeout));
            }

            if (ProtocolVersion > MqttProtocolVersion.Unknown)
            {
                builder.WithProtocolVersion(ProtocolVersion);
            }

            return(builder.Build());
        }
Example #4
0
        public static IServiceCollection AddMqttServices <TMqttSettings>(this IServiceCollection services, IConfiguration mqttConfiguration)
            where TMqttSettings : MqttSettings, new()
        {
            services.AddOptions <TMqttSettings>()
            .Bind(mqttConfiguration)
            .ValidateDataAnnotations();

            services.AddSingleton(sp =>
            {
                var mqttSettings = sp.GetRequiredService <IOptions <TMqttSettings> >().Value;

                var mqttClientOptionsBuilder = new MqttClientOptionsBuilder()
                                               .WithTcpServer(mqttSettings.Host, mqttSettings.Port)
                                               .WithProtocolVersion(mqttSettings.MqttProtocolVersion ?? MqttProtocolVersion.V500);

                if (mqttSettings.ClientId != null)
                {
                    mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithClientId(mqttSettings.ClientId);
                }

                if (mqttSettings.CommunicationTimeout.HasValue)
                {
                    mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithCommunicationTimeout(mqttSettings.CommunicationTimeout.Value);
                }

                mqttClientOptionsBuilder = mqttSettings.KeepAliveInterval.HasValue ?
                                           mqttClientOptionsBuilder.WithKeepAlivePeriod(mqttSettings.KeepAliveInterval.Value) :
                                           mqttClientOptionsBuilder.WithNoKeepAlive();

                var lastWillAndTestamentMessage = mqttSettings.GetLastWillAndTestamentApplicationMessage();
                if (lastWillAndTestamentMessage != null)
                {
                    mqttClientOptionsBuilder = mqttClientOptionsBuilder.WithWillMessage(lastWillAndTestamentMessage);
                }

                return(mqttClientOptionsBuilder.Build());
            });

            services.AddSingleton <IMqttFactory, MqttFactory>();
            services.AddTransient(sp =>
            {
                var factory = sp.GetRequiredService <IMqttFactory>();
                var client  = factory.CreateMqttClient();
                return(client);
            });

            return(services);
        }
Example #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;
            }
        }
Example #6
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);
        }