mqttnet client not getting subscribed topics

13.2k Views Asked by At

I'm using mqtt.net (https://github.com/chkr1011/MQTTnet) and have written a small class to handle my mqtt client. The client connects to the broker and publishes it's messages successfully. Now I want the client to also react on some topics I subscribe the client to. But this does not seem to work. I do not get any breakpoint hit. This are the relevant parts of my code:

    public async Task StartAsync(CancellationToken cancellationToken)
            {
        //Building the mqtt config
        var options = new MqttClientOptionsBuilder()
            .WithTcpServer(MqttConfig.Server, MqttConfig.Port)
            .WithClientId("HeaterService")
            .WithCredentials(MqttConfig.User, MqttConfig.Password)
            .WithTls(tlsParameters =>
            {
                tlsParameters.AllowUntrustedCertificates = true;
            })
            .WithCleanSession()
            .Build();

        //Getting an mqtt Instance
        MqttClient = new MqttFactory().CreateMqttClient();

        //Wiring up all the events...
        MqttClient.UseApplicationMessageReceivedHandler( e => { HandleMessageReceived(e.ApplicationMessage); });

        MqttClient.UseConnectedHandler(/*async*/ e =>
        {
            Console.WriteLine("### CONNECTED WITH BROKER ###");

        });

      await MqttClient.ConnectAsync(options);
}

The client connects successfully to the server and is possible to publish messages.

This is my messagehandler function:

private void HandleMessageReceived(MqttApplicationMessage applicationMessage)
{
    Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
    Console.WriteLine($"+ Topic = {applicationMessage.Topic}");

    Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(applicationMessage.Payload)}");
    Console.WriteLine($"+ QoS = {applicationMessage.QualityOfServiceLevel}");
    Console.WriteLine($"+ Retain = {applicationMessage.Retain}");
    Console.WriteLine();
}

This is my subscribe code:

public async Task SubscribeTopic(string topic)
{
   var subscribeResult = await MqttClient.SubscribeAsync(new TopicFilterBuilder()
      .WithTopic(topic)
      //.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
      .Build());

   Console.WriteLine("### SUBSCRIBED ###");
   Console.WriteLine("### Result: " + subscribeResult.Items.FirstOrDefault()?.ResultCode);
   Console.WriteLine("### Result: " + subscribeResult.Items.FirstOrDefault()?.TopicFilter);
}

I call this function of my class with "Home/Heater/control/*";

When I use mqtt-explorer to send a test message to the topic "Home/Heater/control/test"

the functionhandler HandleMessageReceived is never hit.

What I am doing wrong?

2

There are 2 best solutions below

0
Linuxx On

It was important to put the subscribe after the connect for me, else I was having the same problem as you.

objClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(ReceivedMessage);

string[] strTopics = { "test/log", "test/log2" };

MqttClientSubscribeOptions objSubOptions = new MqttClientSubscribeOptions();
List<TopicFilter> objTopics = new List<TopicFilter>();

foreach(string strTopic in strTopics)
{
    TopicFilter objAdd = new TopicFilter();
    objAdd.Topic = strTopic;
    objTopics.Add(objAdd);
}

 objSubOptions.TopicFilters = objTopics;
 objClient.ConnectAsync(objOptions, CancellationToken.None).Wait();
 objClient.SubscribeAsync(objSubOptions); //!!!!subscribe goes here!!!!
2
Joren On

It seems like you currently don't call your SubscribeTopic(string topic) method in your StartAsync(CancellationToken cancellationToken) method.

Besides that i personally also ran into a few problems when starting out with MQTTNet. Like @Linuxx said pay attention to the order in wich you call subscribe and connect. I also recommend adding a Disconnected_Handler to your client to make sure the connection doesn't terminate without your knowing.