Trigger a direct method in Azure IoT Hub by a Azure HTTP Fuc

Reza Naeemabadi 1 Reputation point
2021-01-27T09:57:03.51+00:00

I want to trigger a direct method in Azure IoT Hub (IoT devices) via a webhook using Azure HTTP Functions.
So, I created the following function to trigger the direct method, but it fails to connect to the service.

public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {

            var command = new Microsoft.Azure.Devices.CloudToDeviceMethod("Method Name") { ResponseTimeout = TimeSpan.FromSeconds(30) };

            DateTimeOffset time = DateTimeOffset.Now;
            string payload = JsonConvert.SerializeObject(time);
            command.SetPayloadJson(payload);

            string connectionString = "?????";
            ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(connectionString, TransportType.Amqp);
            //await serviceClient.OpenAsync();
            CloudToDeviceMethodResult result = await serviceClient.InvokeDeviceMethodAsync("IoTDeviceName",command);

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }

Can you give me some hint to figure out how should it work?

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,301 questions
Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,126 questions
Azure IoT SDK
Azure IoT SDK
An Azure software development kit that facilitates building applications that connect to Azure IoT services.
208 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Sander van de Velde 28,796 Reputation points MVP
    2021-01-27T22:33:46.707+00:00

    Hello @MRezaNaeemabadi-5529,

    without the exception you get, it's a bit hard to figure out what is happening.

    The code you added to the HttpTrigger function seems quite ok. Here are some points of attention.

    First, the name of the direct method is case-sensitive.

    Next, Did you reference the Nuget package Microsoft.Azure.Devices so the code knows what a Service Client is?

    You can try to add it in the portal (like this) but I recommend creating a function property in Visual Studio or VS Code.

    This way it far easier to add a package, to debug, etc.

    Finally, Check the response of the direct method like:

       var response = await _serviceClient.InvokeDeviceMethodAsync(deviceId, moduleId, requestMethod);  
         
       directMethodResponse.ResponseStatus = response.Status;  
         
       if (directMethodResponse.ResponseStatus == 200)  
       {  
           var jsonResponse = response.GetPayloadAsJson();  
         
           if (!string.IsNullOrEmpty(jsonResponse))  
           {  
               directMethodResponse.DeserializePayload(jsonResponse);  
         
               return directMethodResponse;  
           }  
       }  
    
    0 comments No comments