C2D message for MQTT device to subscribe to.

Haris Papageorge 246 Reputation points
2021-11-22T09:31:30.567+00:00

Hello,

I have successfully connected two actual devices to Azure IoTHub (in the same Iot Hub) and would like the second device to receive the message that the first device sends.
So, in a normal MQTT broker the second device just subscribes to that topic but Azure does not have a normal MQTT broker.

What I am now trying to do is write an Azure function that triggers every time a message from the first device is received in IoTHub through the Event Hub Trigger; and sends a C2D message with the received message (string) to the second device. To achieve that the second device subscribes to this topic: devices/secondDevice/messages/devicebound

Here is my function

#r "Microsoft.Azure.EventHubs"  
  
  
using System;  
using System.Text;  
  
using Microsoft.Azure.EventHubs;  
using Microsoft.Azure.Devices;  
  
static ServiceClient serviceClient;  
static string connectionString = ".........pXH9WI.....";    
static string targetDevice = "secondDevice";  
  
public static async Task Run(EventData[] events, ILogger log)  
{  
    var exceptions = new List<Exception>();  
    serviceClient = ServiceClient.CreateFromConnectionString(connectionString);  
    foreach (EventData eventData in events)  
    {  
        try  
        {  
            string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);  
  
            // Replace these two lines with your processing logic.  
            log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");  
            await Task.Yield();  
            var commandMessage = new Message(Encoding.ASCII.GetBytes(messageBody));  
            await serviceClient.SendAsync(targetDevice, commandMessage);  //  send the message to the second device that the first device sent to IoTHub  
        }  
        catch (Exception e)  
        {  
            // We need to keep processing the rest of the batch - capture this exception and continue.  
            // Also, consider capturing details of the message that failed processing so it can be processed again later.  
            exceptions.Add(e);  
        }  
    }  
  
    // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.  
    if (exceptions.Count > 1)  
        throw new AggregateException(exceptions);  
  
    if (exceptions.Count == 1)  
        throw exceptions.Single();  
}  

Here's the .json code:

{  
  "bindings": [  
    {  
      "type": "eventHubTrigger",  
      "name": "events",  
      "direction": "inout",  
      "eventHubName": "samples-workitems",  
      "cardinality": "many",  
      "connection": "myIoTHub_events_IOTHUB",  
      "consumerGroup": "$Default"  
    }  
  ]  
}  

I am receiving the first device's message but I am not seeing the message in the topic that the second device subscribes to.
151424-image.png
Any ideas? I am doing all this through the portal because I am having a lot of issues with VSCode at the moment and would like to solve this C2D thing quickly.

thanks

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,127 questions
Azure Event Hubs
Azure Event Hubs
An Azure real-time data ingestion service.
560 questions
0 comments No comments
{count} votes

Accepted answer
  1. Haris Papageorge 246 Reputation points
    2021-11-22T11:05:46.863+00:00

    The topic that the second device needs to subscribe to is this: devices/secondDevice/messages/devicebound/#

    ....
    However I feel like this question can help many others to make this simple application work quickly.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Sander van de Velde 28,956 Reputation points MVP
    2021-11-22T09:57:14.74+00:00

    Hello @Haris Papageorge ,

    The following samples are valid using the Azure IoT SDKs.

    Take a look at the documentation where the device twin update of a single device is sent.

    To make a C2D Direct Method call, check out this example.

    Here is an example of a device receiving a direct method.

    If you want to make use of the MQTT C2D communication, this documentation should be able to help you.

    1 person found this answer helpful.
    0 comments No comments