protected virtual void Dispose(bool disposing) { if (disposing) { mqttClient?.Dispose(); } }
private async void BtnDisConnect_Click(object sender, EventArgs e) { await _mqttClient.DisconnectAsync(); _mqttClient.Dispose(); _mqttClient = null; }
public async void Dispose() { if (mqttClient != null) { if (mqttClient.IsConnected) { Log($"Debug: MQTT: Disconnecting from server."); try { await mqttClient.DisconnectAsync(); } catch (Exception ex) { //dont throw ERROR in the log if fail to disconnect Log($"Debug: MQTT: Could not disconnect from server, got: {ex.Msg()}"); } } else { Log($"Debug: MQTT: Already disconnected from server, no need to disconnect."); } IsConnected = false; mqttClient.Dispose(); } }
public void Dispose() { if (client != null) { client.Dispose(); } }
public void Dispose() { sensor.PropertyChanged -= SensorOnPropertyChanged; client.UseApplicationMessageReceivedHandler((IMqttApplicationMessageReceivedHandler)null); client.Dispose(); }
private async void Disconnect(object sender, RoutedEventArgs e) { try { if (_mqttClient != null) { await _mqttClient.DisconnectAsync(); _mqttClient.Dispose(); _mqttClient = null; } if (_managedMqttClient != null) { await _managedMqttClient.StopAsync(); _managedMqttClient.Dispose(); _managedMqttClient = null; } } catch (Exception exception) { Trace.Text += exception + Environment.NewLine; } }
public async Task when_connect_clients_then_succeeds(int count) { List <IMqttClient> clients = new List <IMqttClient>(); List <string> clientIds = new List <string>(); List <Task> tasks = new List <Task>(); for (int i = 1; i <= count; i++) { IMqttClient client = await GetClientAsync(); string clientId = MqttTestHelper.GetClientId(); tasks.Add(client.ConnectAsync(new MqttClientCredentials(clientId))); clients.Add(client); clientIds.Add(clientId); } await Task.WhenAll(tasks); Server.ActiveClients.Where(c => clientIds.Contains(c)).Should().HaveCount(count); Assert.True(clients.All(c => c.IsConnected)); Assert.True(clients.All(c => !string.IsNullOrEmpty(c.Id))); foreach (IMqttClient client in clients) { client.Dispose(); } }
/// <summary> /// Disconnects and disposes the MQTT client. /// </summary> private void Disconnect(IMqttClient mqttClient) { if (mqttClient == null || !mqttClient.IsConnected) { return; } try { logHelper.WriteMessage(string.Format(Locale.IsRussian ? "Отключение от {0}:{1}" : "Disconnect from {0}:{1}", connOptions.Server, connOptions.Port)); mqttClient.DisconnectAsync().Wait(); } catch (Exception ex) { logHelper.WriteError(string.Format(Locale.IsRussian ? "Ошибка при отключении: {0}" : "Error disconnecting: {0}", ex.Message)); } finally { mqttClient.Dispose(); } }
public async Task when_in_process_client_communicate_with_tcp_client_then_succeeds() { IMqttConnectedClient inProcessClient = await Server.CreateClientAsync(); IMqttClient remoteClient = await GetClientAsync(); await remoteClient.ConnectAsync(new MqttClientCredentials( MqttTestHelper.GetClientId())); string fooTopic = "foo/message"; string barTopic = "bar/message"; await inProcessClient.SubscribeAsync(fooTopic, MqttQualityOfService.ExactlyOnce); await remoteClient.SubscribeAsync(barTopic, MqttQualityOfService.AtLeastOnce); int fooMessagesReceived = 0; int barMessagesReceived = 0; inProcessClient.MessageStream.Subscribe(message => { if (message.Topic == fooTopic) { fooMessagesReceived++; } }); remoteClient.MessageStream.Subscribe(message => { if (message.Topic == barTopic) { barMessagesReceived++; } }); await remoteClient.PublishAsync(new MqttApplicationMessage( fooTopic, new byte[255] ), MqttQualityOfService.AtMostOnce); await remoteClient.PublishAsync(new MqttApplicationMessage( fooTopic, new byte[10] ), MqttQualityOfService.AtLeastOnce); await remoteClient.PublishAsync(new MqttApplicationMessage( "other/topic", new byte[500] ), MqttQualityOfService.ExactlyOnce); await remoteClient.PublishAsync(new MqttApplicationMessage( fooTopic, new byte[50] ), MqttQualityOfService.ExactlyOnce); await inProcessClient.PublishAsync(new MqttApplicationMessage( barTopic, new byte[255] ), MqttQualityOfService.AtMostOnce); await inProcessClient.PublishAsync(new MqttApplicationMessage( barTopic, new byte[10] ), MqttQualityOfService.AtLeastOnce); await inProcessClient.PublishAsync(new MqttApplicationMessage( "other/topic", new byte[500] ), MqttQualityOfService.ExactlyOnce); await inProcessClient.PublishAsync(new MqttApplicationMessage( barTopic, new byte[50] ), MqttQualityOfService.ExactlyOnce); await Task.Delay(TimeSpan.FromMilliseconds(1000)); Assert.True(inProcessClient.IsConnected); Assert.True(remoteClient.IsConnected); fooMessagesReceived.Should().Be(3); barMessagesReceived.Should().Be(3); inProcessClient.Dispose(); remoteClient.Dispose(); }
public async Task StopAsync(CancellationToken cancellationToken) { logger.LogInformation("Disconnecting and disposing"); await mqttClient.DisconnectAsync(); mqttClient.Dispose(); pioneerConnection.Dispose(); }
public void Cleanup() { _mqttClient.DisconnectAsync().GetAwaiter().GetResult(); _mqttClient.Dispose(); _host.StopAsync().GetAwaiter().GetResult(); _host.Dispose(); }
public void Dispose() { if (mqtt_client != null) { mqtt_client.Dispose(); } OnDisposing(); }
private void OnDisable() { Debug.Log("disconnect"); aborting = true; this.receiveEventThread.Abort(); _client.DisconnectAsync().ConfigureAwait(false); _client.Dispose(); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { if (await TryConnecting() == false) { return; } while (!stoppingToken.IsCancellationRequested) { try { if (subscriber.PublishQueues.TryDequeue(out DataMessage datamessage)) { MqttApplicationMessage message = datamessage.Message; DateTime timestamp = datamessage.Timestamp; string logger = datamessage.LoggerNameByCategory; if (datamessage.Category != 6) // 기온 습도는 아직 브로커에 전달하지 않음 { await mqtt_client.PublishAsync(message, stoppingToken); if (datamessage.StatusMessage != null) { await mqtt_client.PublishAsync(datamessage.StatusMessage, stoppingToken); } } var data_logger = NLog.LogManager.GetLogger(logger); LogEventInfo logEvent = new LogEventInfo(NLog.LogLevel.Info, logger, ""); logEvent.TimeStamp = timestamp.ToUniversalTime(); ReadMembers(datamessage.Data, null, logEvent.Properties); logEvent.Message = "DataLog"; data_logger.Log(logEvent); _logger.LogInformation("Log Write.."); } if (subscriber.PublishEventQueues.TryDequeue(out EventModel eventModel)) { string evtMessage = JsonConvert.SerializeObject(eventModel); var msg = ModelConverter.CreateMessage(evtMessage, eventModel.GetTopicName()); await mqtt_client.PublishAsync(msg, stoppingToken); } } catch (MQTTnet.Exceptions.MqttCommunicationException mqttex) { mqtt_client.Dispose(); mqtt_client = null; await TryConnecting(); } catch (Exception ex) { _logger.LogError(ex, ex.Message); } await Task.Delay(100, stoppingToken); } }
public async void Dispose() { await _mqttClient.UnsubscribeAsync(Subscribes); await _mqttClient.DisconnectAsync(); _mqttClient.Dispose(); _mqttClient = null; }
public void Dispose() { if (_mqttClient != null) { _mqttClient.Dispose(); } _subsManager.Clear(); }
/// <summary> /// Disconnects and disposes the MQTT client. /// </summary> public void Close() { if (mqttClient.IsConnected) { Disconnect(); } mqttClient.Dispose(); }
public void Dispose() { CancellationTokenSource.Cancel(); if (client.IsConnected) { client.DisconnectAsync(); client.Dispose(); } }
private void CombServer_SelectedIndexChanged(object sender, EventArgs e) { if (mqttClient != null) { mqttClient.Dispose(); mqttClient = null; } Task.Run(async() => { await ConnectMqttServerAsync(); }); }
private static async Task CloseIntern(IMqttClient client) { try { await client.DisconnectAsync(); } catch (Exception) { } try { client.Dispose(); } catch (Exception) { } }
protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _mqttClient?.Dispose(); } disposedValue = true; } }
private async void BtnDisConnect_Click(object sender, EventArgs e) { int num = int.Parse(this.tbClientNum.Text); for (int i = 0; i < num; i++) { IMqttClient _mqttClient = _mqttClients[i]; if (null != _mqttClient && _mqttClient.IsConnected) { await _mqttClient.DisconnectAsync(); _mqttClient.Dispose(); _mqttClient = null; } else { _mqttClient.Dispose(); _mqttClient = null; } } _mqttClients.Clear(); _mqttClients = new List <IMqttClient>(); }
public void Dispose() { logger.LogDebug("Dispose requested... "); if (internalCancellationTokenSource.IsCancellationRequested) { logger.LogWarning("Dispose requested for already disposed object!"); return; } internalCancellationTokenSource.Cancel(); client.UseDisconnectedHandler((IMqttClientDisconnectedHandler)null); client?.Dispose(); logger.LogInformation("Disposed."); }
private Task <ITransition> DisposeClient() { try { _client.Dispose(); } catch { // We're terminating so don't really // care if an exception is thrown here } return(Task.FromResult <ITransition>(new Transition.ToTerminated())); }
public async Task when_keep_alive_enabled_and_client_is_disposed_then_server_refresh_active_client_list() { IMqttClient client = await GetClientAsync(); await client.ConnectAsync(new MqttClientCredentials( MqttTestHelper.GetClientId())); string clientId = client.Id; bool existClientAfterConnect = Server.ActiveClients.Any(c => c == clientId); ManualResetEventSlim clientClosed = new ManualResetEventSlim(); IDisposable subscription = Observable.Create <bool>(observer => { System.Timers.Timer timer = new System.Timers.Timer(); timer.Interval = 200; timer.Elapsed += (sender, args) => { if (Server.ActiveClients.Any(c => c == clientId)) { observer.OnNext(false); } else { observer.OnNext(true); clientClosed.Set(); observer.OnCompleted(); } }; timer.Start(); return(() => { timer.Dispose(); }); }) .Subscribe( _ => { }, ex => { Console.WriteLine($"Error: {ex.Message}"); }); client.Dispose(); bool serverDetectedClientClosed = clientClosed.Wait(TimeSpan.FromSeconds(KeepAliveSecs * 2)); subscription.Dispose(); Assert.True(existClientAfterConnect); Assert.True(serverDetectedClientClosed); Assert.False(Server.ActiveClients.Any(c => c == clientId)); }
public async Task <bool> Stop() { if (_mqttClient != null) { await _mqttClient?.DisconnectAsync(); _mqttClient?.Dispose(); } if (_mqttServer != null) { await _mqttServer.StopAsync(); } return(true); }
async ValueTask IAsyncDisposable.DisposeAsync() { Console.WriteLine("disposoing"); try { if (_mqtt != null) { await _mqtt.DisconnectAsync(); } } finally { _mqtt?.Dispose(); } }
public async Task when_keep_alive_enabled_and_no_packets_are_sent_then_connection_is_maintained() { IMqttClient client = await GetClientAsync(); string clientId = MqttTestHelper.GetClientId(); await client.ConnectAsync(new MqttClientCredentials( clientId )); await Task.Delay(TimeSpan.FromSeconds(KeepAliveSecs * 5)); Assert.True(Server.ActiveClients.Any(c => c == clientId)); Assert.True(client.IsConnected); Assert.False(string.IsNullOrEmpty(client.Id)); client.Dispose(); }
public async Task when_client_disconnects_then_message_stream_completes() { ManualResetEventSlim streamCompletedSignal = new ManualResetEventSlim(initialState: false); IMqttClient client = await GetClientAsync(); await client.ConnectAsync(new MqttClientCredentials( MqttTestHelper.GetClientId())); client.MessageStream.Subscribe(_ => { }, onCompleted: () => streamCompletedSignal.Set()); await client.DisconnectAsync(); bool streamCompleted = streamCompletedSignal.Wait(2000); Assert.True(streamCompleted); client.Dispose(); }
// Protected implementation of Dispose pattern. protected virtual void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { // Free any other managed objects here. _client.Dispose(); } // Free any unmanaged objects here. // disposed = true; }