Ejemplo n.º 1
0
 /// <summary>
 /// Helper to create device client
 /// </summary>
 /// <param name="cs"></param>
 /// <param name="transportSetting"></param>
 /// <returns></returns>
 private static DeviceClient Create(IotHubConnectionStringBuilder cs,
     ITransportSettings transportSetting) {
     if (cs == null) {
         throw new ArgumentNullException(nameof(cs));
     }
     if (transportSetting != null) {
         return DeviceClient.CreateFromConnectionString(cs.ToString(),
             new ITransportSettings[] { transportSetting });
     }
     return DeviceClient.CreateFromConnectionString(cs.ToString());
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Helper to create module client
 /// </summary>
 /// <param name="cs"></param>
 /// <param name="transportSetting"></param>
 /// <returns></returns>
 private static async Task<ModuleClient> CreateAsync(IotHubConnectionStringBuilder cs,
     ITransportSettings transportSetting) {
     if (transportSetting == null) {
         if (cs == null) {
             return await ModuleClient.CreateFromEnvironmentAsync();
         }
         return ModuleClient.CreateFromConnectionString(cs.ToString());
     }
     var ts = new ITransportSettings[] { transportSetting };
     if (cs == null) {
         return await ModuleClient.CreateFromEnvironmentAsync(ts);
     }
     return ModuleClient.CreateFromConnectionString(cs.ToString(), ts);
 }
Ejemplo n.º 3
0
        protected async Task GetOrCreateEdgeDeviceIdentity()
        {
            Console.WriteLine("Getting or Creating device Identity.");
            var settings = new HttpTransportSettings();

            this.proxy.ForEach(p => settings.Proxy = p);
            IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(this.iothubConnectionString);
            RegistryManager rm = RegistryManager.CreateFromConnectionString(builder.ToString(), settings);

            Device device = await rm.GetDeviceAsync(this.deviceId);

            if (device != null)
            {
                Console.WriteLine($"Device '{device.Id}' already registered on IoT hub '{builder.HostName}'");
                Console.WriteLine($"Clean up Existing device? {this.cleanUpExistingDeviceOnSuccess}");
                this.context = new DeviceContext(device, this.iothubConnectionString, rm, this.cleanUpExistingDeviceOnSuccess);
            }
            else
            {
                // if dpsAttestion is enabled, do not create a device as the
                // ESD will register with DPS to create the device in IoT Hub
                if (this.dpsAttestation.HasValue)
                {
                    this.context = new DeviceContext(this.deviceId, this.iothubConnectionString, rm, this.cleanUpExistingDeviceOnSuccess);
                }
                else
                {
                    await this.CreateEdgeDeviceIdentity(rm);
                }
            }
        }
Ejemplo n.º 4
0
        async Task CreateEdgeDeviceIdentity(RegistryManager rm)
        {
            var device = new Device(this.deviceId)
            {
                Authentication = new AuthenticationMechanism()
                {
                    Type = AuthenticationType.Sas
                },
                Capabilities = new DeviceCapabilities()
                {
                    IotEdge = true
                }
            };

            await this.parentEdgeDevice.ForEachAsync(async p =>
            {
                var parentDevice    = await rm.GetDeviceAsync(p);
                device.ParentScopes = new[] { parentDevice.Scope };
            });

            IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(this.iothubConnectionString);

            Console.WriteLine($"Registering device '{device.Id}' on IoT hub '{builder.HostName}'");

            device = await rm.AddDeviceAsync(device);

            this.context = new DeviceContext(device, builder.ToString(), rm, true);
        }
Ejemplo n.º 5
0
        protected async Task GetOrCreateEdgeDeviceIdentity()
        {
            IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(this.iothubConnectionString);
            RegistryManager rm = RegistryManager.CreateFromConnectionString(builder.ToString());

            Device device = await rm.GetDeviceAsync(this.deviceId);

            if (device != null)
            {
                Console.WriteLine($"Device '{device.Id}' already registered on IoT hub '{builder.HostName}'");
                Console.WriteLine($"Clean up Existing device? {this.cleanUpExistingDeviceOnSuccess}");

                this.context = new DeviceContext
                {
                    Device = device,
                    IotHubConnectionString = this.iothubConnectionString,
                    RegistryManager        = rm,
                    RemoveDevice           = this.cleanUpExistingDeviceOnSuccess
                };
            }
            else
            {
                await this.CreateEdgeDeviceIdentity(rm);
            }
        }
        internal static IAuthenticationMethod GetAuthenticationMethod(IotHubConnectionStringBuilder iotHubConnectionStringBuilder)
        {
            if (iotHubConnectionStringBuilder.SharedAccessKeyName != null)
            {
                return new DeviceAuthenticationWithSharedAccessPolicyKey(
                    iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.SharedAccessKeyName, iotHubConnectionStringBuilder.SharedAccessKey);
            }
            else if (iotHubConnectionStringBuilder.SharedAccessKey != null)
            {
                return new DeviceAuthenticationWithRegistrySymmetricKey(
                    iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.SharedAccessKey);
            }       
            else if (iotHubConnectionStringBuilder.SharedAccessSignature != null)
            {
                return new DeviceAuthenticationWithToken(iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.SharedAccessSignature);
            }
#if !NETMF && !WINDOWS_UWP && !PCL
            else if (iotHubConnectionStringBuilder.UsingX509Cert)
            {
                return new DeviceAuthenticationWithX509Certificate(iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.Certificate);
            }
#endif

#if NETMF
            throw new InvalidOperationException("Unsupported Authentication Method " + iotHubConnectionStringBuilder.ToString());
#else
            throw new InvalidOperationException("Unsupported Authentication Method {0}".FormatInvariant(iotHubConnectionStringBuilder));
#endif
        }
        public IoTDeviceService(IConfiguration config)
        {
            string connectionString = config["IoTHubConnectionString"];

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);

            _hostname = connectionStringBuilder.HostName;
            _manager  = RegistryManager.CreateFromConnectionString(connectionStringBuilder.ToString());
        }
        public static IotHubClientFactoryFunc PreparePoolFactory(string baseConnectionString, string poolId, int connectionPoolSize, TimeSpan?connectionIdleTimeout)
        {
            IotHubConnectionStringBuilder csb = IotHubConnectionStringBuilder.Create(baseConnectionString);
            IotHubClientFactoryFunc       iotHubClientFactory = deviceIdentity =>
            {
                var identity = (IotHubDeviceIdentity)deviceIdentity;
                csb.AuthenticationMethod = DeriveAuthenticationMethod(csb.AuthenticationMethod, identity);
                csb.HostName             = identity.IotHubHostName;
                string connectionString = csb.ToString();
                return(CreateFromConnectionStringAsync(connectionString, connectionPoolSize, connectionIdleTimeout));
            };

            return(iotHubClientFactory);
        }
Ejemplo n.º 9
0
        public static Func <IDeviceIdentity, Task <ITcpIoTHubMessagingServiceClient> > PreparePoolFactory(string baseConnectionString, int connectionPoolSize,
                                                                                                          TimeSpan?connectionIdleTimeout, IotHubClientSettings settings)
        {
            Func <IDeviceIdentity, Task <ITcpIoTHubMessagingServiceClient> > mqttCommunicatorFactory = deviceIdentity =>
            {
                IotHubConnectionStringBuilder csb = IotHubConnectionStringBuilder.Create(baseConnectionString);
                var identity = (AzureIoTHUb.IotHubDeviceIdentity)deviceIdentity;
                csb.AuthenticationMethod = DeriveAuthenticationMethod(csb.AuthenticationMethod, identity);
                csb.HostName             = identity.IotHubHostName;
                string connectionString = csb.ToString();
                return(CreateFromConnectionStringAsync(identity.Id, connectionString, connectionPoolSize, connectionIdleTimeout, settings));
            };

            return(mqttCommunicatorFactory);
        }
        public static Func <IDeviceIdentity, Task <IMessagingServiceClient> > PreparePoolFactory(string baseConnectionString, int connectionPoolSize,
                                                                                                 TimeSpan?connectionIdleTimeout, IotHubClientSettings settings, IByteBufferAllocator allocator, IMessageAddressConverter messageAddressConverter)
        {
            IotHubConnectionStringBuilder csb = IotHubConnectionStringBuilder.Create(baseConnectionString);
            Func <IDeviceIdentity, Task <IMessagingServiceClient> > mqttCommunicatorFactory = deviceIdentity =>
            {
                var identity = (IotHubDeviceIdentity)deviceIdentity;
                csb.AuthenticationMethod = DeriveAuthenticationMethod(csb.AuthenticationMethod, identity);
                csb.HostName             = identity.IotHubHostName;
                string connectionString = csb.ToString();
                return(CreateFromConnectionStringAsync(identity.Id, connectionString, connectionPoolSize, connectionIdleTimeout, settings, allocator, messageAddressConverter));
            };

            return(mqttCommunicatorFactory);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Create a DeviceClient from individual parameters
        /// </summary>
        /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param>
        /// <param name="authenticationMethod">The authentication method that is used</param>
        /// <returns>DeviceClient</returns>
        public static AmqpTransportHandler Create(string hostname, IAuthenticationMethod authenticationMethod)
        {
            if (hostname == null)
            {
                throw new ArgumentNullException(nameof(hostname));
            }

            if (authenticationMethod == null)
            {
                throw new ArgumentNullException(nameof(authenticationMethod));
            }

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, authenticationMethod);

            return(CreateFromConnectionString(connectionStringBuilder.ToString()));
        }
        public static DeviceClientFactoryFunc PreparePoolFactory(string baseConnectionString, string poolId, int connectionPoolSize)
        {
            IotHubConnectionStringBuilder csb = IotHubConnectionStringBuilder.Create(baseConnectionString);

            string[] connectionIds   = Enumerable.Range(1, connectionPoolSize).Select(index => poolId + index).ToArray();
            int      connectionIndex = 0;
            DeviceClientFactoryFunc deviceClientFactory = deviceCredentials =>
            {
                if (++connectionIndex >= connectionPoolSize)
                {
                    connectionIndex = 0;
                }
                //csb.GroupName = connectionIds[connectionIndex]; // todo: uncommment once explicit control over connection pooling is available
                csb.AuthenticationMethod = Util.DeriveAuthenticationMethod(csb.AuthenticationMethod, deviceCredentials);
                string connectionString = csb.ToString();
                return(CreateFromConnectionStringAsync(connectionString));
            };

            return(deviceClientFactory);
        }
        public static IotHubClientFactoryFunc PreparePoolFactory(string baseConnectionString, string poolId, int connectionPoolSize)
        {
            IotHubConnectionStringBuilder csb = IotHubConnectionStringBuilder.Create(baseConnectionString);
            // todo: uncommment once explicit control over connection pooling is available
            //string[] connectionIds = Enumerable.Range(1, connectionPoolSize).Select(index => poolId + index).ToArray();
            int connectionIndex = 0;
            IotHubClientFactoryFunc iotHubClientFactory = deviceIdentity =>
            {
                //if (++connectionIndex >= connectionPoolSize)
                //{
                //    connectionIndex = 0;
                //}
                //csb.GroupName = connectionIds[connectionIndex]; // todo: uncommment once explicit control over connection pooling is available
                var identity = (IotHubDeviceIdentity)deviceIdentity;
                csb.AuthenticationMethod = DeriveAuthenticationMethod(csb.AuthenticationMethod, identity);
                csb.HostName             = identity.IotHubHostName;
                string connectionString = csb.ToString();
                return(CreateFromConnectionStringAsync(connectionString));
            };

            return(iotHubClientFactory);
        }
        public static async Task <IEnumerable <string> > CreateDevices(string hubConnectionString, IEnumerable <string> deviceIds)
        {
            if (deviceIds.Count() <= 1)
            {
                return(new string[] { await CreateDevice(hubConnectionString, deviceIds.FirstOrDefault()) });
            }

            IotHubConnectionStringBuilder connection = IotHubConnectionStringBuilder.Create(hubConnectionString);
            RegistryManager registryManager          = RegistryManager.CreateFromConnectionString(connection.ToString());

            var tempIds = deviceIds;

            do
            {
                await registryManager.AddDevices2Async(tempIds.Take(100).Select(deviceId => new Device(deviceId)));

                tempIds = tempIds.Skip(100);
            } while (tempIds.Any());

            ConcurrentBag <Device> devices = new ConcurrentBag <Device>();

            tempIds = deviceIds;

            do
            {
                await Task.WhenAll(tempIds.Take(50).Select(x => AddDevice(devices, x, registryManager)));

                tempIds = tempIds.Skip(50);
            } while (tempIds.Any());


            return(devices.Select(x => "HostName=" + connection.HostName + ";DeviceId=" + x.Id + ";SharedAccessKey=" + x.Authentication.SymmetricKey.PrimaryKey));
        }
        public static async Task <string> CreateDevice(string hubConnectionString, string deviceId)
        {
            IotHubConnectionStringBuilder connection = IotHubConnectionStringBuilder.Create(hubConnectionString);
            RegistryManager registryManager          = RegistryManager.CreateFromConnectionString(connection.ToString());

            Device device;

            try
            {
                device = await registryManager.AddDeviceAsync(new Device(deviceId));
            }
            catch (Exception)
            {
                device = await registryManager.GetDeviceAsync(deviceId);
            }

            return("HostName=" + connection.HostName + ";DeviceId=" + deviceId + ";SharedAccessKey=" + device.Authentication.SymmetricKey.PrimaryKey);
        }