async Task TryReceivePacketsAsync(CancellationToken cancellationToken) { try { _logger.Verbose("Start receiving packets."); while (!cancellationToken.IsCancellationRequested) { var packet = await _adapter.ReceivePacketAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false); if (cancellationToken.IsCancellationRequested) { return; } if (packet == null) { if (!DisconnectIsPending()) { await DisconnectInternalAsync(_packetReceiverTask, null, null).ConfigureAwait(false); } return; } await TryProcessReceivedPacketAsync(packet, cancellationToken).ConfigureAwait(false); } } catch (Exception exception) { if (_cleanDisconnectInitiated) { return; } if (exception is OperationCanceledException) { } else if (exception is MqttCommunicationException) { _logger.Warning(exception, "Communication error while receiving packets."); } else { _logger.Error(exception, "Error while receiving packets."); } _packetDispatcher.Dispatch(exception); if (!DisconnectIsPending()) { await DisconnectInternalAsync(_packetReceiverTask, exception, null).ConfigureAwait(false); } } finally { _logger.Verbose("Stopped receiving packets."); } }
private async Task ReceivePacketsAsync(CancellationToken cancellationToken) { _logger.Verbose("Start receiving packets."); try { while (!cancellationToken.IsCancellationRequested) { var packet = await _adapter.ReceivePacketAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false); if (packet != null) { await ProcessReceivedPacketAsync(packet, cancellationToken).ConfigureAwait(false); } } } catch (Exception exception) { if (_cleanDisconnectInitiated) { return; } if (exception is OperationCanceledException) { _logger.Verbose("MQTT OperationCanceled exception while receiving packets."); } else if (exception is MqttCommunicationException) { _logger.Warning(exception, "MQTT communication exception while receiving packets."); } else { _logger.Error(exception, "Unhandled exception while receiving packets."); } _packetDispatcher.Dispatch(exception); if (_disconnectReason.TrySetException(exception)) { await DisconnectInternalAsync(_packetReceiverTask, exception).ConfigureAwait(false); } } finally { _logger.Verbose("Stopped receiving packets."); } }
private async Task ProcessReceivedPacketAsync(MqttBasePacket packet) { try { _logger.Info <MqttClient>("Received <<< {0}", packet); if (packet is MqttPublishPacket publishPacket) { await ProcessReceivedPublishPacketAsync(publishPacket).ConfigureAwait(false); return; } if (packet is MqttPingReqPacket) { await SendAsync(new MqttPingRespPacket()).ConfigureAwait(false); return; } if (packet is MqttDisconnectPacket) { await DisconnectAsync().ConfigureAwait(false); return; } if (packet is MqttPubRelPacket pubRelPacket) { await ProcessReceivedPubRelPacket(pubRelPacket).ConfigureAwait(false); return; } _packetDispatcher.Dispatch(packet); } catch (Exception exception) { _logger.Error <MqttClient>(exception, "Unhandled exception while processing received packet."); } }