Reading D2C message from specific device RRS feed

  • Question

  • Hi,

    strangely, everything is working fine in my code, I am sending commands from my BE to device and receiving response which is fine, now suppose I want to receive information back from the device (not confirmation).

    so I am dispatching a command that runs code at the device and the device sends the results in a message, I have MMC console that receives the messages but I want to read the message sent by specific device (the device that the operator issues a command to in MMC), how can I do that ?!

    I am reading everything from 

    iotHubD2cEndpoint = "messages/events";

    but this will return everything, I want to read the message that was sent by specific device, hope my question is clear.

    Mahmoud Magdy - Exchange Server MVP

    Sunday, July 23, 2017 11:24 AM

All replies

  • Hi,

    Based on the MSDN Docs Send device-to-cloud messages to IoT Hub and Event Hub features overview you have to filter a stream of messages for your specific device.

    The service-facing messages/events endpoint is the Event Hubs compatible endpoint, so first of all you must resolve a partition of the consumer groups where your device ingested all events:

    string selectedPartition = Microsoft.Azure.Devices.Common.EventHubPartitionKeyResolver.ResolveToPartition(device.Id, eventHubClient.GetRuntimeInformation().PartitionCount);

    once you have this partition, you can create a receiver:

    private static async Task ReceiveMessagesFromDeviceAsync(string partition, string selectedDeviceId, CancellationToken ct)
       var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);
       while (true)
          if (ct.IsCancellationRequested) break;
          EventData eventData = await eventHubReceiver.ReceiveAsync();
          if (eventData == null) continue;
          var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();
          if (string.CompareOrdinal(selectedDeviceId.ToUpper(), connectionDeviceId.ToUpper()) == 0)
             string data = Encoding.UTF8.GetString(eventData.GetBytes());
             Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);



    • Edited by Roman Kiss Tuesday, July 25, 2017 7:36 AM
    Tuesday, July 25, 2017 7:33 AM