2020.09.01.

Xamarin.Forms – Using MQTT and Azure IoT Hub

By bence960206

If you have an Azure IoT Hub, you may also need a mobile app. You can communicate with Azure IoT Hub just like a regular MQTT.

First step: create a Xamarin.Forms application (but very important, you can use this snippet in any native project, just copy this to the platform’s project).

Right click on the Standard Library and click on Manage NuGet Packages.

Add the MQTTnet NuGet Package to your project.

Create a new class, and call it: AzureMQTTConnection. In this class we will implementing the connection between Azure IoT Hub and Xamarin.Forms Application.

using MQTTnet;
using MQTTnet.Core.Client;
using MQTTnet.Core.Packets;
using MQTTnet.Core.Protocol;
using System;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace IoTMobile
{
    public class AzureMQTTConnection
    {
        #region Properties

        public IMqttClient mqttClient;

        private int _port;
        private string _server;
        private string _clientID;
        private string _userName;
        private string _password;
        private MQTTnet.Core.Serializer.MqttProtocolVersion _protocolVersion;
        private MqttClientTlsOptions _tlsOption;
        private bool _cleanSession;

        #endregion

        public AzureMQTTConnection(string server, int port, string clientID, string userName, string password, MQTTnet.Core.Serializer.MqttProtocolVersion protocolVersion, MqttClientTlsOptions tlsOption, bool cleanSession)
        {
            _server = server;
            _port = port;
            _clientID = clientID;
            _userName = userName;
            _password = password;
            _protocolVersion = protocolVersion;
            _tlsOption = tlsOption;
            _cleanSession = cleanSession;
        }

        public async Task CreateAzureMQTTConnection()
        {
            var options = new MqttClientTcpOptions()
            {
                Server = _server,
                Port = _port,
                ClientId = _clientID,
                UserName = _userName,
                Password = _password,
                ProtocolVersion = _protocolVersion,
                TlsOptions = _tlsOption,
                CleanSession = _cleanSession
            };

            var factory = new MqttClientFactory();
            mqttClient = factory.CreateMqttClient();

            mqttClient.Connected += MqttClient_Connected;
            mqttClient.Disconnected += MqttClient_Disconnected;

            mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;

            await mqttClient.ConnectAsync(options);
        }

        private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            //You got a message!
        }

        private void MqttClient_Disconnected(object sender, EventArgs e)
        {
            //You are disconnected!
        }

        private async void MqttClient_Connected(object sender, EventArgs e)
        {
            //You are connected!

            // subscribe on the topics
            var topicFilters = new[] {
                new TopicFilter("devices/testdevice/messages/events/#", MqttQualityOfServiceLevel.AtLeastOnce),
            };
            await mqttClient.SubscribeAsync(topicFilters);
        }
    }
}

Perfect! Try it out! Go to App.cs and create a new object:

AzureMQTTConnection = new AzureMQTTConnection(
                "your_iot_hub_host", 
                8883,
                "your_device_name",
                "your_iot_hub_host/your_device_name/api-version=2018-06-30",
                "SharedAccessSignature sr=<your_SAS_key>",
                MQTTnet.Core.Serializer.MqttProtocolVersion.V311,
                new MqttClientTlsOptions() { UseTls = true },
                true);
await AzureMQTTConnection.CreateAzureMQTTConnection();

Okay, but what is SAS key? How can I obtain one? Suppose we have an Azure IoT Hub and we added a Device. After that, we have to download a tool called: Device Explorer Twin: https://github.com/Azure/azure-iot-explorer/releases.

Go to Management and SAS Token. And Click on Generate.

We need just from the SharedAccessSignature sr=<key> section. Copy and paste to the object initialization and that’s all. It will work fine!