Count provisioned devices by DPS

This post shows a way to find out how many IoT (Edge) devices have been provisioned by a specific enrolment group within the last x minutes.

The solution could be much simpler if I just wanted to know how many devices are registering themselves. In this case the build in metrics are enough to get that information.

IoT Hub Metrics

The use case required a more sophisticated solution that is able to reflect the tenants, identified by tags.

Solution Architecture

Device Provisioning Service

Different Enrolment Groups separate devices in this scenario into Tenants. To be able to identify the customers, an initial tag CustomerId is added to the enrolment group. It is then applied to the devices that are create by DPS in the IoT Hub.

{
  "tags": {
    "CustomerId": "AnotherCustomer"
  },
  "properties": {
    "desired": {}
  }
}

This tag can then be used for e.g. message enrichment. I’ve written previously about using it: /2020/05/13/properties-for-iot-messages-in-azure-stream-analytics/ (opens in a new tab)

The metrics from DPS did not allow me to distinguish the tags/customers. But IoT Hub will make them available and offers events for newly created devices.

IoT Hub

Within IoT Hub I created an event subscription, that passed on all necessary events to an EventHub.

Event Subscription in IoT Hub

The event will include the device twin, which has been prepopulated with the tags specified in the enrolment group.

Device Twin in IoT Hub

As seen in the architecture diagram, Event Grid has been connected to an Event Hub. #plugandplay 😉 It will fire an event with the documented schema: Azure IoT Hub and Event Grid | Microsoft Docs

Event Hub

Why the additional Event Hub? Event Grid cannot be used as input for an Azure Stream Analytics Job and Event Hub is the universal connector in this case.

You can use the smallest tier (which is Basic) as there is not a lot of events flowing through it. The default 2 partitions is also fine.

Stream Analytics Job

I chose Stream Analytics for the further analysis of the events, because it offers an out-of-the box functionality for queries on time windows: Introduction to Azure Stream Analytics windowing functions | Microsoft Docs

As you can see, the query is pretty simple and can be adjusted easily.

Azure Stream Analytics Job Query

The example uses a blob storage as output, but you can choose to write to an Azure Function or whatever you want to do with the know how that one customer has onboarded lots of devices in a short period of time.