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 | Microsoft MVP | IoT Solution Architect | Speaker | Maker 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.

Advertentie

Share this:

  • Twitter
  • Facebook

Vind ik leuk:

Vind-ik-leuk Laden...

Gerelateerd

  • Getagged
  • az login

Gepubliceerd door Sander van de Velde | Microsoft MVP | IoT Solution Architect | Speaker | Maker

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, 2021, 2022, 2023 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 | Microsoft MVP | IoT Solution Architect | Speaker | Maker 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

  • Using Azure Logic apps as business rules for Azure Digital Twins
  • Another year, another AZ-220 Azure IoT Developer Specialty certification renewal
  • Azure Logic App actions for Azure Data Explorer
  • Does your Azure IoT (Edge Ubuntu) device survive the Baltimore certificate migration?
  • Azure IoT Community, unified edge event with Microsoft Nederland

Tags

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

Category

Twitter

  • You can now offer rule-based decision-making using @Azure #DigitalTwins together with #Logicapps using the new ADT… twitter.com/i/web/status/1…- 1 week ago
  • RT @adamj89: Yesterday I had the sad news that my role leading Developer Communities at Microsoft UK is at risk of redundancy. I’ve been wi…- 1 week ago
  • @obloch This very unfortunate news. You practically built the Azure IoT family. Next beer is on me!- 1 week ago
  • RT @obloch: The Digital Twins Definition Language (DTDL) has some (major) updates for you. Check out @ridomin's post on https://t.co/97iNAi…- 2 weeks ago
  • RT @obloch: Digital Twins are about modelling complete environments to monitor, simulate, interact with physical spaces, objects and people…- 2 weeks ago
Follow @svelde

Archief

  • maart 2023 (1)
  • februari 2023 (2)
  • januari 2023 (4)
  • december 2022 (4)
  • oktober 2022 (2)
  • september 2022 (2)
  • augustus 2022 (4)
  • juli 2022 (2)
  • mei 2022 (4)
  • april 2022 (4)
  • maart 2022 (1)
  • februari 2022 (1)
  • januari 2022 (2)
  • december 2021 (2)
  • november 2021 (4)
  • oktober 2021 (4)
  • september 2021 (4)
  • juli 2021 (6)
  • juni 2021 (4)
  • mei 2021 (5)
  • maart 2021 (2)
  • februari 2021 (2)
  • 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
Blog op WordPress.com.
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
  • Volg Volgend
    • Sander van de Velde
    • Doe mee met 47 andere volgers
    • Heb je al een WordPress.com-account? Nu inloggen.
    • Sander van de Velde
    • Aanpassen
    • Volg Volgend
    • Aanmelden
    • Inloggen
    • Korte link kopiëren
    • Deze inhoud rapporteren
    • View post in Reader
    • Beheer abonnementen
    • Deze balk inklappen
 

Reacties laden....
 

    %d bloggers liken dit: