IoT Hub telemetry ingestion in Azure Digital Twins.

Matías Liñán García 25 Reputation points
2023-06-21T10:47:27.3666667+00:00

Hi, I am doing the IoT Hub Telemetry Ingest tutorial on Azure Digital Twins, this is linked to another tutorial which is where you create the function and application functions in Azure.

Well when I create the function with the example code, which is as follows:

using System.Collections.Generic;
using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;

namespace FunctionApp10
{
    public static class HttpExample
    {
        [Function("HttpExample")]
        public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
            FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("HttpExample");
            logger.LogInformation("C# HTTP trigger function processed a request.");

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            response.WriteString("Welcome to Azure Functions!");

            return response;
        }
    }
}

The function implements it well in the function application but when I modify the file with the code I need which is as follows:

using System;
using Azure;
using System.Net.Http;
using Azure.Core.Pipeline;
using Azure.DigitalTwins.Core;
using Azure.Identity;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Azure.Messaging.EventGrid;

namespace IotHubtoTwins
{
    public class IoTHubtoTwins
    {
        private static readonly string adtInstanceUrl = Environment.GetEnvironmentVariable("ADT_SERVICE_URL");
        private static readonly HttpClient httpClient = new HttpClient();

        [FunctionName("IoTHubtoTwins")]
        // While async void should generally be used with caution, it's not uncommon for Azure function apps, since the function app isn't awaiting the task.
#pragma warning disable AZF0001 // Suppress async void error
        public async void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
#pragma warning restore AZF0001 // Suppress async void error
        {
            if (adtInstanceUrl == null) log.LogError("Application setting \"ADT_SERVICE_URL\" not set");

            try
            {
                // Authenticate with Digital Twins
                var cred = new DefaultAzureCredential();
                var client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred);
                log.LogInformation($"ADT service client connection created.");
            
                if (eventGridEvent != null && eventGridEvent.Data != null)
                {
                    log.LogInformation(eventGridEvent.Data.ToString());

                    // 

                    log.LogInformation($"Device:{deviceId} Temperature is:{temperature}");

                    // 
                }
            }
            catch (Exception ex)
            {
                log.LogError($"Error in ingest function: {ex.Message}");
            }
        }
    }
}

The function neither executes it nor implements it in the functions application.

Could you tell me how I can solve it?

Azure Digital Twins
Azure Digital Twins
An Azure platform that is used to create digital representations of real-world things, places, business processes, and people.
231 questions
0 comments No comments
{count} votes

Accepted answer
  1. LeelaRajeshSayana-MSFT 16,046 Reputation points
    2023-06-21T19:34:12.8866667+00:00

    Hello @Matías Liñán García Greetings! Welcome to Microsoft Q&A forum. Thank you for posting your question here.

    The first function you have provided in the question works on HttpTrigger. The HTTP trigger lets you invoke a function with an HTTP request. Whereas the second function sample you have provided is configured with EventGridTrigger. This is used to respond to an event sent by an Event Grid source. You must have an event subscription to the source to receive events and the function gets triggered only when an event is received on the Event grid source. Please refer the resource Azure Functions triggers and bindings concepts to get more details on the Trigger options available for Azure function and how they can be used.

    I understand the you are trying to follow the tutorial Ingest IoT Hub telemetry into Azure Digital Twins. Please note that the Azure function defined in this article relies on an Event Grid which is supposed to receive data from Azure IoT Hub. The binding of Azure function with the Event Grid can be made using the step outlined in the section Connect the function to IoT Hub. Here is the CLI command for your reference.

    az eventgrid event-subscription create --name <name-for-hub-event-subscription> --event-delivery-schema eventgridschema --source-resource-id /subscriptions/<your-subscription-ID>/resourceGroups/<your-resource-group>/providers/Microsoft.Devices/IotHubs/<your-IoT-hub> --included-event-types Microsoft.Devices.DeviceTelemetry --endpoint-type azurefunction --endpoint /subscriptions/<your-subscription-ID>/resourceGroups/<your-resource-group>/providers/Microsoft.Web/sites/<your-function-app>/functions/IoTHubtoTwins
    
    
    

    Once you have the Event Grid bound to Azure function and have a client that sends data to Event Grid (IoT Hub device telemetry sample in the given tutorial), you should be able to see the function getting triggered.

    Please ensure that you have done all the configurations mentioned in the article and assigned appropriate permissions to the Azure function app to access Azure Digital Twin instance in order to update the Digital Twin.

    Hope this helps. Please let us know if you have any additional questions or need further assistance. We would be glad to help you.


    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 additional answers

Sort by: Most helpful

Your answer

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