【问题标题】:How can I get total number of devices and total number of messages send to azure IoT hub c#如何获取发送到 azure IoT hub c# 的设备总数和消息总数
【发布时间】:2018-10-21 16:39:01
【问题描述】:

我们只有这两种方法可用于 c# 中的 azure IoThub。

Device device = await registryManager.GetDeviceAsync("deviceId");

device = await registryManager.GetDevicesAsync("max count");

但是如何使用 c# 获取所有可用设备计数或活动设备计数以及消息计数?

【问题讨论】:

    标签: c# azure c#-4.0 iot azure-iot-hub


    【解决方案1】:

    您感兴趣的值是Azure IoT Hub metrics 的一部分。基本上你可以得到他们的:

    • 使用REST APIhere
    • 为 Azure IoT Hub 添加诊断设置,并为 AllMetrics 选择以下目标之一:
      1. 事件驱动存储中存档。使用带有输入 blob 绑定的 EventGridTrigger 函数等订阅者,可以在函数体内查询指标。
      2. 或通过事件中心将指标推送到流式管道,并使用流分析作业查询指标数据。

    【讨论】:

    • 但它不包含设备计数、消息总数等
    • 添加到url查询字符串:metricnames=dailyMessageQuotaUsed,totalDeviceCount,connectedDeviceCount,...
    【解决方案2】:

    设备数量可以使用device query检索,例如:

    SELECT COUNT() AS numberOfDevices FROM c

    返回如下内容:

    [ { "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;
            }
        }
    }
    

    【讨论】:

    • 这是非常有用的,虽然它存在于registryManager中却无法轻松找到它!谢谢:)
    【解决方案3】:

    据我所知,

    没有直接的方法来实际获取 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);
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 2019-07-22
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多