예제 #1
0
        public async Task <string> DeleteDevice(string deviceId)
        {
            string             result             = null;
            RegistryStatistics registryStatistics = await registryManager.GetRegistryStatisticsAsync();

            IEnumerable <Device> devices = await registryManager.GetDevicesAsync((Int32)registryStatistics.TotalDeviceCount);

            bool flag = false;

            foreach (var obj in devices)
            {
                if (obj.Id == deviceId)
                {
                    await registryManager.RemoveDeviceAsync(obj);

                    flag = true;
                }
            }
            if (flag)
            {
                result = "success";
            }
            else
            {
                result = "error";
            }
            return(result);
        }
예제 #2
0
        public async Task <Response <RegistryStatistics> > GetDeviceStatisticsAsync(CancellationToken cancellationToken = default)
        {
            using var message = CreateGetDeviceStatisticsRequest();
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            {
                RegistryStatistics value = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                value = RegistryStatistics.DeserializeRegistryStatistics(document.RootElement);
                return(Response.FromValue(value, message.Response));
            }
        private static async System.Threading.Tasks.Task RemoveDevice()
        {
            registryManager = RegistryManager.CreateFromConnectionString(connectionString);
            Console.WriteLine("Please type in the pattern. If a device's id contain this, it will be removed.");
            string pattern = Console.ReadLine();

            // TODO: Something wrong here. After deleting devices the total number of devices is not updated.
            RegistryStatistics stat = await registryManager.GetRegistryStatisticsAsync();

            long total_num_device = stat.TotalDeviceCount;

            Console.WriteLine("The total number of devices in this IoThub is " + total_num_device + ". How many devices do you want to remove?");

            string amount_devices_tobe_removed = Console.ReadLine();
            int    num_devices_tobe_removed    = Convert.ToInt32(amount_devices_tobe_removed);

            while (num_devices_tobe_removed > total_num_device)
            {
                Console.WriteLine("# of to be removed device is larger than the total number of devices connected to the IoThub. Please provide a new number");
                num_devices_tobe_removed = Convert.ToInt16(Console.ReadLine());
            }

            int num_retrived_device = 0;
            int num_removed_device  = 0;

            while ((num_removed_device < num_devices_tobe_removed) && (num_retrived_device < total_num_device))
            {
                num_retrived_device += 100;
                var devices = await registryManager.GetDevicesAsync(num_retrived_device);

                foreach (var item in devices)
                {
                    if (item.Id.Contains(pattern))
                    {
                        await registryManager.RemoveDeviceAsync(item);

                        Console.WriteLine("Divice: " + item.Id + " has been removed");
                        num_removed_device++;
                        if (num_removed_device == num_devices_tobe_removed)
                        {
                            break;
                        }
                    }
                }
            }
            Console.WriteLine("Total number of removed device is " + num_removed_device);
            Console.ReadLine();
        }
예제 #4
0
        public async Task <ConcurrentBag <Device> > GetDevices()
        {
            RegistryStatistics registryStatistics = await registryManager.GetRegistryStatisticsAsync();

            int maxCount = (int)registryStatistics.TotalDeviceCount;
            IEnumerable <Device> tempDevices = await registryManager.GetDevicesAsync(maxCount);

            List <string> IotEdgeDeviceIdList = null;
            List <string> IotDeviceIdList     = null;

            foreach (var d in tempDevices)
            {
                //var device = await registryManager.GetDeviceAsync(d.Id);
                if (d.Capabilities.IotEdge == true)
                {
                    IotEdgeDeviceIdList.Add(d.Id);
                }
                else
                {
                    IotDeviceIdList.Add(d.Id);
                }
            }
            return(null);
        }
예제 #5
0
 public static PSIotHubRegistryStatistics ToPSIotHubRegistryStatistics(RegistryStatistics registryStats)
 {
     return(ConvertObject <RegistryStatistics, PSIotHubRegistryStatistics>(registryStats));
 }
        public override void ExecuteCmdlet()
        {
            RegistryStatistics registryStats = this.IotHubClient.IotHubResource.GetStats(this.ResourceGroupName, this.Name);

            this.WriteObject(IotHubUtils.ToPSIotHubRegistryStatistics(registryStats), false);
        }
예제 #7
0
        public async Task IotHubClient_HubCreate()
        {
            try
            {
                using var context = MockContext.Start(GetType());
                Initialize(context);

                // Create resource group
                ResourceGroup resourceGroup = await CreateResourceGroupAsync(IotHubTestUtilities.DefaultResourceGroupName)
                                              .ConfigureAwait(false);

                // Check if hub exists and delete
                IotHubNameAvailabilityInfo iotHubNameAvailabilityInfo = await _iotHubClient.IotHubResource
                                                                        .CheckNameAvailabilityAsync(IotHubTestUtilities.DefaultIotHubName)
                                                                        .ConfigureAwait(false);

                if (!iotHubNameAvailabilityInfo.NameAvailable.Value)
                {
                    _ = await _iotHubClient.IotHubResource
                        .DeleteAsync(
                        IotHubTestUtilities.DefaultResourceGroupName,
                        IotHubTestUtilities.DefaultIotHubName)
                        .ConfigureAwait(false);

                    iotHubNameAvailabilityInfo = await _iotHubClient.IotHubResource
                                                 .CheckNameAvailabilityAsync(IotHubTestUtilities.DefaultIotHubName)
                                                 .ConfigureAwait(false);

                    iotHubNameAvailabilityInfo.NameAvailable.Should().BeTrue();
                }

                // Create EH and AuthRule
                var properties = new IotHubProperties
                {
                    Routing             = await GetIotHubRoutingPropertiesAsync(resourceGroup).ConfigureAwait(false),
                    EnableDataResidency = false
                };

                IotHubDescription iotHub = await _iotHubClient.IotHubResource
                                           .CreateOrUpdateAsync(
                    resourceGroup.Name,
                    IotHubTestUtilities.DefaultIotHubName,
                    new IotHubDescription
                {
                    Location = IotHubTestUtilities.DefaultLocation,
                    Sku      = new IotHubSkuInfo
                    {
                        Name     = IotHubSku.S1,
                        Capacity = 1,
                    },
                    Properties = properties,
                })
                                           .ConfigureAwait(false);

                iotHub.Should().NotBeNull();
                iotHub.Name.Should().Be(IotHubTestUtilities.DefaultIotHubName);
                iotHub.Location.Should().Be(IotHubTestUtilities.DefaultLocation);
                iotHub.Sku.Name.Should().Be(IotHubSku.S1);
                iotHub.Sku.Capacity.Should().Be(1);
                iotHub.SystemData.CreatedAt.Should().NotBeNull();
                iotHub.Properties.EnableDataResidency.Should().BeFalse();

                // Add and get tags
                var tags = new Dictionary <string, string>
                {
                    { "key1", "value1" },
                    { "key2", "value2" }
                };
                iotHub = await _iotHubClient.IotHubResource
                         .UpdateAsync(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, tags)
                         .ConfigureAwait(false);

                iotHub.Should().NotBeNull();
                iotHub.Tags.Count().Should().Be(tags.Count);
                iotHub.Tags.Should().BeEquivalentTo(tags);

                UserSubscriptionQuotaListResult subscriptionQuota = await _iotHubClient.ResourceProviderCommon
                                                                    .GetSubscriptionQuotaAsync()
                                                                    .ConfigureAwait(false);

                subscriptionQuota.Value.Count.Should().Be(2);
                subscriptionQuota.Value.FirstOrDefault(x => x.Name.Value.Equals("freeIotHubCount")).Limit.Should().BeGreaterThan(0);
                subscriptionQuota.Value.FirstOrDefault(x => x.Name.Value.Equals("paidIotHubCount")).Limit.Should().BeGreaterThan(0);

                IPage <EndpointHealthData> endpointHealth = await _iotHubClient
                                                            .IotHubResource
                                                            .GetEndpointHealthAsync(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName);

                endpointHealth.Count().Should().Be(4);
                Assert.Contains(endpointHealth, q => q.EndpointId.Equals("events", StringComparison.OrdinalIgnoreCase));

                var testAllRoutesInput = new TestAllRoutesInput(RoutingSource.DeviceMessages, new RoutingMessage(), new RoutingTwin());
                TestAllRoutesResult testAllRoutesResult = await _iotHubClient.IotHubResource
                                                          .TestAllRoutesAsync(testAllRoutesInput, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.DefaultResourceGroupName)
                                                          .ConfigureAwait(false);

                testAllRoutesResult.Routes.Count.Should().Be(4);

                var             testRouteInput  = new TestRouteInput(properties.Routing.Routes[0], new RoutingMessage(), new RoutingTwin());
                TestRouteResult testRouteResult = await _iotHubClient.IotHubResource
                                                  .TestRouteAsync(testRouteInput, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.DefaultResourceGroupName)
                                                  .ConfigureAwait(false);

                testRouteResult.Result.Should().Be("true");

                // Get quota metrics
                var quotaMetrics = await _iotHubClient.IotHubResource
                                   .GetQuotaMetricsAsync(
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultIotHubName)
                                   .ConfigureAwait(false);

                quotaMetrics.Count().Should().BeGreaterThan(0);
                Assert.Contains(quotaMetrics, q => q.Name.Equals("TotalMessages", StringComparison.OrdinalIgnoreCase) &&
                                q.CurrentValue == 0 &&
                                q.MaxValue == 400000);

                Assert.Contains(quotaMetrics, q => q.Name.Equals("TotalDeviceCount", StringComparison.OrdinalIgnoreCase) &&
                                q.CurrentValue == 0 &&
                                q.MaxValue == 1000000);

                // Get all IoT hubs in a resource group
                IPage <IotHubDescription> iotHubs = await _iotHubClient.IotHubResource
                                                    .ListByResourceGroupAsync(IotHubTestUtilities.DefaultResourceGroupName)
                                                    .ConfigureAwait(false);

                iotHubs.Count().Should().BeGreaterThan(0);

                // Get all IoT hubs in a subscription
                IPage <IotHubDescription> iotHubBySubscription = await _iotHubClient.IotHubResource
                                                                 .ListBySubscriptionAsync()
                                                                 .ConfigureAwait(false);

                iotHubBySubscription.Count().Should().BeGreaterThan(0);

                // Get registry stats on newly created hub
                RegistryStatistics regStats = await _iotHubClient.IotHubResource
                                              .GetStatsAsync(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName)
                                              .ConfigureAwait(false);

                regStats.TotalDeviceCount.Value.Should().Be(0);
                regStats.EnabledDeviceCount.Value.Should().Be(0);
                regStats.DisabledDeviceCount.Value.Should().Be(0);

                // Get valid skus
                IPage <IotHubSkuDescription> skus = await _iotHubClient.IotHubResource
                                                    .GetValidSkusAsync(
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultIotHubName)
                                                    .ConfigureAwait(false);

                skus.Count().Should().Be(3);

                // Get all IoT hub keys
                const string hubOwnerRole = "iothubowner";
                IPage <SharedAccessSignatureAuthorizationRule> keys = await _iotHubClient.IotHubResource
                                                                      .ListKeysAsync(
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultIotHubName)
                                                                      .ConfigureAwait(false);

                keys.Count().Should().BeGreaterThan(0);
                Assert.Contains(keys, k => k.KeyName.Equals(hubOwnerRole, StringComparison.OrdinalIgnoreCase));

                // Get specific IoT Hub key
                SharedAccessSignatureAuthorizationRule key = await _iotHubClient.IotHubResource
                                                             .GetKeysForKeyNameAsync(
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultIotHubName,
                    hubOwnerRole)
                                                             .ConfigureAwait(false);

                key.KeyName.Should().Be(hubOwnerRole);

                // Get all EH consumer groups
                IPage <EventHubConsumerGroupInfo> ehConsumerGroups = await _iotHubClient.IotHubResource
                                                                     .ListEventHubConsumerGroupsAsync(
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultIotHubName,
                    IotHubTestUtilities.EventsEndpointName)
                                                                     .ConfigureAwait(false);

                ehConsumerGroups.Count().Should().BeGreaterThan(0);
                Assert.Contains(ehConsumerGroups, e => e.Name.Equals("$Default", StringComparison.OrdinalIgnoreCase));

                // Add EH consumer group
                const string ehCgName        = "testConsumerGroup";
                var          ehConsumerGroup = await _iotHubClient.IotHubResource
                                               .CreateEventHubConsumerGroupAsync(
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultIotHubName,
                    IotHubTestUtilities.EventsEndpointName,
                    ehCgName,
                    new EventHubConsumerGroupName(ehCgName))
                                               .ConfigureAwait(false);

                ehConsumerGroup.Name.Should().Be(ehCgName);

                // Get EH consumer group
                ehConsumerGroup = await _iotHubClient.IotHubResource
                                  .GetEventHubConsumerGroupAsync(
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultIotHubName,
                    IotHubTestUtilities.EventsEndpointName,
                    ehCgName)
                                  .ConfigureAwait(false);

                ehConsumerGroup.Name.Should().Be(ehCgName);

                // Delete EH consumer group
                await _iotHubClient.IotHubResource.DeleteEventHubConsumerGroupAsync(
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultIotHubName,
                    IotHubTestUtilities.EventsEndpointName,
                    ehCgName)
                .ConfigureAwait(false);

                // Get all of the available IoT Hub REST API operations
                IPage <Operation> operationList = _iotHubClient.Operations.List();
                operationList.Count().Should().BeGreaterThan(0);
                Assert.Contains(operationList, e => e.Name.Equals("Microsoft.Devices/iotHubs/Read", StringComparison.OrdinalIgnoreCase));

                // Get IoT Hub REST API read operation
                IEnumerable <Operation> hubReadOperation = operationList.Where(e => e.Name.Equals("Microsoft.Devices/iotHubs/Read", StringComparison.OrdinalIgnoreCase));
                hubReadOperation.Count().Should().Be(1);
                hubReadOperation.First().Display.Provider.Should().Be("Microsoft Devices");
                hubReadOperation.First().Display.Operation.Should().Be("Get IotHub(s)");

                // Initiate manual failover
                IotHubDescription iotHubBeforeFailover = await _iotHubClient.IotHubResource
                                                         .GetAsync(
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultIotHubName)
                                                         .ConfigureAwait(false);

                await _iotHubClient.IotHub
                .ManualFailoverAsync(
                    IotHubTestUtilities.DefaultIotHubName,
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultFailoverLocation)
                .ConfigureAwait(false);

                var iotHubAfterFailover = await _iotHubClient.IotHubResource
                                          .GetAsync(
                    IotHubTestUtilities.DefaultResourceGroupName,
                    IotHubTestUtilities.DefaultIotHubName)
                                          .ConfigureAwait(false);

                iotHubBeforeFailover.Properties.Locations[0].Role.ToLower().Should().Be("primary");
                iotHubBeforeFailover.Properties.Locations[0].Location.Replace(" ", "").ToLower().Should().Be(IotHubTestUtilities.DefaultLocation.ToLower());
                iotHubBeforeFailover.Properties.Locations[1].Role.ToLower().Should().Be("secondary");
                iotHubBeforeFailover.Properties.Locations[1].Location.Replace(" ", "").ToLower().Should().Be(IotHubTestUtilities.DefaultFailoverLocation.ToLower());

                iotHubAfterFailover.Properties.Locations[0].Role.ToLower().Should().Be("primary");
                iotHubAfterFailover.Properties.Locations[0].Location.Replace(" ", "").ToLower().Should().Be(IotHubTestUtilities.DefaultFailoverLocation.ToLower());
                iotHubAfterFailover.Properties.Locations[1].Role.ToLower().Should().Be("secondary");
                iotHubAfterFailover.Properties.Locations[1].Location.Replace(" ", "").ToLower().Should().Be(IotHubTestUtilities.DefaultLocation.ToLower());
            }
            catch (ErrorDetailsException ex)
            {
                Console.WriteLine(ex.ToString());
                Console.WriteLine($"{ex.Body.Message}: {ex.Body.Details}");
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        public static async void Run([TimerTrigger("*/2 * * * * *")] TimerInfo myTimer, ILogger log, ExecutionContext context)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(config.GetConnectionString("IoTHubConnectionString"));

            RegistryStatistics stats = await registryManager.GetRegistryStatisticsAsync();

            long krcentralTotal = stats.TotalDeviceCount;

            string queryString  = "SELECT COUNT() AS numberOfConnectedDevices FROM devices WHERE connectionState = 'Connected'";
            IQuery query        = registryManager.CreateQuery(queryString, 1);
            string json         = (await query.GetNextAsJsonAsync()).FirstOrDefault();
            long   centralCount = 0;

            if (json != null)
            {
                Dictionary <string, long> data = JsonConvert.DeserializeObject <Dictionary <string, long> >(json);
                centralCount = data["numberOfConnectedDevices"];
            }


            //-----------------

            RegistryManager registryManager_south = RegistryManager.CreateFromConnectionString(config.GetConnectionString("IoTHubConnectionString_south"));

            RegistryStatistics stats_south = await registryManager_south.GetRegistryStatisticsAsync();

            long krsouthTotal = stats_south.TotalDeviceCount;

            IQuery query_south = registryManager_south.CreateQuery(queryString, 1);
            string json_south  = (await query_south.GetNextAsJsonAsync()).FirstOrDefault();
            long   southCount  = 0;

            if (json_south != null)
            {
                Dictionary <string, long> data_south = JsonConvert.DeserializeObject <Dictionary <string, long> >(json_south);
                southCount = data_south["numberOfConnectedDevices"];
            }

            //------------------

            var result = new IoTConnectedDevice
            {
                krcentral      = centralCount,
                krsouth        = southCount,
                timestamp      = DateTime.Now.ToUniversalTime(),
                krsouthTotal   = krsouthTotal,
                krcentralTotal = krcentralTotal
            };

            var jsonResult = JsonConvert.SerializeObject(result);
            var powerbiUri = "https://api.powerbi.com/beta/72f988bf-86f1-41af-91ab-2d7cd011db47/datasets/1e275ffc-71bc-4bf6-9531-8de3391d4027/rows?key=uejGC33nWLEgVoWmAHXoOlXwy0mhxnImmHT7VvMsg5Qtj%2FvBkoEHnJY1B%2FuIEgSQkRb9IrE1haIp19t%2FJp7Xvw%3D%3D";

            var client   = new HttpClient();
            var response = await client.PostAsync(powerbiUri, new StringContent(jsonResult, Encoding.UTF8, "application/json"));

            log.LogInformation($"Send data to powerbi: {jsonResult}");
        }