How to use IoT Hub SDK from Azure C# function app

Hocker, Cary 20 Reputation points
2023-06-16T18:12:22.28+00:00

I need to wrap Azure IoT Hub SDK calls in a C# function app with HTTP trigger to provide a validation service to confirm successful IoT Device provisioning. Would like to see an example of how to instantiate a ServiceClient type object against my IoT Hub, which can then be used to retrieve device details (to confirm that the specified device exists in the IoT Hub Registry.)

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
{count} votes

Answer accepted by question author
  1. LeelaRajeshSayana-MSFT 17,866 Reputation points Moderator
    2023-06-16T21:10:32.4033333+00:00

    Hi @Hocker, Cary Greetings! Welcome to Microsoft Q&A forum. Thank you for posting this question here.

    Here is an Azure function sample code to achieve what you are looking for

    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    using Microsoft.Azure.Devices;
    
    namespace Raj.ServiceClient
    {
        public static class IoTServiceClient
        {
            private static RegistryManager _registryManager;
    
            [FunctionName("IoTServiceClient")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
            {
                log.LogInformation("C# HTTP trigger function processed a request.");
    
                if (_registryManager == null)
                {
                    // Connection string for the IoT Hub
                    string connectionString = "<IoTHubOwnerConnectionString>";
    
                    // Create a new instance of RegistryManager using the IoT Hub connection string
                    _registryManager = RegistryManager.CreateFromConnectionString(connectionString);
                }
                
                string deviceId = req.Query["deviceId"];
    
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                deviceId = deviceId ?? data?.name;
    
                // Check if the device exists
                Device device = await _registryManager.GetDeviceAsync(deviceId);
                if (device == null)
                {
                    // Device does not exist
                    Console.WriteLine($"Device with ID {deviceId} does not exist.");
                }
                else
                {
                    // Device exists
                    Console.WriteLine($"Device with ID {deviceId} exists.");
                }
    
                string responseMessage = string.IsNullOrEmpty(deviceId)
                    ? $"Hello, {deviceId} does not exists."
                    : $"Hello, {deviceId} exists.";
    
                return new OkObjectResult(responseMessage);
            }
        }
    }
    
    
    

    I have tested this function locally and you can pass the device ID as a query parameter to invoke the HTPP trigger function as follows http://localhost:7071/api/IoTServiceClient?deviceid=TestDevice4. Please find the below snippet from the function execution stack.

    enter image description here Hope this helps. Please let us know if you have any additional questions or need further assistance.


    If the response helped, please do click Accept Answer and Yes. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.