Search code examples
azureazure-iot-hub

How to send an explicit response with payload for a C2D (Cloud to Device) Azure IoT Hub message back to the initiator?


I am currently trying to implement some processing of C2D messages. So far sending a C2D message from an IoT Hub Function works like a charm and I'm receiving and processing the payload without any problems.

My problem however is, that on the initiating side I always get a positive ACK, even if I kill the IoT device while processing the command. It seems all documentation starts becoming a little vague as soon as it comes to responses to C2D messages. And I did read the related documents of the IoT Hub functionality multiple times ... Hope I didn't miss an essential part, but I doubt it.

So how can I explicitly send a response back to the initiator which also contains a payload?

I'm currently on the free demo-subscription as I'm doing my first steps with IoT Hub.

Help greatly appreciated.


Solution

  • A good place to start for any communication from cloud to the device is this page. From what I can tell, in your situation, you might want to use a Direct Method rather than a C2D message. A C2D message is great for notifying the device, but as you experienced, there are no built-in features for responding to the message.

    A direct method allows to send a request to a device, and for that device to respond to it. Both the request and response are allowed a 128 KB JSON payload, so you can use that on the device-side to send something back.

    Update: Like mentioned in the comments, you don't have a lot of influence on how to handle C2D messages from the device, other than accepting/rejecting it. Here's how you would reject a message using the C# Device SDK.

    private async Task RejectSample()
    {
        var deviceClient = DeviceClient.CreateFromConnectionString("muchconnectionstring");
        var message = await deviceClient.ReceiveAsync();
        // await deviceClient.CompleteAsync(message);
        await deviceClient.RejectAsync(message);
    }