1
votes

MQTT in c#

I have two button in my xaml page. One is to Publish the message and other is to subscribe the topic. I have installed mosquitto as broker. In Publish button, i have written code to publish the message and in mosquitto cmd prompt, i can receive the message. In viceversa, in subscribe button, i have subscribed to one topic and in cmd prompt i am publishing message, where can i view the message in subscribe button?

 Case 1:       
    In cmd propmt, i will subscribe to the topic,
    mosquitto_sub -h 190.178.4.180 -t “test1”  

    private async void BtnPublish_Click(object sender, RoutedEventArgs e)
    {     
        var message = new MqttApplicationMessage("test1", Encoding.UTF8.GetBytes("Hello"));

        await client.PublishAsync(message, MqttQualityOfService.ExactlyOnce);
    }

    I will receive Hello in cmd propmt.

 Case 2:

    In cmd prompt, i will publish the message in some topic,
    mosquitto_pub -h 192.168.0.180 -t test1 -m "HelloWorld"

    private async void BtnSubscrbe_Click(object sender, RoutedEventArgs e)
    {
        await client.SubscribeAsync("test1", MqttQualityOfService.ExactlyOnce);
        var message = client.MessageStream;
    } 

 If i click the button subscribe, where will i get the published message?

Thanks in advance.

2

2 Answers

1
votes

The MessageStream property returns an IObservable that you are supposed to subscribe to:

private async void BtnSubscrbe_Click(object sender, RoutedEventArgs e)
{
    client.MessageStream.Subscribe(msg =>
    {
        string topic = msg.Topic;
        byte[] payload = msg.Payload;
        //deserialize and do something...
    });

    await client.SubscribeAsync("test1", MqttQualityOfService.ExactlyOnce);
}
0
votes

As I understand it, you need to hook a delegate using MqttMsgPublishReceived See https://www.hivemq.com/blog/mqtt-client-library-encyclopedia-m2mqtt/

client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

and

void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
     Debug.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
}