protected void Initialize(MockContext context)
        {
            if (_isInitialized)
            {
                return;
            }

            lock (_initializeLock)
            {
                if (_isInitialized)
                {
                    return;
                }

                _testEnvironment = TestEnvironmentFactory.GetTestEnvironment();
                _resourcesClient = IotHubTestUtilities.GetResourceManagementClient(context, new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });
                _iotHubClient = IotHubTestUtilities.GetIotHubClient(context, new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });
                _ehClient = IotHubTestUtilities.GetEhClient(context, new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });
                _sbClient = IotHubTestUtilities.GetSbClient(context, new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });

                _location = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AZURE_LOCATION"))
                    ? IotHubTestUtilities.DefaultLocation
                    : Environment.GetEnvironmentVariable("AZURE_LOCATION").Replace(" ", "").ToLower();

                _isInitialized = true;
            }
        }
示例#2
0
        protected void Initialize(MockContext context)
        {
            if (!initialized)
            {
                lock (locker)
                {
                    if (!initialized)
                    {
                        testEnv         = TestEnvironmentFactory.GetTestEnvironment();
                        resourcesClient = IotHubTestUtilities.GetResourceManagementClient(context, new RecordedDelegatingHandler {
                            StatusCodeToReturn = HttpStatusCode.OK
                        });
                        iotHubClient = IotHubTestUtilities.GetIotHubClient(context, new RecordedDelegatingHandler {
                            StatusCodeToReturn = HttpStatusCode.OK
                        });

                        if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION")))
                        {
                            location = IotHubTestUtilities.DefaultLocation;
                        }
                        else
                        {
                            location = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION").Replace(" ", "").ToLower();
                        }

                        this.initialized = true;
                    }
                }
            }
        }
示例#3
0
 public FileRecorder(ILoggingChannel loggingChannel)
 {
     isRecording = false;
     InitializeAudioSettings();
     this.loggingChannel = loggingChannel;
     iotHubClient        = new IotHubClient(loggingChannel);
 }
        ServerBootstrap SetupBootstrap(ChannelHandlerAdapter firstHandler)
        {
            Contract.Requires(firstHandler != null);

            return(new ServerBootstrap()
                   .Group(this.parentEventLoopGroup, this.eventLoopGroup)
                   .Option(ChannelOption.SoBacklog, ListenBacklogSize)
                   .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
                   .Channel <TcpServerSocketChannel>()
                   .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                int connectionPoolSize = this.settingsProvider.GetIntegerSetting("IotHubClient.ConnectionPoolSize", DefaultConnectionPoolSize);
                TimeSpan connectionIdleTimeout = this.settingsProvider.GetTimeSpanSetting("IotHubClient.ConnectionIdleTimeout", DefaultConnectionIdleTimeout);
                string connectionString = this.iotHubClientSettings.IotHubConnectionString;
                int maxInboundMessageSize = this.settingsProvider.GetIntegerSetting("MaxInboundMessageSize", 256 * 1024);

                var messagingAddressConverter = new IoTHubProvider.Addressing.MessageAddressConverter();
                Func <IDeviceIdentity, Task <ITcpIoTHubMessagingServiceClient> > deviceClientFactory
                    = IotHubClient.PreparePoolFactory(connectionString, connectionPoolSize, connectionIdleTimeout, this.iotHubClientSettings);

                MessagingBridgeFactoryFunc bridgeFactory
                    = async deviceIdentity => new SingleClientMessagingBridge(deviceIdentity, await deviceClientFactory(deviceIdentity));

                channel.Pipeline.AddLast(firstHandler);
                channel.Pipeline.AddLast(DeviceTopicDecoder.HandlerName, new DeviceTopicDecoder(this.credentialProvider, messagingAddressConverter.TopicTemplates));
                channel.Pipeline.AddLast(SocketIoTHubAdapter.HandlerName, new SocketIoTHubAdapter(this.settings, credentialProvider, this.authProvider, bridgeFactory));
            })));
        }
示例#5
0
        private static async Task <IotHubClient> GetIotHubClientAsync(Config config)
        {
            var serviceClientCredentials = await ApplicationTokenProvider.LoginSilentAsync(config.TenantId, config.ClientId, config.ClientSecret);

            var iotHubClient = new IotHubClient(serviceClientCredentials);

            iotHubClient.SubscriptionId = config.SubscriptionId;
            return(iotHubClient);
        }
示例#6
0
        async Task EnsureServerInitializedAsync()
        {
            if (this.ServerAddress != null)
            {
                return;
            }

            int threadCount   = Environment.ProcessorCount;
            var executorGroup = new MultithreadEventLoopGroup(threadCount);
            var bufAllocator  = new PooledByteBufferAllocator(16 * 1024, 10 * 1024 * 1024 / threadCount); // reserve 10 MB for 64 KB buffers
            BlobSessionStatePersistenceProvider sessionStateProvider = await BlobSessionStatePersistenceProvider.CreateAsync(
                this.settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageConnectionString"),
                this.settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageContainerName"));

            TableQos2StatePersistenceProvider qos2StateProvider = await TableQos2StatePersistenceProvider.CreateAsync(
                this.settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageConnectionString"),
                this.settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageTableName"));

            var settings        = new Settings(this.settingsProvider);
            var authProvider    = new SasTokenDeviceIdentityProvider();
            var topicNameRouter = new ConfigurableMessageRouter();

            IotHubClientFactoryFunc iotHubClientFactoryMethod = IotHubClient.PreparePoolFactory(settings.IotHubConnectionString + ";DeviceId=stub", "a", 1);
            var iotHubFactory = new IotHubCommunicationFactory(iotHubClientFactoryMethod);

            ServerBootstrap server = new ServerBootstrap()
                                     .Group(executorGroup)
                                     .Channel <TcpServerSocketChannel>()
                                     .ChildOption(ChannelOption.Allocator, bufAllocator)
                                     .ChildOption(ChannelOption.AutoRead, false)
                                     .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(TlsHandler.Server(this.tlsCertificate));
                ch.Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(true, 256 * 1024),
                    new LoggingHandler(),
                    new MqttIotHubAdapter(
                        settings,
                        sessionStateProvider,
                        authProvider,
                        qos2StateProvider,
                        iotHubFactory,
                        topicNameRouter),
                    new XUnitLoggingHandler(this.output));
            }));

            IChannel serverChannel = await server.BindAsync(IPAddress.Any, this.ProtocolGatewayPort);

            this.ScheduleCleanup(async() =>
            {
                await serverChannel.CloseAsync();
                await executorGroup.ShutdownGracefullyAsync();
            });
            this.ServerAddress = IPAddress.Loopback;
        }
        async Task EnsureServerInitializedAsync()
        {
            if (this.ServerAddress != null)
            {
                return;
            }

            int threadCount   = Environment.ProcessorCount;
            var executorGroup = new MultithreadEventLoopGroup(threadCount);
            BlobSessionStatePersistenceProvider sessionStateProvider = await BlobSessionStatePersistenceProvider.CreateAsync(
                this.settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageConnectionString"),
                this.settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageContainerName"));

            TableQos2StatePersistenceProvider qos2StateProvider = await TableQos2StatePersistenceProvider.CreateAsync(
                this.settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageConnectionString"),
                this.settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageTableName"));

            var settings             = new Settings(this.settingsProvider);
            var iotHubClientSettings = new IotHubClientSettings(this.settingsProvider);
            var authProvider         = new SasTokenDeviceIdentityProvider();
            var topicNameRouter      = new ConfigurableMessageAddressConverter();

            var iotHubClientFactory = IotHubClient.PreparePoolFactory(iotHubClientSettings.IotHubConnectionString, 400, TimeSpan.FromMinutes(5),
                                                                      iotHubClientSettings, PooledByteBufferAllocator.Default, topicNameRouter);
            MessagingBridgeFactoryFunc bridgeFactory = async identity => new SingleClientMessagingBridge(identity, await iotHubClientFactory(identity));

            ServerBootstrap server = new ServerBootstrap()
                                     .Group(executorGroup)
                                     .Channel <TcpServerSocketChannel>()
                                     .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
                                     .ChildOption(ChannelOption.AutoRead, false)
                                     .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(TlsHandler.Server(this.tlsCertificate));
                ch.Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(true, 256 * 1024),
                    new LoggingHandler("SERVER"),
                    new MqttAdapter(
                        settings,
                        sessionStateProvider,
                        authProvider,
                        qos2StateProvider,
                        bridgeFactory),
                    new XUnitLoggingHandler(this.output));
            }));

            IChannel serverChannel = await server.BindAsync(IPAddress.Any, this.ProtocolGatewayPort);

            this.ScheduleCleanup(async() =>
            {
                await serverChannel.CloseAsync();
                await executorGroup.ShutdownGracefullyAsync();
            });
            this.ServerAddress = IPAddress.Loopback;
        }
        ServerBootstrap SetupBootstrap()
        {
            int maxInboundMessageSize = this.settingsProvider.GetIntegerSetting("MaxInboundMessageSize", 256 * 1024);
            int connectionPoolSize;

            if (!this.settingsProvider.TryGetIntegerSetting("IotHubClient.ConnectionPoolSize", out connectionPoolSize))
            {
                connectionPoolSize = DefaultConnectionPoolSize;
            }

            TimeSpan connectionIdleTimeout;

            if (!this.settingsProvider.TryGetTimeSpanSetting("IotHubClient.ConnectionIdleTimeout", out connectionIdleTimeout))
            {
                connectionIdleTimeout = DefaultConnectionIdleTimeout;
            }

            string connectionString = this.settings.IotHubConnectionString;

            if (connectionString.IndexOf("DeviceId=", StringComparison.OrdinalIgnoreCase) == -1)
            {
                connectionString += ";DeviceId=stub";
            }

            var deviceClientFactory = new ThreadLocal <IotHubClientFactoryFunc>(() =>
            {
                string poolId = Guid.NewGuid().ToString("N");
                return(IotHubClient.PreparePoolFactory(connectionString, poolId, connectionPoolSize, connectionIdleTimeout));
            });

            var iotHubCommunicationFactory = new IotHubCommunicationFactory(deviceClientFactory.Value);

            return(new ServerBootstrap()
                   .Group(this.parentEventLoopGroup, this.eventLoopGroup)
                   .Option(ChannelOption.SoBacklog, ListenBacklogSize)
                   .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
                   .ChildOption(ChannelOption.AutoRead, false)
                   .Channel <TcpServerSocketChannel>()
                   .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                channel.Pipeline.AddLast(TlsHandler.Server(this.tlsCertificate));
                channel.Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(true, maxInboundMessageSize),
                    new MqttIotHubAdapter(
                        this.settings,
                        this.sessionStateManager,
                        this.authProvider,
                        this.qos2StateProvider,
                        iotHubCommunicationFactory,
                        this.iotHubMessageRouter));
            })));
        }
示例#9
0
        private static async Task ObserveIoTHub(Config config, CancellationToken cancellationToken)
        {
            string previousState           = null;
            string previousEndpointAddress = null;

            IotHubClient iotHubClient = await GetIotHubClientAsync(config);

            SharedAccessSignatureAuthorizationRule sasAuthorizationRule = await GetIotHubKeyAsync(iotHubClient, config, cancellationToken);

            while (!cancellationToken.IsCancellationRequested)
            {
                IotHubDescription iotHubDescription = await GetIotHubDescriptionAsync(iotHubClient, config, cancellationToken);

                var currentState           = iotHubDescription.Properties.State;
                var currentEndpointAddress = iotHubDescription.Properties.EventHubEndpoints["events"].Endpoint;
                var currentEndpointPath    = iotHubDescription.Properties.EventHubEndpoints["events"].Path;

                var stateChanged    = currentState != previousState;
                var endpointChanged = currentEndpointAddress != previousEndpointAddress;

                if (stateChanged || endpointChanged)
                {
                    // print changes
                    Console.WriteLine();
                    Console.WriteLine($"-----------------------------------------------------------");
                    Console.WriteLine($"Date time:             {DateTime.Now}");
                    Console.WriteLine($"Status changed:        {previousState} => {currentState}");
                    Console.WriteLine($"Endpoint Address:      {currentEndpointAddress}");
                    Console.WriteLine($"Endpoint Path:         {currentEndpointPath}");

                    if (endpointChanged)
                    {
                        var connectionString = BuildEventHubConnectionString(iotHubDescription, sasAuthorizationRule);
                        Console.WriteLine($"Endpoint new/changed");
                        Console.WriteLine($"new connection string: {connectionString}");
                    }
                }
                else
                {
                    // print indicator that application is running
                    Console.Write(".");
                }

                previousState           = currentState;
                previousEndpointAddress = currentEndpointAddress;

                await Task.Delay(1000);
            }
        }
        private async Task CreateIotHub(IResourceGroup resourceGroup)
        {
            var client = new IotHubClient(new TokenCredentials(_accessToken))
            {
                SubscriptionId = _configuration.SubscriptionId
            };
            var iotHub = await client.IotHubResource.BeginCreateOrUpdateAsync(
                resourceGroup.Name,
                _configuration.ResourceNamePrefix + "Hub",
                new IotHubDescription(
                    _configuration.RegionName,
                    new IotHubSkuInfo("F1", IotHubSkuTier.Free, 1)));

            Console.WriteLine($"Successfully created or updated Iot Hub '{iotHub.Name}'");
        }
        /// <summary>
        /// Helper to create new client
        /// </summary>
        /// <returns></returns>
        private async Task <IotHubClient> CreateIoTHubClientAsync(
            IResourceGroupResource resourceGroup)
        {
            var environment = await resourceGroup.Subscription.GetAzureEnvironmentAsync();

            var credentials = await _creds.GetTokenCredentialsAsync(
                environment.ManagementEndpoint);

            var client = new IotHubClient(credentials)
            {
                SubscriptionId = await resourceGroup.Subscription.GetSubscriptionId()
            };

            return(client);
        }
        public async Task <string> GetModulePrimaryKey(RequestedResource sr)
        {
            var credentials = SdkContext.AzureCredentialsFactory.FromMSI(new MSILoginInformation(MSIResourceType.AppService),
                                                                         AzureEnvironment.AzureGlobalCloud);
            var azure = Azure
                        .Configure()
                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .Authenticate(credentials)
                        .WithDefaultSubscription();

            string iothubowner = string.Empty;

            var    azureServiceTokenProvider = new AzureServiceTokenProvider();
            string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com");

            IotHubClient hubClient = new IotHubClient(new TokenCredentials(accessToken))
            {
                SubscriptionId = azure.GetCurrentSubscription().SubscriptionId
            };
            var listHubs = await hubClient.IotHubResource.ListBySubscriptionAsync();

            do
            {
                var hub = listHubs.Where(iothub => string.Equals(iothub.Name, sr.iotHubName)).FirstOrDefault();
                if (!string.IsNullOrEmpty(hub.Id))
                {
                    iothubowner = (await hubClient.IotHubResource.GetKeysForKeyNameAsync(GetResourceGroupName(hub.Id), hub.Name, "iothubowner")).PrimaryKey;
                    break;
                }
            } while (!string.IsNullOrEmpty(listHubs.NextPageLink));

            if (string.IsNullOrEmpty(iothubowner))
            {
                throw new Exception("Failed to retrieve IoT Hub Primary Key string");
            }

            string iotHubConnString = IotHubConnectionStringBuilder.Create(sr.iotHubFQDN, new ServiceAuthenticationWithSharedAccessPolicyKey("iothubowner", iothubowner)).ToString();

            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnString);

            var modulesOnDevice = await registryManager.GetModuleAsync(sr.deviceId, sr.moduleId);

            return(!string.IsNullOrEmpty(modulesOnDevice.Authentication.SymmetricKey.PrimaryKey) ? modulesOnDevice.Authentication.SymmetricKey.PrimaryKey : null);
        }
示例#13
0
        private static IotHubClient GetNewIotHubClient(ILogger log)
        {
            var authContext            = new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", TenantId));
            var credential             = new ClientCredential(ApplicationId, ApplicationPassword);
            AuthenticationResult token = authContext.AcquireTokenAsync("https://management.core.windows.net/", credential).Result;

            if (token == null)
            {
                log.LogError("Failed to obtain the authentication token");
                return(null);
            }

            var creds  = new TokenCredentials(token.AccessToken);
            var client = new IotHubClient(creds);

            client.SubscriptionId = SubscriptionId;

            return(client);
        }
示例#14
0
        static async Task Main(string[] args)
        {
            // connect management lib to iotHub
            IotHubClient client = GetNewIotHubClient();

            if (client == null)
            {
                Console.WriteLine("Unable to create IotHub client");
                return;
            }

            IotHubDescription desc       = client.IotHubResource.Get(ResourceGroupName, IotHubName);
            string            currentSKU = desc.Sku.Name;
            long currentUnits            = desc.Sku.Capacity.Value;

            Console.WriteLine("Current SKU Tier: " + desc.Sku.Tier);
            Console.WriteLine("Current SKU Name: " + currentSKU);
            Console.WriteLine("Current SKU Capacity: " + currentUnits.ToString());

            // update the IoT Hub description with the new sku level and units
            desc.Sku.Name     = "S3";
            desc.Sku.Capacity = 2;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            client.IotHubResource.CreateOrUpdate(ResourceGroupName, IotHubName, desc);

            stopwatch.Stop();

            TimeSpan t      = TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds);
            string   answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
                                            t.Hours,
                                            t.Minutes,
                                            t.Seconds,
                                            t.Milliseconds);

            Console.WriteLine($"Elapsed Time: {answer}");
            Console.WriteLine($"Changed SKU Capacity: {desc.Sku.Capacity}");
            Console.WriteLine($"Changed SKU Name: {desc.Sku.Name}");
        }
 private Task <IotHubDescription> GetIotHubAsync(IotHubClient iotHubClient, ResourceGroup resourceGroup, string hubName)
 {
     return(iotHubClient.IotHubResource.CreateOrUpdateAsync(
                resourceGroup.Name,
                hubName,
                new IotHubDescription
     {
         Location = resourceGroup.Location,
         Subscriptionid = _testEnv.SubscriptionId,
         Resourcegroup = resourceGroup.Name,
         Sku = new IotHubSkuInfo
         {
             Name = "S1",
             Capacity = 1,
         },
         Properties = new IotHubProperties
         {
             Routing = new RoutingProperties(),
         },
     }));
 }
示例#16
0
        public IotHubMgmtClient(
            string subscriptionId,
            RestClient restClient
            )
        {
            // We need to initialize new RestClient so that we
            // extract RootHttpHandler and DelegatingHandlers out of it.
            var iotHubRestClient = RestClient
                                   .Configure()
                                   .WithEnvironment(restClient.Environment)
                                   .WithCredentials(restClient.Credentials)
                                   //.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
                                   .Build();

            _iotHubClient = new IotHubClient(
                restClient.Credentials,
                iotHubRestClient.RootHttpHandler,
                iotHubRestClient.Handlers.ToArray()
                )
            {
                SubscriptionId = subscriptionId
            };
        }
示例#17
0
        public DeviceManager()
        {
            AzureCredentials creds = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
                clientId,
                secret,
                tenantId,
                AzureEnvironment.AzureGlobalCloud);

            // create clients
            _azure = Azure
                     .Configure()
                     .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                     .Authenticate(creds)
                     .WithSubscription(subscriptionId);

            _hubClient = new IotHubClient(creds)
            {
                SubscriptionId = subscriptionId
            };
            _rmClient = new ResourceManagementClient(creds)
            {
                SubscriptionId = subscriptionId
            };
        }
示例#18
0
 public IoTHubManagementClient(IotHubClient client, AppConfig config)
 {
     this.client = client;
     this.config = config;
     this.client.SubscriptionId = this.config.Global.SubscriptionId;
 }
示例#19
0
        public static void IotHubScaleWorker([ActivityTrigger] IDurableActivityContext context, ILogger log)
        {
            IotHubClient client = GetNewIotHubClient(log);

            if (client == null)
            {
                log.LogError("Unable to create IotHub client");
                return;
            }

            IotHubDescription desc       = client.IotHubResource.Get(ResourceGroupName, IotHubName);
            string            currentSKU = desc.Sku.Name;
            long currentUnits            = desc.Sku.Capacity;

            // get current "used" message count for the IotHub
            long currentMessageCount         = -1;
            IPage <IotHubQuotaMetricInfo> mi = client.IotHubResource.GetQuotaMetrics(ResourceGroupName, IotHubName);

            foreach (IotHubQuotaMetricInfo info in mi)
            {
                if (info.Name == "TotalMessages")
                {
                    currentMessageCount = (long)info.CurrentValue;
                }
            }
            if (currentMessageCount < 0)
            {
                log.LogError("Unable to retreive current message count for IoTHub");
                return;
            }

            // compute the desired message threshold for the current sku
            long messageLimit = GetSkuUnitThreshold(desc.Sku.Name, desc.Sku.Capacity, ThresholdPercentage);

            log.LogInformation("Current SKU Tier: " + desc.Sku.Tier);
            log.LogInformation("Current SKU Name: " + currentSKU);
            log.LogInformation("Current SKU Capacity: " + currentUnits.ToString());
            log.LogInformation("Current Message Count:  " + currentMessageCount.ToString());
            log.LogInformation("Current Sku/Unit Message Threshold:  " + messageLimit);

            // if we are below the threshold, nothing to do, bail
            if (currentMessageCount < messageLimit)
            {
                log.LogInformation(String.Format("Current message count of {0} is less than the threshold of {1}. Nothing to do", currentMessageCount.ToString(), messageLimit));
                return;
            }
            else
            {
                log.LogInformation(String.Format("Current message count of {0} is over the threshold of {1}. Need to scale IotHub", currentMessageCount.ToString(), messageLimit));
            }

            // figure out what new sku level and 'units' we need to scale to
            string newSkuName  = desc.Sku.Name;
            long   newSkuUnits = GetScaleUpTarget(desc.Sku.Name, desc.Sku.Capacity);

            if (newSkuUnits < 0)
            {
                log.LogError("Unable to determine new scale units for IoTHub (perhaps you are already at the highest units for a tier?)");
                return;
            }

            // update the IoT Hub description with the new sku level and units
            desc.Sku.Name     = newSkuName;
            desc.Sku.Capacity = newSkuUnits;

            // scale the IoT Hub by submitting the new configuration (tier and units)
            DateTime dtStart = DateTime.Now;

            client.IotHubResource.CreateOrUpdate(ResourceGroupName, IotHubName, desc);
            TimeSpan ts = new TimeSpan(DateTime.Now.Ticks - dtStart.Ticks);

            log.LogInformation(String.Format("Updated IoTHub {0} from {1}-{2} to {3}-{4} in {5} seconds", IotHubName, currentSKU, currentUnits, newSkuName, newSkuUnits, ts.Seconds));
        }
        ServerBootstrap SetupBootstrap()
        {
            if (this.settings.DeviceReceiveAckCanTimeout && this.iotHubClientSettings.MaxPendingOutboundMessages > 1)
            {
                throw new InvalidOperationException("Cannot maintain ordering on retransmission with more than 1 allowed pending outbound message.");
            }

            int      maxInboundMessageSize = this.settingsProvider.GetIntegerSetting("MaxInboundMessageSize", 256 * 1024);
            int      connectionPoolSize    = this.settingsProvider.GetIntegerSetting("IotHubClient.ConnectionPoolSize", DefaultConnectionPoolSize);
            TimeSpan connectionIdleTimeout = this.settingsProvider.GetTimeSpanSetting("IotHubClient.ConnectionIdleTimeout", DefaultConnectionIdleTimeout);
            string   connectionString      = this.iotHubClientSettings.IotHubConnectionString;

            Func <IDeviceIdentity, Task <IMessagingServiceClient> > deviceClientFactory = IotHubClient.PreparePoolFactory(connectionString, connectionPoolSize,
                                                                                                                          connectionIdleTimeout, this.iotHubClientSettings, PooledByteBufferAllocator.Default, this.topicNameConverter);
            MessagingBridgeFactoryFunc bridgeFactory = async deviceIdentity => new SingleClientMessagingBridge(deviceIdentity, await deviceClientFactory(deviceIdentity));

            return(new ServerBootstrap()
                   .Group(this.parentEventLoopGroup, this.eventLoopGroup)
                   .Option(ChannelOption.SoBacklog, ListenBacklogSize)
                   .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
                   .ChildOption(ChannelOption.AutoRead, false)
                   .Channel <TcpServerSocketChannel>()
                   .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                channel.Pipeline.AddLast(TlsHandler.Server(this.tlsCertificate));
                channel.Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(true, maxInboundMessageSize),
                    new MqttAdapter(
                        this.settings,
                        this.sessionStateManager,
                        this.authProvider,
                        this.qos2StateProvider,
                        bridgeFactory));
            })));
        }
示例#21
0
        private static async Task <SharedAccessSignatureAuthorizationRule> GetIotHubKeyAsync(IotHubClient iotHubClient, Config config, CancellationToken cancellationToken)
        {
            const string iotHubSharedAccessKeyName = "iothubowner";
            var          keys = await iotHubClient.IotHubResource.ListKeysAsync(config.ResourceGroupName, config.IotHubName, cancellationToken);

            var sharedAccessSignatureAuthorizationRule = keys.Single(k => k.KeyName == iotHubSharedAccessKeyName);

            return(sharedAccessSignatureAuthorizationRule);
        }
示例#22
0
        private static async Task <IotHubDescription> GetIotHubDescriptionAsync(IotHubClient iotHubClient, Config config, CancellationToken cancellationToken = default)
        {
            IotHubDescription iotHubDescription = await iotHubClient.IotHubResource.GetAsync(config.ResourceGroupName, config.IotHubName, cancellationToken);

            return(iotHubDescription);
        }
示例#23
0
        static void Main(string[] args)
        {
            var resourceGroupName = "your resource group name of iot hub";
            var iothubName        = "your iot hub name";
            var tenantId          = "your tenant";
            var subscriptionId    = "your subscription";

            #region for native client, based on user login
            var nativeClientId    = "your native client id";
            var redirectUri       = "your native client redirect uri";
            var adServiceSettings = new ActiveDirectoryServiceSettings
            {
                AuthenticationEndpoint = new Uri(AzureEnvironment.AzureChinaCloud.AuthenticationEndpoint),
                TokenAudience          = new Uri(AzureEnvironment.AzureChinaCloud.ResourceManagerEndpoint),
                ValidateAuthority      = true
            };
            var adClientSettings = new ActiveDirectoryClientSettings()
            {
                ClientId          = nativeClientId,
                ClientRedirectUri = new Uri(redirectUri)
            };
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            ServiceClientCredentials azureCredential = null;
            try
            {
                azureCredential = UserTokenProvider.LoginWithPromptAsync(tenantId, adClientSettings, adServiceSettings).Result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Acquire credential failed: {ex.Message}");
            }
            #endregion

            #region for web client, based on clientid and clientsecret
            //var webClientId = "your web client id";
            //azureCredential = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
            //        webClientId,
            //        "!!123abc",
            //        tenantId,
            //        AzureEnvironment.AzureChinaCloud);
            #endregion

            if (azureCredential != null)
            {
                var iothubClient = new IotHubClient(new Uri("https://management.chinacloudapi.cn/"), azureCredential, new RetryDelegatingHandler());
                iothubClient.SubscriptionId = subscriptionId;

                var iothubResource = iothubClient.IotHubResource;

                // get iothub description
                var iothubDescription = iothubResource.Get(resourceGroupName, iothubName);
                Console.WriteLine($"Get iothub successfully: {iothubDescription.Name}");

                // set C2D message default ttl to 2 hours
                iothubDescription.Properties.CloudToDevice.DefaultTtlAsIso8601 = TimeSpan.FromHours(2);

                try
                {
                    // commit the change
                    iothubResource.CreateOrUpdate(resourceGroupName, iothubName, iothubDescription);
                    Console.WriteLine("Update iothub successfully!");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Update iothub failed: {ex.Message}");
                }
            }

            Console.WriteLine("Press ENTER to exit!");
            Console.ReadLine();
        }
 public ServiceConsumerTester()
 {
     iotHubClient = new IotHubClient();
 }