Exemplo n.º 1
0
        /// <inheritdoc cref="IMqttClientConfigBuilder.SendKeepAlive" />
        public IMqttClientConfigBuilder SendKeepAlive(TimeSpan interval)
        {
            Check.Range(interval, nameof(interval), TimeSpan.Zero, TimeSpan.MaxValue);

            _builder.WithKeepAlivePeriod(interval);
            return(this);
        }
Exemplo n.º 2
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);
        }
        /// <summary>
        /// Opens the component.
        /// </summary>
        /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
        public async Task OpenAsync(string correlationId)
        {
            var options = await _connectionResolver.ResolveAsync(correlationId);

            var opts = new MqttClientOptionsBuilder()
                       .WithClientId(_clientId);

            if (_keepAliveTimeout > 0)
            {
                opts.WithKeepAlivePeriod(TimeSpan.FromMilliseconds(_keepAliveTimeout));
            }
            else
            {
                opts.WithNoKeepAlive();
            }

            var uri     = options.GetAsString("servers") ?? "";
            var servers = uri.Split(',');

            foreach (var server in servers)
            {
                var host = server;
                var port = 1883;

                var pos = server.IndexOf(":");
                if (pos > 0)
                {
                    host = server.Substring(0, pos);
                    Int32.TryParse(server.Substring(pos + 1), out port);
                }

                opts.WithTcpServer(host, port);
            }

            var username = options.GetAsString("username");

            if (!string.IsNullOrEmpty(username))
            {
                var password = options.GetAsString("password");
                opts.WithCredentials(username, password);
            }

            //opts.SetAutoReconnect(c.retryConnect)
            //opts.SetConnectTimeout(time.Millisecond * time.Duration(c.connectTimeout))
            //opts.SetConnectRetryInterval(time.Millisecond * time.Duration(c.reconnectTimeout))

            var client = new MqttFactory().CreateMqttClient();

            client.UseDisconnectedHandler(DisconnectedHandlerAsync);
            client.UseApplicationMessageReceivedHandler(MessageReceiveHandlerAsync);

            try
            {
                await client.ConnectAsync(opts.Build());
            }
            catch (Exception ex)
            {
                _logger.Error(correlationId, ex, "Failed to connect to MQTT broker at " + uri);
                throw ex;
            }

            _connection    = client;
            _clientOptions = opts.Build();

            _logger.Debug(correlationId, "Connected to MQTT broker at " + uri);
        }
Exemplo n.º 4
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);
        }