Skip to content

MqttConnectingFailedException: Error while authenticating. Received packet 'PubAck: [PacketIdentifier=21584] [ReasonCode=Success]' at an unexpected time. #1387

@Huntk23

Description

@Huntk23

Describe the bug

I am trying to setup a broker/server instance in a .NET 6 minimal Web API project and then connect to it using a BackgroundService for testing. When trying to use mqttClient.ConnectAsync I receive an error while authenticating message when I did not setup any kind of authentication.

I've spent hours going through documentation and countless examples. I know 4.0 is new with a lot of changes.. Am I somehow missing something?

Which component is your bug related to?

  • MqttClient

To Reproduce

Steps to reproduce the behavior:

  1. Using this version of MQTTnet 4.0.0-preview5
  2. Run the code below in a new Program.cs .NET 6.0 minimal Web API project.

Expected behavior

I expected the client to connect.

Screenshots

N/A

Additional context / logging

MQTTnet.Adapter.MqttConnectingFailedException: Error while authenticating. Received packet 'PubAck: [PacketIdentifier=21584] [ReasonCode=Success]' at an unexpected time.
 ---> MQTTnet.Exceptions.MqttProtocolViolationException: Received packet 'PubAck: [PacketIdentifier=21584] [ReasonCode=Success]' at an unexpected time.
   at MQTTnet.Client.MqttClient.TryProcessReceivedPacketAsync(MqttBasePacket packet, CancellationToken cancellationToken)
   at MQTTnet.PacketDispatcher.MqttPacketAwaitable`1.WaitOneAsync(TimeSpan timeout)
   at MQTTnet.Client.MqttClient.SendAndReceiveAsync[TResponsePacket](MqttBasePacket requestPacket, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.AuthenticateAsync(MqttClientOptions options, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MQTTnet.Client.MqttClient.AuthenticateAsync(MqttClientOptions options, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(MqttClientOptions options, CancellationToken cancellationToken)
   at MQTTnet.Client.MqttClient.ConnectAsync(MqttClientOptions options, CancellationToken cancellationToken)
   at Premier.MQTT.Broker.Worker.ExecuteAsync(CancellationToken stoppingToken) in C:\Development\Premier-MQTT\src\Premier.MQTT.Broker\Worker.cs:line 18
   at Microsoft.Extensions.Hosting.Internal.Host.TryExecuteBackgroundServiceAsync(BackgroundService backgroundService)

Code example

.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MQTTnet" Version="4.0.0-preview5" />
    <PackageReference Include="MQTTnet.AspNetCore" Version="4.0.0-preview5" />
  </ItemGroup>

</Project>

Program.cs

using MQTTnet;
using MQTTnet.AspNetCore;
using MQTTnet.Client;
using MQTTnet.Server;

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.UseKestrel(options => options.ListenAnyIP(1883));

// Add services to the container.
builder.Services.AddMqttServer();
builder.Services.AddConnections();

builder.Services.AddHostedService<Worker>();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseRouting();

app.UseEndpoints(routeBuilder => { routeBuilder.MapMqtt("/mqtt"); });

app.UseMqttServer(server =>
{
    server.StartedAsync += args =>
    {
        _ = Task.Run(async () =>
        {
            var mqttApplicationMessage = new MqttApplicationMessageBuilder()
                .WithPayload("Test application message from MQTTnet server.")
                .WithTopic("message")
                .Build();

            while (true)
            {
                try
                {
                    await server.InjectApplicationMessage(new MqttInjectedApplicationMessage(mqttApplicationMessage)
                    {
                        SenderClientId = "server"
                    });
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                finally
                {
                    await Task.Delay(TimeSpan.FromSeconds(5));
                }
            }
        });

        return Task.CompletedTask;
    };
});

app.Run();

public class Worker : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var options = new MqttClientOptionsBuilder()
            .WithClientId("TestClient")
            .WithTcpServer("127.0.0.1")
            .Build();

        var factory = new MqttFactory();
        var mqttClient = factory.CreateMqttClient();

        await mqttClient.ConnectAsync(options, CancellationToken.None);

        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(5000);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions