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); }
/// <inheritdoc cref="IMqttClientConfigBuilder.DisableKeepAlive" /> public IMqttClientConfigBuilder DisableKeepAlive() { _builder.WithNoKeepAlive(); return(this); }
/// <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); }