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.

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.