Naar de inhoud springen

Sander van de Velde

Microsoft MVP Azure | IoT Platform Architect | Speaker about IoT | Let me add some value

  • Home
  • Public speaking
  • About Sander van de Velde

Counting the current number of IoT Hub messages and devices

Sander van de Velde IoTHub, REST 5 december 20206 december 2020 3 Minutes

Microsoft provides SDKs for both building IoT devices and accessing the IoT Hub (based on several programming languages).

Regarding the IoT Hub, with the SDK you are able to eg. register and control devices.

Still, some actions are possible with the IoT Hub which is not supported by the SDK.

For those actions, Microsoft supports an IoTHub Rest API which extends the capabilities of the SDK.

In the past, I demonstrated how to work with C2D messages using the REST API.

A few days back, I came along with this MS Learn question about IoT Hub message counts. This also has to be tackled by the REST API.

Let’s see how.

Access to an Azure IoT Hub is secured by credentials, just like any other Azure resource.

To make use of the Rest API, we need to provide some credentials in the form of a bearer token.

In the previous IoT Hub Rest API blog, I got a token from some Microsoft app. This time, we will generate one on the fly!

First, create an identity in Azure using these PowerShell commands (see here for more details):

az login 
az ad sp create-for-rbac -n "testaccount"

This creates an ‘testaccount’ with its credentials and secrets.

Note: This is a one-time action. You can revoke the user at any time you want. This will stop all code using the credential secrets.

Fill these credential secrets in, in the code below:

internal class Program
{
    private static void Main(string[] args)
    {
        // Take these values from the login credentials of our new user
        var appId = "[testaccount user Appid]";
        var password = "[testaccount user password]";
        var tennant = "[testaccount user tennant]";

        var bearer = GetBearer(tennant, appId, password);

        Console.WriteLine($"bearer {bearer}");

        // Take the following values from the IoT Hub overview page
        GetQuota(bearer, "[subscriptionId]", "[resourceGroup]", "[iotHub]");

        Console.WriteLine("Press a key to exit");

        Console.ReadKey();
    }

    private static void GetQuota(string bearer, string subscriptionId, string resourceGroup, string iotHub)
    {
        var url = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Devices/IotHubs/{iotHub}/quotaMetrics?api-version=2018-04-01";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
        var req = new HttpRequestMessage(HttpMethod.Get, url);

        using var res = client.SendAsync(req).Result;
        var jsonString = res.Content.ReadAsStringAsync().Result;

        Console.WriteLine(jsonString);
    }

    private static string GetBearer(string tennant, string appId, string password)
    {
        var nvc = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("grant_type", "client_credentials"),
            new KeyValuePair<string, string>("client_id", appId),
            new KeyValuePair<string, string>("client_secret", password),
            new KeyValuePair<string, string>("resource", "https://management.azure.com/")
        };

        var url = $"https://login.microsoftonline.com/{tennant}/oauth2/token";

        using var client = new HttpClient();
        var req = new HttpRequestMessage(HttpMethod.Post, url)
        {
            Content = new FormUrlEncodedContent(nvc)
        };

        using var res = client.SendAsync(req).Result;
        var jsonString = res.Content.ReadAsStringAsync().Result;
        var json = JsonConvert.DeserializeObject<dynamic>(jsonString);
        return json.access_token;
    }
}

The IoT Hub related values can be taken from the overview blade of the targetted IoT Hub.

Note: due to the secrets being use, it’s advised to run the logic only in the cloud, not on a local device.

This code first creates the bearer token and uses that bearer token to make the actual call.

Note: The bearer token comes with an expiration DateTime (actually a Unix timestamp) which translates into a one hour expiration time. On multiple API calls, you can buy yourself some time by reusing the token within that one hour.

The result is seen here:

This result shows four Quota values:

  1. The current total messages for today
  2. The max number of messages allowed per day for this IoT Hub (based on the tier and number of units)
  3. The number of registered devices
  4. The maximum allowed devices for this IoT Hub

Do not expect an actual real-time representation of the number of messages received. There can be experienced a delay.

Conclusion

Using the Rest API of the IoT Hub, you can access many more IoT Hub features compared with the SDK.

So please give it a try.

Share this:

  • Twitter
  • Facebook

Vind ik leuk:

Like Laden...

Gerelateerd

  • Getagged
  • az login

Gepubliceerd door Sander van de Velde

I started as an IT consultant in 1993. I like to get my hands dirty with software innovations and I try to implement these in my daily work. Currently, I am involved in the IoT Platform part of Azure (eg. IoT Hubs, IoT Edge, StreamAnalytics, Azure Functions, etc.) and Azure in general. I've been presented with the 2017, 2018, 2019, 2020 Microsoft Most Valuable Professional (MVP) Award and I'm a member of the Microsoft Azure Advisory Board. For me, it is important to share knowledge. And I am committed to doing so by writing blogs, articles for magazines and giving lots of presentations. When offline, I like cutting down trees using Gränsfors Bruks axes, sailing, motorcycling or geocaching with my wife and my sons. Alle berichten van Sander van de Velde weergeven

Gepubliceerd 5 december 20206 december 2020

Berichtnavigatie

Previous Post Using a Weidmueller UC 20 Controller as Azure IoT Edge child device
Next Post Getting started with the Azure IoT Central Rest API

Recent

  • All Around Azure IoT. Join this free conference at January 19, 2021
  • Add local storage to Azure IoT Edge modules using Docker Bind
  • Handling Advantech Wise 710 OPC-UA telemetry using OPCPublisher
  • Azure IoT Edge module metrics in action
  • Getting started with the Azure IoT Central Rest API

Tags

Accelerator Agile Agile Scrum Ajax AMS ASP.NET MVC Azure Azure Functions Azure Gateway SDK Azure Portal C# CamSpace Client Side Validations commands Core DATAJS DDWA Debugging Deployment deployment manifest Devices Device Twin DirectMethods Direct Methods dps edgeAgent edgeHub etag Firmata Functions GABC gpio GPS I2C Ignite IoT IoT Edge IoT Hub IoTHub Javascript Json keynote KnockoutJS Linux Ubuntu Logging metrics Moby module twin MVC MVVM NRF24L01+ ODATA opcpublisher PowerBi RDP Routing Scrum Service tags Shell SignalR Spec# SSH Standupmeeting Tags Techdays TechEd Teched 2010 TFS The Things Network TPM Unittest VSCODE Watchdog Webcam WPF

Category

Twitter

  • RT @AzureCoach: Very happy to announce that Sander van de Velde @svelde joins the Your Azure Coach team! Sander is an Azure MVP and has an…- 9 hours ago
  • RT @vyalla: Want to have your cake and eat it too? Checkout IoT EFLOW - combine your battle-tested IT/OT Windows investments with modern L…- 4 days ago
  • Next Saturday, I will present at the Azure Nigeria User Group talking about @Azure #IoT. Register at… twitter.com/i/web/status/1…- 4 days ago
  • RT @nottsiot: Don't forget, you can catch up with tonight's #NottsIoT talks from @svelde and @david_whitney on @YouTube right here... https…- 6 days ago
  • RT @nottsiot: Join us tonight from 18:30GMT for two ace talks! We'll have @svelde talking about his @MicrosoftIoT Edge powered Beer Lift, a…- 6 days ago
Follow @svelde

Archief

  • januari 2021 (4)
  • december 2020 (2)
  • november 2020 (3)
  • oktober 2020 (2)
  • september 2020 (1)
  • augustus 2020 (3)
  • juli 2020 (2)
  • juni 2020 (3)
  • mei 2020 (5)
  • april 2020 (4)
  • maart 2020 (6)
  • februari 2020 (3)
  • januari 2020 (1)
  • december 2019 (4)
  • oktober 2019 (7)
  • september 2019 (1)
  • augustus 2019 (6)
  • juli 2019 (4)
  • juni 2019 (2)
  • mei 2019 (2)
  • april 2019 (2)
  • maart 2019 (1)
  • februari 2019 (3)
  • januari 2019 (4)
  • december 2018 (3)
  • november 2018 (3)
  • oktober 2018 (2)
  • september 2018 (3)
  • augustus 2018 (3)
  • juni 2018 (4)
  • mei 2018 (1)
  • april 2018 (3)
  • maart 2018 (2)
  • februari 2018 (1)
  • januari 2018 (5)
  • december 2017 (8)
  • november 2017 (3)
  • oktober 2017 (2)
  • september 2017 (4)
  • juli 2017 (5)
  • juni 2017 (5)
  • mei 2017 (2)
  • april 2017 (2)
  • maart 2017 (3)
  • februari 2017 (4)
  • januari 2017 (2)
  • december 2016 (3)
  • november 2016 (3)
  • oktober 2016 (5)
  • september 2016 (2)
  • juli 2016 (5)
  • juni 2016 (4)
  • mei 2016 (1)
  • april 2016 (2)
  • maart 2016 (4)
  • februari 2016 (5)
  • januari 2016 (6)
  • december 2015 (2)
  • november 2015 (1)
  • oktober 2015 (2)
  • september 2015 (3)
  • augustus 2015 (2)
  • juli 2015 (1)
  • juni 2015 (4)
  • mei 2015 (4)
  • april 2015 (1)
  • maart 2015 (6)
  • februari 2015 (1)
  • november 2014 (2)
  • oktober 2014 (6)
  • juli 2014 (1)
  • april 2014 (2)
  • oktober 2013 (1)
  • april 2013 (2)
  • maart 2013 (2)
  • februari 2013 (2)
  • januari 2013 (1)
  • december 2012 (2)
  • november 2012 (2)
  • augustus 2012 (1)
  • juni 2012 (6)
  • mei 2012 (3)
  • april 2012 (1)
  • oktober 2011 (1)
  • september 2011 (3)
  • augustus 2011 (1)
  • juni 2011 (2)
  • mei 2011 (2)
  • april 2011 (2)
  • maart 2011 (2)
  • januari 2011 (2)
  • december 2010 (2)
  • november 2010 (4)
  • mei 2010 (1)
  • april 2010 (3)
  • maart 2010 (1)
  • februari 2010 (2)
  • januari 2010 (1)
  • december 2009 (2)
  • november 2009 (2)
  • oktober 2009 (2)
  • juli 2009 (2)
  • maart 2009 (1)
  • februari 2009 (2)
  • januari 2009 (1)
  • december 2008 (1)
  • november 2008 (2)
  • oktober 2008 (2)
  • september 2008 (1)
  • augustus 2008 (2)
  • juli 2008 (2)

RSS

  • RSS - Berichten
  • RSS - Reacties
Maak een gratis website of blog op WordPress.com.
Annuleren
Privacy en cookies: Deze site maakt gebruik van cookies. Door verder te gaan op deze website, ga je akkoord met het gebruik hiervan.
Voor meer informatie, onder andere over cookiebeheer, bekijk je: Cookiebeleid
%d bloggers liken dit: