Esempio n. 1
0
        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);
        }
Esempio n. 2
0
        public async Task <MqttClientConnectResult> ConnectAsync(IMqttClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (options.ChannelOptions == null)
            {
                throw new ArgumentException("ChannelOptions are not set.");
            }

            ThrowIfConnected("It is not allowed to connect with a server after the connection is established.");

            try
            {
                _options = options;
                _cancellationTokenSource = new CancellationTokenSource();
                _latestPacketIdentifier  = 0;
                _packetDispatcher.Reset();

                _adapter = _communicationAdapterFactory.CreateClientCommunicationAdapter(options);

                _scopeHandle = _logger.BeginScope(options.LogId ?? options.ClientId);
                _logger.LogTrace("Trying to connect with server.");
                await _adapter.ConnectAsync(_options.CommunicationTimeout).ConfigureAwait(false);

                _logger.LogTrace("Connection with server established.");

                await StartReceivingPacketsAsync(_cancellationTokenSource.Token).ConfigureAwait(false);

                var connectResponse = await AuthenticateAsync(options.WillMessage).ConfigureAwait(false);

                _logger.LogTrace("MQTT connection with server established.");

                if (_options.KeepAlivePeriod != TimeSpan.Zero)
                {
                    StartSendingKeepAliveMessages(_cancellationTokenSource.Token);
                }

                IsConnected = true;
                Connected?.Invoke(this, new MqttClientConnectedEventArgs(connectResponse.IsSessionPresent));
                return(new MqttClientConnectResult(connectResponse.IsSessionPresent));
            }
            catch (Exception exception)
            {
                _logger.LogError(new EventId(), exception, "Error while connecting with server.");
                await DisconnectInternalAsync().ConfigureAwait(false);

                throw;
            }
        }
Esempio n. 3
0
        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;
            }
        }
Esempio n. 4
0
        public async Task ConnectAsync(MqttClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            ThrowIfConnected("It is not allowed to connect with a server after the connection is established.");

            try
            {
                _options = options;
                _cancellationTokenSource = new CancellationTokenSource();
                _latestPacketIdentifier  = 0;
                _packetDispatcher.Reset();

                _adapter = _communicationChannelFactory.CreateMqttCommunicationAdapter(options);

                MqttNetTrace.Verbose(nameof(MqttClient), "Trying to connect with server.");
                await _adapter.ConnectAsync(_options.DefaultCommunicationTimeout).ConfigureAwait(false);

                MqttNetTrace.Verbose(nameof(MqttClient), "Connection with server established.");

                await SetupIncomingPacketProcessingAsync();
                await AuthenticateAsync(options.WillMessage);

                MqttNetTrace.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;
            }
        }