public async Task ConnectAsync(MqttApplicationMessage willApplicationMessage = null) { MqttTrace.Verbose(nameof(MqttClient), "Trying to connect."); if (IsConnected) { throw new MqttProtocolViolationException("It is not allowed to connect with a server after the connection is established."); } var connectPacket = new MqttConnectPacket { ClientId = _options.ClientId, Username = _options.UserName, Password = _options.Password, CleanSession = _options.CleanSession, KeepAlivePeriod = (ushort)_options.KeepAlivePeriod.TotalSeconds, WillMessage = willApplicationMessage }; await _adapter.ConnectAsync(_options, _options.DefaultCommunicationTimeout); MqttTrace.Verbose(nameof(MqttClient), "Connection with server established."); _cancellationTokenSource = new CancellationTokenSource(); _latestPacketIdentifier = 0; _processedPublishPackets.Clear(); _packetDispatcher.Reset(); IsConnected = true; #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(() => ReceivePackets(_cancellationTokenSource.Token), _cancellationTokenSource.Token); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed var response = await SendAndReceiveAsync <MqttConnAckPacket>(connectPacket); if (response.ConnectReturnCode != MqttConnectReturnCode.ConnectionAccepted) { await DisconnectAsync(); throw new MqttConnectingFailedException(response.ConnectReturnCode); } if (_options.KeepAlivePeriod != TimeSpan.Zero) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(() => SendKeepAliveMessagesAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } Connected?.Invoke(this, EventArgs.Empty); }
public async Task ConnectAsync(MqttApplicationMessage willApplicationMessage = null) { ThrowIfConnected("It is not allowed to connect with a server after the connection is established."); try { _cancellationTokenSource = new CancellationTokenSource(); _latestPacketIdentifier = 0; _packetDispatcher.Reset(); MqttTrace.Verbose(nameof(MqttClient), "Trying to connect with server."); await _adapter.ConnectAsync(_options.DefaultCommunicationTimeout, _options).ConfigureAwait(false); MqttTrace.Verbose(nameof(MqttClient), "Connection with server established."); StartReceivePackets(_cancellationTokenSource.Token); var connectPacket = new MqttConnectPacket { ClientId = _options.ClientId, Username = _options.UserName, Password = _options.Password, CleanSession = _options.CleanSession, KeepAlivePeriod = (ushort)_options.KeepAlivePeriod.TotalSeconds, WillMessage = willApplicationMessage }; var response = await SendAndReceiveAsync <MqttConnAckPacket>(connectPacket).ConfigureAwait(false); if (response.ConnectReturnCode != MqttConnectReturnCode.ConnectionAccepted) { throw new MqttConnectingFailedException(response.ConnectReturnCode); } MqttTrace.Verbose(nameof(MqttClient), "MQTT connection with server established."); if (_options.KeepAlivePeriod != TimeSpan.Zero) { StartSendKeepAliveMessages(_cancellationTokenSource.Token); } Connected?.Invoke(this, EventArgs.Empty); } catch (Exception) { await DisconnectInternalAsync().ConfigureAwait(false); throw; } }
public void EnqueuePublishPacket(MqttPublishPacket publishPacket) { if (publishPacket == null) { throw new ArgumentNullException(nameof(publishPacket)); } if (!_subscriptionsManager.IsSubscribed(publishPacket)) { return; } _messageQueue.Enqueue(publishPacket); MqttTrace.Verbose(nameof(MqttClientSession), "Client '{0}': Enqueued pending publish packet.", _identifier); }
private GetOrCreateClientSessionResult GetOrCreateClientSession(MqttConnectPacket connectPacket) { lock (_syncRoot) { MqttClientSession clientSession; var isSessionPresent = _clientSessions.TryGetValue(connectPacket.ClientId, out clientSession); if (isSessionPresent) { if (connectPacket.CleanSession) { _clientSessions.Remove(connectPacket.ClientId); clientSession.Dispose(); clientSession = null; MqttTrace.Verbose(nameof(MqttClientSessionsManager), $"Disposed existing session of client '{connectPacket.ClientId}'."); } else { MqttTrace.Verbose(nameof(MqttClientSessionsManager), $"Reusing existing session of client '{connectPacket.ClientId}'."); } } var isExistingSession = true; if (clientSession == null) { isExistingSession = false; clientSession = new MqttClientSession(connectPacket.ClientId, _options, DispatchPublishPacket); _clientSessions[connectPacket.ClientId] = clientSession; MqttTrace.Verbose(nameof(MqttClientSessionsManager), $"Created a new session for client '{connectPacket.ClientId}'."); } return(new GetOrCreateClientSessionResult { IsExistingSession = isExistingSession, Session = clientSession }); } }