如何获取发送到 azure IoT hub c# 的设备总数和消息总数
How can I get total number of devices and total number of messages send to azure IoT hub c#
对于 c# 中的 Azure IoThub,我们只有这两种方法可用。
Device device = await registryManager.GetDeviceAsync("deviceId");
和
device = await registryManager.GetDevicesAsync("max count");
但是如何使用 c# 获取所有可用设备数或活动设备数以及消息数?
据我所知,
没有直接的方法来实际获取 total number of devices
。或者你可以做的是创建一个列表,每当你使用 AddDeviceAsync
添加设备时,你应该将对象推送到列表中。
与消息总数相同,您应该创建自己的方式来保持值更新。
以下代码应该有所帮助。
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);
}
}
}
您感兴趣的值是 Azure IoT Hub metrics 的一部分。基本上你可以获得他们的:
可以使用 device query 检索 设备数量 ,例如:
SELECT COUNT() AS numberOfDevices FROM c
其中 returns 是这样的:
[
{
"numberOfDevices": 123
}
]
要检索条消息,您需要连接到与事件中心兼容的端点,连接到每个基础分区并查看每个分区信息(最后一个序列号和序列号)。不过,这涉及到一些数据保留,因此除非您为此添加更多逻辑,否则您将得到一个数字,表示集线器中 当前 的消息数,而不是自创建以来的总数,不是剩下要处理的总数。
更新:这里的代码显示了几种获取设备数量的方法:
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;
}
}
}
对于 c# 中的 Azure IoThub,我们只有这两种方法可用。
Device device = await registryManager.GetDeviceAsync("deviceId");
和
device = await registryManager.GetDevicesAsync("max count");
但是如何使用 c# 获取所有可用设备数或活动设备数以及消息数?
据我所知,
没有直接的方法来实际获取 total number of devices
。或者你可以做的是创建一个列表,每当你使用 AddDeviceAsync
添加设备时,你应该将对象推送到列表中。
与消息总数相同,您应该创建自己的方式来保持值更新。
以下代码应该有所帮助。
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);
}
}
}
您感兴趣的值是 Azure IoT Hub metrics 的一部分。基本上你可以获得他们的:
可以使用 device query 检索 设备数量 ,例如:
SELECT COUNT() AS numberOfDevices FROM c
其中 returns 是这样的:
[
{
"numberOfDevices": 123
}
]
要检索条消息,您需要连接到与事件中心兼容的端点,连接到每个基础分区并查看每个分区信息(最后一个序列号和序列号)。不过,这涉及到一些数据保留,因此除非您为此添加更多逻辑,否则您将得到一个数字,表示集线器中 当前 的消息数,而不是自创建以来的总数,不是剩下要处理的总数。
更新:这里的代码显示了几种获取设备数量的方法:
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;
}
}
}