// This method receives the the provisioning device client and security
        // instances created earlier.
        private static async Task <DeviceClient> ProvisionDevice(
            ProvisioningDeviceClient provisioningDeviceClient,
            SecurityProviderSymmetricKey security)
        {
            // The provisioningDeviceClient.RegisterAsync()
            // is called, which returns a DeviceRegistrationResult instance.
            // This result contains a number of properties including the DeviceId,
            // AssignedHub and the Status.
            var result = await provisioningDeviceClient
                         .RegisterAsync()
                         .ConfigureAwait(false);

            Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

            // The method then checks to ensure that the provisioning status has
            // been set and throws an exception if the device is not Assigned.
            // Other possible results here include Unassigned, Assigning,
            // Failed and Disabled.
            if (result.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'");
            }

            // The DeviceAuthenticationWithRegistrySymmetricKey class simplifies
            // the creation of an IoT Hub connection string using the device
            // ID and the Primary Symmetric Key
            var auth = new DeviceAuthenticationWithRegistrySymmetricKey(
                result.DeviceId,
                security.GetPrimaryKey());

            // Finally, a DeviceClient instance is returned that is connected
            // to the desired IoT Hub, using the authentication created above,
            // and using the AMQP protocol.
            return(DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp));
        }
Пример #2
0
        private ValueTask <DeviceClient> BuildDeviceClientAsync(DeviceServiceSettings deviceServiceSettings)
        {
            if (cachedDeviceClient != null)
            {
                return(new ValueTask <DeviceClient>(cachedDeviceClient));
            }

            return(new ValueTask <DeviceClient>(CreateAndCacheDeviceClient()));

            async Task <DeviceClient> CreateAndCacheDeviceClient()
            {
                var registryManager = RegistryManager.CreateFromConnectionString(deviceServiceSettings.IoTHubConnectionString);
                var device          = await registryManager.GetDeviceAsync(deviceServiceSettings.DeviceName);

                if (device == null)
                {
                    var message = $"Device {deviceServiceSettings.DeviceName} is not registered!";
                    DeviceSimulatorActorEventSource.Current.ExceptionOccured(message);
                    throw new InvalidOperationException(message);
                }

                var deviceKeyInfo = new DeviceAuthenticationWithRegistrySymmetricKey(deviceServiceSettings.DeviceName, device.Authentication.SymmetricKey.PrimaryKey);
                var iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(deviceServiceSettings.IoTHubConnectionString);

                cachedDeviceClient = DeviceClient.Create(
                    iotHubConnectionStringBuilder.HostName,
                    deviceKeyInfo,
                    DeviceClientTransportSettings);

                return(cachedDeviceClient);
            }
        }
Пример #3
0
        private static async Task <DeviceClient> SetupDeviceClientAsync(Parameters parameters, CancellationToken cancellationToken)
        {
            DeviceClient deviceClient;

            switch (parameters.DeviceSecurityType.ToLowerInvariant())
            {
            case "dps":
                s_logger.LogDebug($"Initializing via DPS");
                DeviceRegistrationResult dpsRegistrationResult = await ProvisionDeviceAsync(parameters, cancellationToken);

                var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(dpsRegistrationResult.DeviceId, parameters.DeviceSymmetricKey);
                deviceClient = InitializeDeviceClient(dpsRegistrationResult.AssignedHub, authMethod);
                break;

            case "connectionstring":
                s_logger.LogDebug($"Initializing via IoT Hub connection string");
                deviceClient = InitializeDeviceClient(parameters.PrimaryConnectionString);
                break;

            default:
                throw new ArgumentException($"Unrecognized value for device provisioning received: {parameters.DeviceSecurityType}." +
                                            $" It should be either \"dps\" or \"connectionString\" (case-insensitive).");
            }
            return(deviceClient);
        }
Пример #4
0
        private async Task <DeviceClient> CreateConnection(
            DeviceConfiguration deviceConfig,
            CancellationToken cancellationToken)
        {
            const TransportType transportType = TransportType.Amqp_Tcp_Only;

            var authentication = new DeviceAuthenticationWithRegistrySymmetricKey(
                deviceConfig.DeviceId,
                deviceConfig.DeviceKey);

            DeviceClient deviceClient = DeviceClient.Create(
                deviceConfig.HubHostname,
                authentication,
                transportType);

            deviceClient.SetConnectionStatusChangesHandler(MonitorForDisabledConnection);

            await deviceClient.OpenAsync(cancellationToken);

            Log.Information(
                "Connection to hub {host} opened with transport {transportType} for device {device}",
                deviceConfig.HubHostname,
                transportType,
                deviceConfig.DeviceId);

            return(deviceClient);
        }
        public void IotHubConnectionStringBuilder_ParamHostNameAuthMethod_DeviceIdComplex()
        {
            var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(DeviceIdSplChar, SharedAccessKey);
            var csBuilder  = IotHubConnectionStringBuilder.Create(HostName, authMethod);

            csBuilder.DeviceId.Should().Be(DeviceIdSplChar);
        }
Пример #6
0
        private static IAuthenticationMethod GetAuthenticationMethod(DeviceRegistrationResult result, SecurityProvider security)
        {
            IAuthenticationMethod auth;

            if (security is SecurityProviderTpm)
            {
                Console.WriteLine("Creating TPM DeviceClient authentication.");
                auth = new DeviceAuthenticationWithTpm(result.DeviceId, security as SecurityProviderTpm);
            }
            else if (security is SecurityProviderX509)
            {
                Console.WriteLine("Creating X509 DeviceClient authentication.");
                auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, (security as SecurityProviderX509).GetAuthenticationCertificate());
            }
            else if (security is SecurityProviderSymmetricKey)
            {
                Console.WriteLine("Creating Symmetric Key DeviceClient authenication");
                auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (security as SecurityProviderSymmetricKey).GetPrimaryKey());
            }
            else
            {
                throw new NotSupportedException("Unknown authentication type.");
            }
            return(auth);
        }
Пример #7
0
        private Client.IAuthenticationMethod CreateAuthenticationMethodFromSecurityProvider(
            SecurityProvider provisioningSecurity,
            string deviceId)
        {
            _verboseLog.WriteLine($"{nameof(CreateAuthenticationMethodFromSecurityProvider)}({deviceId})");

            if (provisioningSecurity is SecurityProviderTpm)
            {
                var security = (SecurityProviderTpm)provisioningSecurity;
                var auth     = new DeviceAuthenticationWithTpm(deviceId, security);
                return(auth);
            }
            else if (provisioningSecurity is SecurityProviderX509)
            {
                var security          = (SecurityProviderX509)provisioningSecurity;
                X509Certificate2 cert = security.GetAuthenticationCertificate();
                return(new DeviceAuthenticationWithX509Certificate(deviceId, cert));
            }
            else if (provisioningSecurity is SecurityProviderSymmetricKey)
            {
                var security = (SecurityProviderSymmetricKey)provisioningSecurity;
                var auth     = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, security.GetPrimaryKey());
                return(auth);
            }

            throw new NotSupportedException($"Unknown provisioningSecurity type.");
        }
Пример #8
0
        private Client.IAuthenticationMethod CreateAuthenticationMethodFromSecurityProvider(
            SecurityProvider provisioningSecurity,
            string deviceId)
        {
            _verboseLog.WriteLine($"{nameof(CreateAuthenticationMethodFromSecurityProvider)}({deviceId})");

            Client.IAuthenticationMethod auth;
            if (provisioningSecurity is SecurityProviderTpm tpmSecurity)
            {
                auth = new DeviceAuthenticationWithTpm(deviceId, tpmSecurity);
            }
            else if (provisioningSecurity is SecurityProviderX509 x509Security)
            {
                X509Certificate2 cert = x509Security.GetAuthenticationCertificate();
                auth = new DeviceAuthenticationWithX509Certificate(deviceId, cert);
            }
            else if (provisioningSecurity is SecurityProviderSymmetricKey symmetricKeySecurity)
            {
                auth = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, symmetricKeySecurity.GetPrimaryKey());
            }
            else
            {
                throw new NotSupportedException($"Unknown provisioningSecurity type.");
            }

            return auth;
        }
Пример #9
0
        private async Task <bool> Init()
        {
            try
            {
                using (var security = new SecurityProviderSymmetricKey(_deviceID, _primaryKey, null))
                {
                    DeviceRegistrationResult result = await RegisterDeviceAsync(security);

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        _logger.LogInformation("{time} - Failed to register device", DateTimeOffset.Now);

                        return(false);
                    }
                    IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (security as SecurityProviderSymmetricKey).GetPrimaryKey());
                    _deviceClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt);
                }

                await SendDevicePropertiesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"{DateTimeOffset.Now} - Error:{ex.Message}");
                return(false);
            }

            return(true);
        }
        private static DeviceClient NewDeviceClient(string assignedHub)
        {
            try
            {
                ConsoleWriteLine();
                ConsoleWriteLine($"Will create client for device {deviceId}...", ConsoleColor.Green);

                var authenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey(
                    deviceId: deviceId,
                    key: devicePrimaryKey);

                var deviceClient = DeviceClient.Create(
                    hostname: assignedHub,
                    authenticationMethod: authenticationMethod,
                    transportType: TransportType.Mqtt_Tcp_Only);

                ConsoleWriteLine($"Successfully created client for device {deviceId}", ConsoleColor.Green);

                return(deviceClient);
            }
            catch (Exception ex)
            {
                ConsoleWriteLine($"* ERROR * {ex.Message}", ConsoleColor.Red);
            }

            return(null);
        }
        /// <summary>
        /// Generates the connection string.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <param name="devicekey">The devicekey.</param>
        /// <returns></returns>
        protected string GenerateDeviceConnectionString(string deviceId, string devicekey)
        {
            var authenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, devicekey);
            var builder = Microsoft.Azure.Devices.Client.IotHubConnectionStringBuilder.Create(HostName, authenticationMethod);

            return(builder.ToString());
        }
Пример #12
0
        static void Main()
        {
            var deviceId             = ConfigurationManager.AppSettings["deviceId"];
            var authenticationMethod =
                new DeviceAuthenticationWithRegistrySymmetricKey(
                    deviceId,
                    ConfigurationManager.AppSettings["deviceKey"]
                    )
            ;

            var transportType = TransportType.Mqtt;

            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["transportType"]))
            {
                transportType = (TransportType)
                                Enum.Parse(typeof(TransportType),
                                           ConfigurationManager.AppSettings["transportType"], true);
            }

            var client = DeviceClient.Create(
                ConfigurationManager.AppSettings["hostName"],
                authenticationMethod,
                transportType
                );


            var view      = new DeviceView();
            var viewModel = new DeviceViewModel(deviceId, client);

            view.DataContext = viewModel;

            var app = new Application();

            app.Run(view);
        }
Пример #13
0
        // https://github.com/Azure-Samples/azure-iot-samples-csharp/blob/master/provisioning/Samples/device/SymmetricKeySample/Program.cs
        // Azure IoT Central Client

        static async Task Main(string[] args)
        {
            IAuthenticationMethod auth;

            using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey))
                using (var transport = new ProvisioningTransportHandlerHttp())
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, idScope, security, transport);
                    DeviceRegistrationResult result     = await provClient.RegisterAsync();

                    auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (security as SecurityProviderSymmetricKey).GetPrimaryKey());

                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt))
                    {
                        while (true)
                        {
                            if (_temperature.IsAvailable)
                            {
                                try
                                {
                                    Console.WriteLine($"The CPU temperature is {Math.Round(_temperature.Temperature.Celsius, 2)}");
                                    await SendMsgIotHub(iotClient, _temperature.Temperature.Celsius);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("exception msg: " + ex.Message);
                                }
                            }
                            Thread.Sleep(10000); // sleep for 10 seconds
                        }
                    }
                }
        }
        /// <summary>
        /// This method is called when a device registration response direct method call is received from IoTHub.
        /// On succesful registration, it creates a device client and sends all waiting messages.
        /// </summary>
        static async Task <MethodResponse> DeviceRegistered(MethodRequest methodRequest, object userContext)
        {
            var moduleClient = userContext as ModuleClient;

            if (moduleClient == null)
            {
                throw new InvalidOperationException("UserContext doesn't contain " + "expected values");
            }

            var methodResponse = new MethodResponse(200);

            // Process device registration
            var    response     = JsonConvert.DeserializeObject <RegistrationResponse>(methodRequest.DataAsJson);
            string leafDeviceId = response.DeviceId;
            var    leafDevice   = _leafDevices.Get(leafDeviceId);

            if (leafDevice == null)
            {
                methodResponse = new MethodResponse(404); // Not Found
            }
            else if (leafDevice.Status == DeviceInfoStatus.WaitingConfirmation)
            {
                leafDevice.Status = DeviceInfoStatus.Confirmed;
                if ((response.ResultCode == 200) || (response.ResultCode == 201)) // OK, Created
                {
                    Console.WriteLine($"Leaf device '{leafDeviceId}' registered with IoTHub: {response.ResultDescription}");

                    // Create new DeviceClient for the leaf device
                    string signedKey = await SignAsync(leafDeviceId);

                    IAuthenticationMethod authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(leafDeviceId, signedKey);
                    leafDevice.DeviceClient = _useTransparentGateway ? DeviceClient.Create(_iothubHostName, _gatewayHostName, authMethod) : DeviceClient.Create(_iothubHostName, authMethod);
                    leafDevice.DeviceClient.SetConnectionStatusChangesHandler(DeviceConnectionChanged);

                    // Send waiting messages
                    leafDevice.Status = DeviceInfoStatus.Registered;
                    var waitingMessages = leafDevice.GetWaitingList();
                    Console.WriteLine($"Sending {waitingMessages.Count} waiting messages from leaf device '{leafDeviceId}' to IoTHub.");
                    await leafDevice.DeviceClient.SendEventBatchAsync(waitingMessages);

                    leafDevice.ClearWaitingList();
                }
                else if ((response.ResultCode == 401) || (response.ResultCode == 403) || (response.ResultCode == 404)) // Unauthorized, Forbidden, Not Found
                {
                    Console.WriteLine($"Registration of leaf device '{leafDeviceId}' not allowed: {response.ResultDescription}");
                    leafDevice.Status = DeviceInfoStatus.NotRegistered;
                }
                else
                {
                    Console.WriteLine($"ERROR: Unsuccesful registration response (code {response.ResultCode}: {response.ResultDescription}) for leaf device '{leafDeviceId}' received.");
                }
            }
            else
            {
                Console.WriteLine($"ERROR: Registration response (code {response.ResultCode}: {response.ResultDescription}) for leaf device '{leafDeviceId}' with invalid status {leafDevice.Status} received.");
            }

            return(methodResponse);
        }
Пример #15
0
        private async Task InitializeDeviceClient()
        {
            var authentication = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey);

            deviceClient = DeviceClient.Create(hostname, authentication);

            await deviceClient.OpenAsync();
        }
Пример #16
0
        static async Task Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            var configuration = builder.Build();

            var deviceId             = configuration["deviceId"];
            var authenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, configuration["deviceKey"]);
            var transportType        = TransportType.Mqtt;

            if (!string.IsNullOrWhiteSpace(configuration["transportType"]))
            {
                transportType = (TransportType)Enum.Parse(typeof(TransportType), configuration["transportType"], true);
            }
            var client           = DeviceClient.Create(configuration["hostName"], authenticationMethod, transportType);
            var connectionString = configuration["StorageConnectionString"];


            var twin = await client.GetTwinAsync();

            while (true)
            {
                var message = await client.ReceiveAsync();

                if (message == null)
                {
                    continue;
                }

                var bytes = message.GetBytes();
                if (bytes == null)
                {
                    continue;
                }

                var text = Encoding.UTF8.GetString(bytes);
                switch (text)
                {
                case "apridosatore":
                    await apriDosatore(client);

                    break;

                case "scattafoto":
                    await scattaFoto(client);

                    break;

                default:
                    Console.WriteLine("Scrivi bene!");
                    break;
                }
                await client.CompleteAsync(message);
            }
        }
        /// <summary>
        /// Builds the IoT Hub connection string
        /// </summary>
        string GetConnectionString()
        {
            string key = _device.PrimaryAuthKey;
            string deviceID = _device.DeviceID;
            string hostName = _device.HostName;

            var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(deviceID, key);
            return IotHubConnectionStringBuilder.Create(hostName, authMethod).ToString();
        }
        public async Task RunSampleAsync()
        {
            // When registering with a symmetric key using a group enrollment, the provided key will not
            // work for a specific device, rather it must be computed based on two values: the group enrollment
            // key and the desired device Id.
            if (_parameters.EnrollmentType == EnrollmentType.Group)
            {
                _parameters.PrimaryKey = ComputeDerivedSymmetricKey(_parameters.PrimaryKey, _parameters.Id);
            }

            Console.WriteLine($"Initializing the device provisioning client...");

            // For individual enrollments, the first parameter must be the registration Id, where in the enrollment
            // the device Id is already chosen. However, for group enrollments the device Id can be requested by
            // the device, as long as the key has been computed using that value.
            // Also, the secondary could could be included, but was left out for the simplicity of this sample.
            using var security = new SecurityProviderSymmetricKey(
                      _parameters.Id,
                      _parameters.PrimaryKey,
                      null);

            using var transportHandler = GetTransportHandler();

            ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
                _parameters.GlobalDeviceEndpoint,
                _parameters.IdScope,
                security,
                transportHandler);

            Console.WriteLine($"Initialized for registration Id {security.GetRegistrationID()}.");

            Console.WriteLine("Registering with the device provisioning service...");
            DeviceRegistrationResult result = await provClient.RegisterAsync();

            Console.WriteLine($"Registration status: {result.Status}.");
            if (result.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                Console.WriteLine($"Registration status did not assign a hub, so exiting this sample.");
                return;
            }

            Console.WriteLine($"Device {result.DeviceId} registered to {result.AssignedHub}.");

            Console.WriteLine("Creating symmetric key authentication for IoT Hub...");
            IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(
                result.DeviceId,
                security.GetPrimaryKey());

            Console.WriteLine($"Testing the provisioned device with IoT Hub...");
            using DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, _parameters.TransportType);

            Console.WriteLine("Sending a telemetry message...");
            using var message = new Message(Encoding.UTF8.GetBytes("TestMessage"));
            await iotClient.SendEventAsync(message);

            Console.WriteLine("Finished.");
        }
Пример #19
0
        public async Task RunSampleAsync()
        {
            try
            {
                Console.WriteLine($"RegistrationID = {_security.GetRegistrationID()}");
                VerifyRegistrationIdFormat(_security.GetRegistrationID());

                Console.Write("ProvisioningClient RegisterAsync . . . ");
                DeviceRegistrationResult result = await _provClient.RegisterAsync().ConfigureAwait(false);

                Console.WriteLine($"{result.Status}");
                Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                {
                    return;
                }

                Microsoft.Azure.Devices.Client.IAuthenticationMethod auth;
                if (_security is SecurityProviderTpm)
                {
                    Console.WriteLine("Creating TPM DeviceClient authentication.");
                    auth = new DeviceAuthenticationWithTpm(result.DeviceId, _security as SecurityProviderTpm);
                }
                else if (_security is SecurityProviderX509)
                {
                    Console.WriteLine("Creating X509 DeviceClient authentication.");
                    auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, (_security as SecurityProviderX509).GetAuthenticationCertificate());
                }
                else if (_security is SecurityProviderSymmetricKey)
                {
                    Console.WriteLine("Creating Symmetric Key DeviceClient authenication");
                    auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (_security as SecurityProviderSymmetricKey).GetPrimaryKey());
                }
                else
                {
                    throw new NotSupportedException("Unknown authentication type.");
                }

                using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, Microsoft.Azure.Devices.Client.TransportType.Amqp))
                {
                    Console.WriteLine("DeviceClient OpenAsync.");
                    await iotClient.OpenAsync().ConfigureAwait(false);

                    Console.WriteLine("DeviceClient SendEventAsync.");
                    await iotClient.SendEventAsync(new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false);

                    Console.WriteLine("DeviceClient CloseAsync.");
                    await iotClient.CloseAsync().ConfigureAwait(false);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #20
0
        /// <summary>
        /// Builds the IoT Hub connection string
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        private string GetConnectionString()
        {
            string key      = Constants.PrimaryAuthKey;
            string deviceID = Constants.DeviceId;
            string hostName = Constants.HostName;

            var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(deviceID, key);

            return(Microsoft.Azure.Devices.Client.IotHubConnectionStringBuilder.Create(hostName, authMethod).ToString());
        }
Пример #21
0
        private static async Task <string> BuildConnectionStringAsync(RegistryManager registryManager, DeviceItem deviceItem, TraceWriter log)
        {
            var iotHubConnectionString = IotHubConnectionStringBuilder.Create(Environment.GetEnvironmentVariable("IoTHubConnectionString"));
            var device = await registryManager.GetDeviceAsync(deviceItem.Name);

            var deviceKeyInfo          = new DeviceAuthenticationWithRegistrySymmetricKey(deviceItem.Name, device.Authentication.SymmetricKey.PrimaryKey);
            var deviceConnectionString = ClientIotHubConnectionStringBuilder.Create(iotHubConnectionString.HostName, deviceKeyInfo);

            return(deviceConnectionString.ToString());
        }
        /// <summary>
        /// Builds the IoT Hub connection string
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        private string GetConnectionString()
        {
            string key      = _device.PrimaryAuthKey;
            string deviceID = _device.DeviceID;
            string hostName = _device.HostName;

            var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(deviceID, key);

            return(Client.IotHubConnectionStringBuilder.Create(hostName, authMethod).ToString());
        }
Пример #23
0
        static DeviceClient GetDeviceClient()
        {
            // Generate the symmetric key
            var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(_deviceId, _deviceKey);

            // Build the connection string
            var connecitonString = IotHubConnectionStringBuilder.Create(_ioTHubHostName, authMethod).ToString();
            var deviceClient     = DeviceClient.CreateFromConnectionString("HostName=iothubhackathon.azure-devices.net;DeviceId=receiver;SharedAccessKey=/7pZKSWEiSNI/2RYmzqzlEndQQGDB9Zh6QnWTvHvyuY=", TransportType.Http1);

            return(deviceClient);
        }
Пример #24
0
 public async Task ConectarHub()
 {
     if (Device != null)
     {
         var key  = Device.Authentication.SymmetricKey.PrimaryKey;
         var auth = new DeviceAuthenticationWithRegistrySymmetricKey(
             Constantes.DeviceId, key);
         Client = DeviceClient.Create(Constantes.IoTHubURL, auth,
                                      Microsoft.Azure.Devices.Client.TransportType.Mqtt);
     }
 }
Пример #25
0
        private static void SendMessagesToIotHub(FlexAsset myAsset, List <Message> messages)
        {
            Console.Write("Send messages to IoT hub...");

            IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(myAsset.deviceId, myAsset.primaryKey);

            using var client = Microsoft.Azure.Devices.Client.DeviceClient.Create(myAsset.asignedHub, auth, TransportType.Mqtt);
            client.SendEventBatchAsync(messages).GetAwaiter().GetResult();

            Console.WriteLine(" successfully sent!");
        }
Пример #26
0
        public void InitializeDevice()
        {
            if (Status != ProvisioningRegistrationStatusType.Assigned)
            {
                Console.WriteLine("Device is not assigned");
                return;
            }
            var auth = new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, Key);

            _deviceClient = DeviceClient.Create(AssignedHub, auth);
        }
Пример #27
0
        static DeviceClient GetDeviceClient()
        {
            // Generate the symmetric key
            var authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(_deviceId, _deviceKey);

            // Build the connection string
            var connecitonString = IotHubConnectionStringBuilder.Create(_ioTHubHostName, authMethod).ToString();
            var deviceClient     = DeviceClient.CreateFromConnectionString("HostName=iothubhackathon.azure-devices.net;DeviceId=hackathontrap;SharedAccessKey=BaBrZjE2nnpUIQ+QiG9rJVy4zWhdNmaqw9DrckrM05s=", TransportType.Http1);

            return(deviceClient);
        }
Пример #28
0
        static async Task <DeviceClient> DeviceRegistration(string applicationId, string deviceId, int port)
        {
            string deviceKey;

            // See if AzureIoT hub connections string has been configured
            string connectionString = ApplicationConfiguration.ConnectionStringResolve(applicationId, port);

            if (!String.IsNullOrEmpty(connectionString))
            {
                return(DeviceClient.CreateFromConnectionString(connectionString, deviceId));
            }

            // See if Azure DPS has been configured
            using (var hmac = new HMACSHA256(Convert.FromBase64String(ApplicationConfiguration.DpsEnrollmentGroupSymmetricKeyResolve(applicationId, port))))
            {
                deviceKey = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(deviceId)));
            }

            using (var securityProvider = new SecurityProviderSymmetricKey(deviceId, deviceKey, null))
            {
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(ApplicationConfiguration.DpsGlobaDeviceEndpointResolve(),
                                                                                          ApplicationConfiguration.DpsIdScopeResolve(applicationId, port),
                                                                                          securityProvider,
                                                                                          transport);

                    DeviceRegistrationResult result = await provClient.RegisterAsync();

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        throw new ApplicationException($"DevID:{deviceId} Status:{result.Status} RegisterAsync failed");
                    }

                    IAuthenticationMethod authentication = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (securityProvider as SecurityProviderSymmetricKey).GetPrimaryKey());

                    return(DeviceClient.Create(result.AssignedHub,
                                               authentication,
                                               new ITransportSettings[]
                    {
                        new AmqpTransportSettings(TransportType.Amqp_Tcp_Only)
                        {
                            PrefetchCount = 0,
                            AmqpConnectionPoolSettings = new AmqpConnectionPoolSettings()
                            {
                                Pooling = true,
                            }
                        }
                    }
                                               ));
                }
            }
        }
        public void X509CertificateMutipleClientAuthMechanism()
        {
            string hostName = "acme.azure-devices.net";
            var    amqpConnectionPoolSettings = new AmqpConnectionPoolSettings();
            var    transportSetting           = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings);
            var    authMethod1  = new DeviceAuthenticationWithRegistrySymmetricKey("device1", "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            var    deviceClient = DeviceClient.Create(hostName, authMethod1, new ITransportSettings[] { transportSetting });

            var cert          = CertificateHelper.InstallCertificateFromFile(LocalCertFilename, LocalCertPasswordFile);
            var authMethod2   = new DeviceAuthenticationWithX509Certificate("device2", cert);
            var device2Client = DeviceClient.Create(hostName, authMethod2, new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 100) });
        }
Пример #30
0
        public async Task <Microsoft.Azure.Devices.Client.DeviceClient> ProvisionAsync <DeviceClient>(DataStorage storage)
        {
            var connStringContent       = storage.Read("ConnectionString");
            DevicePortalInfoModel model = JsonConvert.DeserializeObject <DevicePortalInfoModel>(connStringContent);
            string scope          = model.Device.ID_Scope;
            string primaryKey     = model.Device.PrimaryKey;
            string secondaryKey   = model.Device.SecondaryKey;
            string registrationId = model.Device.RegistrationId;

            _sendTelemetry = false;

            using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey))
            {
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    _sendTelemetry = false;
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, scope, security, transport);
                    DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        return(null);
                    }
                    Console.WriteLine($"Provisioninged device : {result.DeviceId} at {result.AssignedHub}");
                    var client = Microsoft.Azure.Devices.Client.DeviceClient.Create(result.AssignedHub, model.Auth, TransportType.Amqp);
                    client.SetMethodHandlerAsync("Reprovision", ReprovisionHandler, null).GetAwaiter().GetResult();
                    client.SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdated, null).GetAwaiter().GetResult();

                    //  TODO:Save new connection information
                    var auth    = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, security.GetPrimaryKey());
                    var host    = result.AssignedHub;
                    var builder = IotHubConnectionStringBuilder.Create(host, auth);
                    var device  = new DevicePortalInfoModel
                    {
                        Host   = result.AssignedHub,
                        Auth   = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, security.GetPrimaryKey()),
                        Device = new DeviceModel {
                            ID_Scope       = scope,
                            PrimaryKey     = security.GetPrimaryKey(),
                            SecondaryKey   = security.GetSecondaryKey(),
                            RegistrationId = result.RegistrationId,
                            DeviceId       = result.DeviceId
                        },
                        ConnectionString = builder.ToString()
                    };

                    _storage.Write(DataStorage.DeviceConnectionString, JsonConvert.SerializeObject(device));
                    return(client);
                }
            }
        }
        public void IotHubConnectionStringBuilder_ParamHostNameGatewayAuthMethod_Basic()
        {
            IAuthenticationMethod authMethod = new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, SharedAccessKey);
            var csBuilder = IotHubConnectionStringBuilder.Create(HostName, GatewayHostName, authMethod);

            csBuilder.HostName.Should().Be(HostName);
            csBuilder.DeviceId.Should().Be(DeviceId);
            csBuilder.GatewayHostName.Should().Be(GatewayHostName);
            csBuilder.SharedAccessKey.Should().Be(SharedAccessKey);
            csBuilder.AuthenticationMethod.Should().BeOfType <DeviceAuthenticationWithRegistrySymmetricKey>();

            csBuilder.SharedAccessSignature.Should().BeNull();
        }