3
votes

I want to read the "Microsoft.Devices.DeviceConnected" events (https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-event-grid#event-types) from Azure IoT Hub. The only examples I found deals with Azure Event Grid but I'd rather like to use the IoT Hub's internal endpoint (Event Hub). Is this even possible? When I subscribe to the internal Event Hub using the EventProcessorHost interface all I get are D2C user telemetry messages.

3
You can't, unless you somehow send a custom made event your self from the device.Peter Bons

3 Answers

1
votes

Like @PeterBons said, this feature is not supported by Azure IoT Hub, however can be done outside of the Azure IoT Hub using an Azure Function. The following screen snippet shows this integration where the EventGrid events are pushed to the IoT Hub Stream:

enter image description here

As you can see, the above EventGridTrigger function is an integrator between the Azure Event Grid and Azure IoT Hub. This integrator has a responsibility to consume an event grid events, mapping to the D2C Message and send it to the Azure IoT Hub as a virtual IoT device (backend device) with a Https protocol.

Update:

The following code snippet is an example of the Azure Function - Integrator to the Azure IoT Hub:

#r "Microsoft.Azure.EventGrid"
#r "Newtonsoft.Json"

using System.Configuration;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Web;
using System.Net.Http;
using System.Text;
using System.Globalization;
using Newtonsoft.Json;
using Microsoft.Azure.EventGrid.Models;


// reusable client proxy
static HttpClientHelper iothub = new HttpClientHelper(Environment.GetEnvironmentVariable("AzureIoTHubShariedAccessPolicy"));

public static async Task Run(EventGridEvent eventGridEvent, ILogger log)
{
    log.LogInformation(eventGridEvent.Data.ToString());

    // my virtual backend iot device
    string deviceId = "Device13";
    var content = new StringContent(JsonConvert.SerializeObject(eventGridEvent), Encoding.UTF8, "application/json");

    await iothub.Client.PostAsync($"/devices/{deviceId}/messages/events?api-version=2018-06-30", content);
}




// helpers
class HttpClientHelper
{
    HttpClient client;
    DateTime expiringSaS;
    (string hostname, string keyname, string key) config;

    public HttpClientHelper(string connectionString)
    {
        config = GetPartsFromConnectionString(connectionString);
        client = new HttpClient() { BaseAddress = new Uri($"https://{config.hostname}")};
        SetAuthorizationHeader();         
    }

    public HttpClient Client
    {
        get
        {          
            if (expiringSaS < DateTime.UtcNow.AddMinutes(-1))
            {
               SetAuthorizationHeader();  
            }         
            return client;
        }
    }

    internal void SetAuthorizationHeader()
    {
        lock (client)
        {
            if (expiringSaS < DateTime.UtcNow.AddMinutes(-1)) 
            {
                string sasToken = GetSASToken(config.hostname, config.key, config.keyname, 1);
                if (client.DefaultRequestHeaders.Contains("Authorization"))
                    client.DefaultRequestHeaders.Remove("Authorization");
                client.DefaultRequestHeaders.Add("Authorization", sasToken);
                expiringSaS = DateTime.UtcNow.AddHours(1);
            }
        }
    }

    internal (string hostname, string keyname, string key) GetPartsFromConnectionString(string connectionString)
    {
        var parts = connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Split(new[] { '=' }, 2)).ToDictionary(x => x[0].Trim(), x => x[1].Trim());
        return (parts["HostName"] ?? "", parts["SharedAccessKeyName"] ?? "", parts["SharedAccessKey"] ?? "");
    }

    internal string GetSASToken(string resourceUri, string key, string keyName = null, uint hours = 24)
    {
        var expiry = GetExpiry(hours);
        string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
        HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key));

        var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
        var sasToken = String.Format(CultureInfo.InvariantCulture, $"SharedAccessSignature sr={HttpUtility.UrlEncode(resourceUri)}&sig={HttpUtility.UrlEncode(signature)}&se={expiry}");
        if (!string.IsNullOrEmpty(keyName))
            sasToken += $"&skn={keyName}";
        return sasToken;
    }

    internal string GetExpiry(uint hours = 24)
    {
        TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
        return Convert.ToString((int)sinceEpoch.TotalSeconds + 3600 * hours);
    }
}

and function.json:

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    }
  ],
  "disabled": false
}
0
votes

I just wanted to add that you quite easily can create an event subscription (using Event Grid) under Events in the IoT Hub and push Connection events (e.g. Device Connected or Device Disconnected) to an Azure Function, Event Hub or Service Bus etc.

0
votes

An IoT hub has a default built-in-endpoint (messages/events) that is compatible with Event Hubs. You can create custom endpoints to route messages to by linking other services in your subscription to the IoT Hub.

enter image description here

Here is link to the relevant Azure documentation