Michael
Michael

Reputation: 15

Connect MQTTnet with Azure IoT Hub

I have created a device that delivers messages. Now I want to send them to an Azure IoT Hub by using MQTTnet Version 2.4.0 because the .NET target Framework is on Version 4.5 and it is not my decision to change it.

My Question:

I have tried almost every combination of values for the ClientId/UserName/Password as described here: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-mqtt-support#using-the-mqtt-protocol-directly-as-a-device

but none of them worked for me

I have tried outside the Project and build a similar device on the current framework and it worked perfectly with the newer version of MQTTnet.

Sadly I don't get any kind of error message only a MqttCommunicationTimedOutException after about 10 seconds.

Thanks for your help I have been stuck at this problem for almost a week.

Upvotes: 1

Views: 2432

Answers (1)

Roman Kiss
Roman Kiss

Reputation: 8265

The following code snippet is a working example of the simulated device1 using the MQTT protocol directly to the Azure IoT Hub via the MQTTnet Version 2.4.0 library:

using MQTTnet;
using MQTTnet.Core;
using MQTTnet.Core.Client;
using MQTTnet.Core.Packets;
using MQTTnet.Core.Protocol;
using System;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var options = new MqttClientTcpOptions()
            {                
                Server = "myIoTHub.azure-devices.net",
                Port = 8883,
                ClientId = "device1",
                UserName = "myIoTHub.azure-devices.net/device1/api-version=2018-06-30",              
                Password = "SharedAccessSignature sr=myIoTHub.azure-devices.net%2Fdevices%2Fdevice1&sig=****&se=1592830262",               
                ProtocolVersion = MQTTnet.Core.Serializer.MqttProtocolVersion.V311,
                TlsOptions = new MqttClientTlsOptions() { UseTls = true },
                CleanSession = true
            };

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

            // handlers
            mqttClient.Connected += delegate (object sender, EventArgs e)
            {
                Console.WriteLine("Connected");
            };
            mqttClient.Disconnected += delegate (object sender, EventArgs e)
            {
                Console.WriteLine("Disconnected");
            };
            mqttClient.ApplicationMessageReceived += delegate (object sender, MqttApplicationMessageReceivedEventArgs e)
            {
                Console.WriteLine(Encoding.ASCII.GetString(e.ApplicationMessage.Payload));
            };

            mqttClient.ConnectAsync(options).Wait();

            // subscribe on the topics
            var topicFilters = new[] {
                new TopicFilter("devices/device1/messages/devicebound/#", MqttQualityOfServiceLevel.AtLeastOnce),
                new TopicFilter("$iothub/twin/PATCH/properties/desired/#", MqttQualityOfServiceLevel.AtLeastOnce),
                new TopicFilter("$iothub/methods/POST/#", MqttQualityOfServiceLevel.AtLeastOnce)
            };
            mqttClient.SubscribeAsync(topicFilters).Wait();


            // publish message 
            var topic = $"devices/device1/messages/events/$.ct=application%2Fjson&$.ce=utf-8";
            var payload = Encoding.ASCII.GetBytes("Hello IoT Hub");
            var message = new MqttApplicationMessage(topic, payload, MqttQualityOfServiceLevel.AtLeastOnce, false);
            mqttClient.PublishAsync(message);

            Console.Read();
        }       
    }
}

and the following screen snippet shows an example of the output for updating a desired twin property color and receiving a C2D message:

enter image description here

Upvotes: 1

Related Questions