The REST API of the IoT Hub gives exactly what you need.
This goes in two steps:
- You need some credentials for your subscription so you can construct a bearer token
Run these two powershell commands
az login
az ad sp create-for-rbac -n "testaccount"
This gives you credentials for a non-human account...
(perhaps you need to install the powershell az module first)
- Execute this code after you filled in the variables:
Run this application with two Rest calls:
internal class Program
{
private static void Main(string[] args)
{
var appId = "";
var password = "";
var tennant = "";
var bearer = GetBearer(tennant, appId, password);
GetQuota(bearer, "[your subscriptionId]", "[resourceGroup of your IoT Hub]", "[name of your 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/{rg}/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;
}
}
As you can see, you need three other values. You can find them on the overview page of your iothub:
this will result in the right numbers:
Please accept an answer if correct. Original posters help the community find answers faster by identifying the correct answer. Here is how.