Raspberry Pi


So you have a Mosquitto or other broker setup with MQTT. This article now describes a piece of stub code which allows you to subscribe to incoming messages. So if you have an IoT Raspberry Pi Device, you can subscribe to a topic from a completely different environment. See the magic?

CSharp Client

The CSharp MQTT Library - M2Mqtt

Please find a nice description of the M2Mqtt library here. Basically you can either get the code or use the Nuget package to add it to your project. So, just startup a project of choice and, if choosing Nuget, add the references via the Nuget console:

PM> Install-Package M2Mqtt 

That's it. Now you can start subscribing.

Subscription code

Now below is an example of subscribing to a topic of your choice. For further reference check the tutorials in the Links section.

static void Subscribe()
    // create client instance (both host name and IP address work nicely)
    MqttClient client = new MqttClient("<your PI hostname>");

    // register to message received 
    client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

    string clientId = Guid.NewGuid().ToString();

    // subscribe to the topic "/home/temperature" with QoS 2 
    client.Subscribe(new string[] { "home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });

static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
    // handle message received 
    Console.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);