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?
It was important to put the subscribe after the connect for me, else I was having the same problem as you.