How to route Azure IOT hub messages to Event Grid MQTT broker

Dylan Yeo 30 Reputation points
2023-07-10T16:29:03.85+00:00

Good day all,

I have came to understand that Azure IOT Hub is unlike a traditional MQTT broker with device-to-device messaging, rather it supports device-to-cloud messaging.

However, may I ask if there is a way to route the IOT hub devices data to a generic MQTT outside of Microsoft Azure or to utilise Azure's Event Grid MQTT broker and afterwards subscribe to that particular MQTT broker to view its messages?

If so, may I receive some guidance and steps on how to achieve whats mentioned above?

Thank you.

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,272 questions
Azure Event Grid
Azure Event Grid
An Azure event routing service designed for high availability, consistent performance, and dynamic scale.
456 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Sander van de Velde | MVP 36,766 Reputation points MVP Volunteer Moderator
    2023-07-10T20:18:38.08+00:00

    Hello @Dylan Yeo ,

    in all scenarios, you need to put custom logic (like an Azure function) behind the IoT Hub to route messages between services.

    You need to route IoT Hub device messages to the other service first. You also need to listen for messages coming from that other service and send them to the device(s) of your choice.

    The Azure IoT Hub has a route towards EventGrid but this supports the classic one-way EventGrid publisher/subscriber pattern only.

    This does not connect to the new MQTT Broker feature of EventGrid.

    So you must add extra d2c and c2d communication logic for this solution too.


    If the response helped, do "Accept Answer". If it doesn't work, please let us know the progress. All community members with similar issues will benefit by doing so. Your contribution is highly appreciated.

    1 person found this answer helpful.

  2. Sedat SALMAN 14,180 Reputation points MVP
    2023-07-10T17:55:08.0833333+00:00

    https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-messages-d2c

    Azure doesn't have built-in support for routing IoT Hub messages directly to an external MQTT broker. You would need to create an intermediary service (like an Azure Function or Logic App) to act as a bridge.

    But

    Azure IoT Hub can be integrated with Event Grid to enable powerful and complex routing rules.

    https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-event-grid

    0 comments No comments

  3. LeelaRajeshSayana-MSFT 17,766 Reputation points Moderator
    2023-07-11T23:32:04.8666667+00:00

    Hi @Dylan Yeo You can route the events from Azure IoT Hub to an Event Hub. You can then create an Azure function that triggers based on the Event hub data and send the data to Mosquitto MQTT end point through the function. Here is a sample function for your reference.

    using Microsoft.Azure.WebJobs;
    using Microsoft.Extensions.Logging;
    using MQTTnet;
    using MQTTnet.Client;
    using System;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace MosquittoPublisher
    {
        public static class MosquittoPublisherFunction
        {
            private static readonly Lazy<IMqttClient> lazyMqttClient = new Lazy<IMqttClient>(() =>
            {
                var factory = new MqttFactory();
                var client = factory.CreateMqttClient();
    
                var options = new MqttClientOptionsBuilder()
                    .WithTcpServer("localhost", 1883)
                    .Build();
    
                client.ConnectAsync(options, CancellationToken.None).Wait();
    
                return client;
            });
    
            private static IMqttClient MqttClientInstance => lazyMqttClient.Value;
    
            [FunctionName("MosquittoPublisherFunction")]
            public static async Task Run(
                [EventHubTrigger("myeventhub", Connection = "EventHubConnection")] EventData[] eventHubMessages,
                ILogger log)
            {
                foreach (var message in eventHubMessages)
                {
                    var mqttMessage = new MqttApplicationMessageBuilder()
                        .WithTopic("test/topic")
                        .WithPayload(message)
                        .WithRetainFlag()
                        .Build();
    
                    await MqttClientInstance.PublishAsync(mqttMessage, CancellationToken.None);
                }
            }
        }
    }
    
    
    

    Please make sure to provide the correct hostname and the port in the options variable to point to your Mosquitto MQTT broker.

    Here is a code sample in Python.

    import logging
    import azure.functions as func
    import paho.mqtt.client as mqtt
    
    # Define the MQTT broker address and port
    broker_address = "localhost"
    broker_port = 1883
    
    # Create an MQTT client and connect to the broker
    client = mqtt.Client()
    client.connect(broker_address, broker_port)
    
    app = func.FunctionApp()
    
    @app.function_name(name="EventHubTrigger1")
    @app.event_hub_message_trigger(arg_name="myhub", 
                                   event_hub_name="<EVENT_HUB_NAME>",
                                   connection="<CONNECTION_SETTING>") 
    def test_function(myhub: func.EventHubEvent):
        # Get the body of the Event Hub event
        event_body = myhub.get_body().decode('utf-8')
    
        # Define the topic and message to send
        topic = "test/topic"
        message = event_body
    
        # Publish the message to the broker
        client.publish(topic, message)
    
        # Log a message to the Azure Function log
        logging.info('Python EventHub trigger processed an event: %s', event_body)
    
        # Disconnect from the broker
        client.disconnect()
    

    Here is a sample response I have received when I subscribed to my local MQTT topic on my local machine.

    User's image

    Please find the following resources that will help you with the routing and creation of Azure function.

    Hope this helps. Please let us know if you have any additional questions.


    If the response helped, please do click Accept Answer and Yes for the answer provided. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.