we only have these two methods available for azure IoThub in c#.
Device device = await registryManager.GetDeviceAsync("deviceId");
and
device = await registryManager.GetDevicesAsync("max count");
but how to get all available device count or active device count and also a messages count using c#?
As of my knowledge,
There is no direct method to actually get the total number of devices
. Alternatively what you could do is to create a List and whenever you add Devices using AddDeviceAsync
you should push the object to the list.
Same with Total number of messages, you should create your own way to keep the value updated.
The following code should help.
static async Task startClient(string IoTHub, string IoTDevicePrefix, int deviceNumber, string commonKey, int maxMessages, int messageDelaySeconds)
{
allClientStarted++;
runningDevices++;
string connectionString = "HostName=" + IoTHub + ";DeviceId=" + IoTDevicePrefix + deviceNumber + ";SharedAccessKey=" + commonKey;
DeviceClient device = DeviceClient.CreateFromConnectionString(connectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);
await device.OpenAsync();
Random rnd = new Random();
int mycounter = 1;
Console.WriteLine("Device " + IoTDevicePrefix + deviceNumber + " started");
while (mycounter <= maxMessages)
{
Thread.Sleep((messageDelaySeconds * 1000) + rnd.Next(1, 100));
string message = "{ \'loadTest\':\'True\', 'sequenceNumber': " + mycounter + ", \'SubmitTime\': \'" + DateTime.UtcNow + "\', \'randomValue\':" + rnd.Next(1, 4096 * 4096) + " }";
Microsoft.Azure.Devices.Client.Message IoTMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(message));
await device.SendEventAsync(IoTMessage);
totalMessageSent++;
mycounter++;
}
await device.CloseAsync();
Console.WriteLine("Device " + IoTDevicePrefix + deviceNumber + " ended");
runningDevices--;
}
static void createDevices(int number)
{
for (int i = 1; i <= number; i++)
{
var registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
Device mydevice = new Device(IoTDevicePrefix + i.ToString());
mydevice.Authentication = new AuthenticationMechanism();
mydevice.Authentication.SymmetricKey.PrimaryKey = commonKey;
mydevice.Authentication.SymmetricKey.SecondaryKey = commonKey;
try
{
registryManager.AddDeviceAsync(mydevice).Wait();
Console.WriteLine("Adding device: " + IoTDevicePrefix + i.ToString());
}
catch (Exception er)
{
Console.WriteLine(" Error adding device: " + IoTDevicePrefix + i.ToString() + " error: " + er.InnerException.Message);
}
}
}
The values what you are interested are part of the Azure IoT Hub metrics . Basically you can obtained their:
The number of devices can be retrieved by using a device query , eg:
SELECT COUNT() AS numberOfDevices FROM c
which returns something like this:
[ { "numberOfDevices": 123 } ]
To retrieve the number of messages you need to connect to the Event Hub-compatible endpoint, connecting to each underlying partition and looking at each Partition Info ( Last Sequence Number and Sequence Number ). There is some data retention involved though, so unless you add more logic to this, you will get a number representing the count of messages currently present in the hub, not the total since the creation, not the total left to process.
Update: here's the code showing a couple of methods to get the number of devices:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Devices;
using Newtonsoft.Json;
namespace Test
{
class Program
{
static async Task Main()
{
string connString = "HostName=_______.azure-devices.net;SharedAccessKeyName=_______;SharedAccessKey=_______";
RegistryManager registry = RegistryManager.CreateFromConnectionString(connString);
// Method 1: using Device Twin
string queryString = "SELECT COUNT() AS numberOfDevices FROM devices";
IQuery query = registry.CreateQuery(queryString, 1);
string json = (await query.GetNextAsJsonAsync()).FirstOrDefault();
Dictionary<string, long> data = JsonConvert.DeserializeObject<Dictionary<string, long>>(json);
long count1 = data["numberOfDevices"];
// Method 2: using Device Registry
RegistryStatistics stats = await registry.GetRegistryStatisticsAsync();
long count2 = stats.TotalDeviceCount;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.