Reputation: 345
I am doing a POC so here is the quick and dirty code. I use MQTT.fx desktop client to test Pub/Sub to my MQTT Server. Works fine. I can publish/subscribe to my topic. I can publish from another mqtt client and I get the messages. When using this code, I do not receive anything when I publish messages from MQTT.fx or any other publishers. I will receive something if I publish with the mqttClient (if you uncomment the line). I am scratching my head... Can someone help? Thanks.
class Program
{
private static CancellationTokenSource cts = new CancellationTokenSource(); //TODO create token using the Timeout delay from config
private static async Task Main(string[] args)
{
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithClientId("MyClientIDHere")
.WithTcpServer("IPAddressHere", 1883)
//.WithCredentials("Wbo", string.Empty)
//.WithTls()
.WithCleanSession()
.Build();
try
{
mqttClient.UseApplicationMessageReceivedHandler(async e =>
{
Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
Console.WriteLine();
});
mqttClient.UseConnectedHandler(async e =>
{
Console.WriteLine("### CONNECTED WITH SERVER ###");
// Subscribe to a topic
await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("MyClientIDHere/Device_2/Instance_1").Build());
Console.WriteLine("### SUBSCRIBED ###");
});
await mqttClient.ConnectAsync(options, cts.Token);
// UNCOMMENT AND YOU WILL RECEIVE A MESSAGE Task.Run(() => mqttClient.PublishAsync("MyClientIDHere/Device_2/Instance_1","met=Temperature~data=29"));
}
catch (OperationCanceledException)
{
Console.WriteLine("task cancelled");
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
}
Upvotes: 1
Views: 4783
Reputation: 550
With the latest version of MQTTnet I could not reproduce your issue, it seems to work here. I'm using a mosquitto MQTT server which is located on another server than where I run my program.
Your code looks good. You can improve some, by subscribing to the topics before connecting.
Upvotes: 1