/// <summary> /// Wrapper to assure an MQTT connection /// </summary> /// <param name="logger"></param> /// <param name="mqttFactory"></param> /// <param name="mqttConfig"></param> public AssuredMqttConnection( ILogger <AssuredMqttConnection> logger, IMqttFactoryWrapper mqttFactory, IOptions <MqttConfiguration> mqttConfig) { _logger = logger; _logger.LogDebug("MQTT initiating connection"); _connectionTask = Task.Run(() => ConnectAsync(mqttConfig.Value, mqttFactory)); }
private async Task ConnectAsync(MqttConfiguration mqttConfig, IMqttFactoryWrapper mqttFactory) { _logger.LogDebug("Connecting to MQTT broker at {Host}:{Port}/{UserName}", mqttConfig.Host, mqttConfig.Port, mqttConfig.UserName); var clientOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithTcpServer(mqttConfig.Host, mqttConfig.Port) .WithCredentials(mqttConfig.UserName, mqttConfig.Password)) .Build(); _mqttClient = mqttFactory.CreateManagedMqttClient(); _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(LogConnectedStatus); _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(LogDisconnectedStatus); await _mqttClient.StartAsync(clientOptions); _logger.LogDebug("MQTT client is ready"); }