public async Task ConnectToBrokerAsync(string nelloTopicId) { try { _nelloTopicId = nelloTopicId; var options = new MqttClientOptionsBuilder() .WithTcpServer(SERVER_ADDRESS, SERVER_PORT) .Build(); _client.UseDisconnectedHandler(async e => { try { await _client.ReconnectAsync(); } catch (Exception ex) { _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString()); } }); _client.UseConnectedHandler(async e => { try { foreach (var topic in _mqttListeningTopics) { await SubscribeToTopicAsync(string.Format("{0}{1}/{2}", TOPIC_PREFIX, _nelloTopicId, topic)); } } catch (Exception ex) { _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString()); } }); _client.UseApplicationMessageReceivedHandler(e => { try { if (e.ApplicationMessage.Topic.StartsWith("/nello_one")) { var args = new MqttMessageEventArgs(); args.ClientId = e.ClientId; args.Message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); args.Topic = e.ApplicationMessage.Topic; MqttMessageReceived?.Invoke(this, args); } } catch (Exception ex) { _logger.LogError("UseDisconnectedHandler error:\n" + ex.ToString()); } }); await _client.ConnectAsync(options); } catch (Exception ex) { _logger.LogError("ConnectToBrokerAsync error:\n" + ex.ToString()); } }
public Task ReconnectAsync() => client.ReconnectAsync();