IoT – MQTT Connects Mobile App & IoT Devices


Internet of Things (IoT) is a trending while mobile devices is so essentials that almost everyone owns one. Previously, I have demonstrated how to connect IoT devices and mobile app through a common network protocol UDP. However, I have received suggestions to use MQTT – a light weighted TCP protocol, which is a very popular IoT Communication Protocol, that works as subscribe-publisher method and promising a guaranteed delivery since it is TCP based.
Therefore, today, I would like to demonstrate how to develop a Cross Platform Mobile Apps that would connect to IoT Devices via MQTT.


Let’s Get Started to Build Mobile App that Connects IoT Device via MQTT

  1. First, we need to create a Xamarin Cross Platform Mobile App. Don’t have one yet? Click to learn how to create one!
  2. Secondly, we need to add a NuGet Packages – MQTTnet, right click Solution in the Solution Explorer -> Manage NuGet Packages for Solution…
  3. Let’s search MQTTnet and install it to all the projects.
  4. Now, we need to add some components to MainPage.xaml as specified below.

      <Label Text="Host:" />
      <Entry x:Name="txtHost" />
      <Label Text="Port:" />
      <Entry x:Name="txtPort" />
      <Label Text="Topic:" />
      <Entry x:Name="txtTopic" />
      <Label Text="Message:" />
      <Entry x:Name="editMessage" HorizontalOptions="FillAndExpand" 
             VerticalOptions="FillAndExpand" />
      <Button x:Name="btnConnect" Text="Connect"/>
      <Button x:Name="btnSend" Text="Send"/>
  5. After that, click the code behind – MainPage.xaml.cs and add the following usings.
    using MQTTnet;
    using MQTTnet.Core;
    using MQTTnet.Core.Client;
    using System;
    using System.Text;
    using Xamarin.Forms;
  6. Now, replace the constructor as below and declare a mqttClient.
    IMqttClient mqttClient;
            public MainPage()
                btnConnect.Clicked += BtnConnect_Clicked;
                btnSend.Clicked += BtnSend_Clicked;
                // Create a new MQTT client.
                var factory = new MqttFactory();
                mqttClient = factory.CreateMqttClient();
                mqttClient.Connected += MqttClient_Connected;
                mqttClient.Disconnected += async (s, e) =>
                    btnConnect.Text = "Connect";
                    btnConnect.IsEnabled = true;
                    Console.WriteLine("### DISCONNECTED WITH SERVER ###");
                mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
  7. Create an Async function for handling BtnConnect’s click event with the following code.
    private async void BtnConnect_Clicked(object sender, EventArgs e)
                    // Use TCP/WebSocket connection.
                    var options = new MqttClientOptionsBuilder()
                        .WithTcpServer(txtHost.Text, Int32.Parse(txtPort.Text))
                    await mqttClient.ConnectAsync(options);
                }catch(Exception ex)
  8. Create an Async function to send the message to MQTT Broker/Server when BtnSend is being clicked.
    private async void BtnSend_Clicked(object sender, EventArgs e)
         var message = new MqttApplicationMessageBuilder()
         await mqttClient.PublishAsync(message);
  9. Create an Async function for handling connected event when MqttClient is successfully connected with MQTT Server.
    private async void MqttClient_Connected(object sender, MqttClientConnectedEventArgs e)
          Device.BeginInvokeOnMainThread(() => {
                    btnConnect.Text = "Connected";
                    btnConnect.IsEnabled = false;
          Console.WriteLine("### CONNECTED WITH SERVER ###");
          // Subscribe to a topic
          await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("Apple").Build());
          Console.WriteLine("### SUBSCRIBED ###");
  10. Lastly, let’s create a function to handle the message it received from Broker.
    private void MqttClient_ApplicationMessageReceived(object sender, MQTTnet.Core.MqttApplicationMessageReceivedEventArgs e)
         if (e.ApplicationMessage.Topic == "response")
             Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
             editMessage.Text = "";
             editMessage.Text += "### RECEIVED APPLICATION MESSAGE ###";
             editMessage.Text += "$ Topic = " + e.ApplicationMessage.Topic;
             editMessage.Text += "$ Payload = " + Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
             editMessage.Text += "$ QoS = " + e.ApplicationMessage.QualityOfServiceLevel;
             editMessage.Text += "$ Retain = " + e.ApplicationMessage.Retain;
  11. Finally, let’s compile and run it on your mobile device. Your MQTT Broker (Get a desktop version here) should be able to receive the message for the topic it subscribed to.


Grab your sample code here & Offline slide here.

Don’t forget to follow me @
Twitter: @hmheng
More slides @ SlideShare:

You may also like...

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: