Esempio n. 1
0
        // INSERT ProvisionDevice method below here
        private static async Task <DeviceClient> ProvisionDevice(ProvisioningDeviceClient provisioningDeviceClient, SecurityProviderX509Certificate security)
        {
            var result = await provisioningDeviceClient.RegisterAsync().ConfigureAwait(false);

            Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
            if (result.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                throw new Exception($"DeviceRegistrationResult.Status is NOT 'Assigned'");
            }

            var auth = new DeviceAuthenticationWithX509Certificate(
                result.DeviceId,
                security.GetAuthenticationCertificate());

            return(DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp));
        }
Esempio n. 2
0
        private static async Task Main(string[] args)
        {
            Console.WriteLine("DPS auto provisioned device");

            if (args.Length == 0)
            {
                Console.WriteLine("Please pass ID Scope as first command line argument");
                return;
            }

            var idScope = args[0];

            var certificate = LoadCertificate();
            DeviceAuthenticationWithX509Certificate auth;
            string iotHub;

            using (var security = new SecurityProviderX509Certificate(certificate))
            {
                using (var transport = new ProvisioningTransportHandlerMqtt())
                {
                    var provisioningClient = ProvisioningDeviceClient.Create("global.azure-devices-provisioning.net",
                                                                             idScope, security, transport);

                    var provisioningResult = await provisioningClient.RegisterAsync();

                    Console.WriteLine(
                        $"Provisioning done - Assigned Hub: {provisioningResult.AssignedHub} - DeviceID {provisioningResult.DeviceId}");

                    auth = new DeviceAuthenticationWithX509Certificate(provisioningResult.DeviceId,
                                                                       security.GetAuthenticationCertificate());
                    iotHub = provisioningResult.AssignedHub;
                }
            }

            using (var deviceClient = DeviceClient.Create(iotHub, auth, TransportType.Mqtt))
            {
                await deviceClient.OpenAsync();

                await deviceClient.SendEventAsync(
                    new Message(Encoding.UTF8.GetBytes("Auto provisioned device was here")));

                await deviceClient.CloseAsync();

                Console.WriteLine("Sent message");
            }
        }
        static async Task <DeviceClient> CreateForDPS(AuthType authType)
        {
            var dpsScope   = Environment.GetEnvironmentVariable("DPSScope");
            var security   = new SecurityProviderX509Certificate(LoadCertificate());
            var transport  = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly);
            var provClient = ProvisioningDeviceClient.Create(dpsEndpoint, dpsScope, security, transport);

            DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);

            if (result.Status != ProvisioningRegistrationStatusType.Assigned)
            {
                throw new Exception("Device could not be provisioned.");
            }
            var auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, security.GetAuthenticationCertificate());

            return(DeviceClient.Create(result.AssignedHub, auth, transportType));
        }
Esempio n. 4
0
 public IAuthenticationMethod Create()
 {
     return(new DeviceAuthenticationWithX509Certificate(
                _deviceRegistrationProvider.DeviceId,
                _securityProvider.GetAuthenticationCertificate()));
 }
Esempio n. 5
0
        public async Task Provision()
        {
            var certificate = LoadPrivateKey("key.pfx");

            using (var securityProvider = new SecurityProviderX509Certificate(certificate))
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    var client = ProvisioningDeviceClient.Create("global.azure-devices-provisioning.net", this.scopeId, securityProvider, transport);

                    var result = await client.RegisterAsync();

                    Console.WriteLine($"Provisioning result: {result.Status}");

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        throw new InvalidOperationException("Something went wrong while trying to provision.");
                    }

                    this.assignedHub = result.AssignedHub;
                    this.auth        = new DeviceAuthenticationWithX509Certificate(result.DeviceId, securityProvider.GetAuthenticationCertificate());
                }
        }
        static async Task Main()
        {
            var configuration = ReadConfiguration();

            using X509Certificate2 certificate = LoadCertificate(configuration.DeviceName);
            using var security = new SecurityProviderX509Certificate(certificate);
            var registrationResult = await RegisterDeviceAsync(configuration, security);

            var auth = new DeviceAuthenticationWithX509Certificate(registrationResult.DeviceId, security.GetAuthenticationCertificate());

            using DeviceClient iotClient = DeviceClient.Create(registrationResult.AssignedHub, auth, TransportType.Amqp);
            await iotClient.OpenAsync();

            await iotClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("TestMessage")));

            await iotClient.CloseAsync();
        }
Esempio n. 7
0
        internal static async Task <DeviceClient> ProvisionDeviceWithCertAsync(string scopeId, string X509LocatorString, string modelId, ILogger log)
        {
            using (var transport = new ProvisioningTransportHandlerMqtt())
            {
                var cert = X509Loader.GetCertFromConnectionString(X509LocatorString, log);
                using (var security = new SecurityProviderX509Certificate(cert))
                {
                    DeviceRegistrationResult provResult;
                    var provClient = ProvisioningDeviceClient.Create("global.azure-devices-provisioning.net", scopeId, security, transport);
                    if (!String.IsNullOrEmpty(modelId))
                    {
                        provResult = await provClient.RegisterWithModelAsync(modelId, log);
                    }
                    else
                    {
                        provResult = await provClient.RegisterAsync().ConfigureAwait(false);
                    }

                    log.LogInformation($"Provioning Result. Status [{provResult.Status}] SubStatus [{provResult.Substatus}]");

                    if (provResult.Status == ProvisioningRegistrationStatusType.Assigned)
                    {
                        log.LogWarning($"Device {provResult.DeviceId} in Hub {provResult.AssignedHub}");
                        log.LogInformation($"LastRefresh {provResult.LastUpdatedDateTimeUtc} RegistrationId {provResult.RegistrationId}");
                        Rido.DeviceClientFactory.Instance.HostName = provResult.AssignedHub;
                        var    csBuilder        = IotHubConnectionStringBuilder.Create(provResult.AssignedHub, new DeviceAuthenticationWithX509Certificate(provResult.DeviceId, security.GetAuthenticationCertificate()));
                        string connectionString = csBuilder.ToString();

                        DeviceClient client;
                        if (string.IsNullOrEmpty(modelId))
                        {
                            client = DeviceClient.Create(provResult.AssignedHub, new DeviceAuthenticationWithX509Certificate(provResult.DeviceId, security.GetAuthenticationCertificate()), TransportType.Mqtt);
                        }
                        else
                        {
                            client = DeviceClient.Create(provResult.AssignedHub, new DeviceAuthenticationWithX509Certificate(provResult.DeviceId, security.GetAuthenticationCertificate()), TransportType.Mqtt, new ClientOptions {
                                ModelId = modelId
                            });
                        }
                        return(client);
                    }
                    else
                    {
                        string errorMessage = $"Device not provisioned. Message: {provResult.ErrorMessage}";
                        log.LogError(errorMessage);
                        throw new IotHubException(errorMessage);
                    }
                }
            }
        }
Esempio n. 8
0
        public static async Task Main(string[] args)
        {
            var configuration = ReadConfiguration();

            Console.WriteLine("Bootstrapping device...");

            using X509Certificate2 certificate = LoadCertificate(configuration.DeviceName);
            using var security = new SecurityProviderX509Certificate(certificate);
            var registrationResult = await RegisterDeviceAsync(configuration, security);

            var auth = new DeviceAuthenticationWithX509Certificate(registrationResult.DeviceId, security.GetAuthenticationCertificate());

            using DeviceClient deviceClient = DeviceClient.Create(registrationResult.AssignedHub, auth, TransportType.Mqtt);

            await deviceClient.SetMethodHandlerAsync(nameof(DestinationCall), DestinationCall, null);

            await SendDeviceStateMessages(configuration.DeviceName, deviceClient);

            //ReceiveC2dAsync(deviceClient);
            Console.ReadKey();
        }
Esempio n. 9
0
        /// <summary>
        /// In order to provision the device and establish secure connection to IoT Edge
        /// certificates need to be installed in the Certificate Store(root, intermediate, leaf).
        /// Next phase is to use DPS to get necessary informations about IoT Hub.
        /// Last phase is to connect to the Edge device and send it MESSAGE_COUNT
        /// number of telemetry data messages.
        ///
        /// Note: Either set the MESSAGE_COUNT environment variable with the number of
        /// messages to be sent to the IoT Edge runtime or set it in the launchSettings.json.
        /// </summary>
        static void Main()
        {
            try
            {
                string messageCountEnv = Environment.GetEnvironmentVariable("MESSAGE_COUNT");
                if (!string.IsNullOrWhiteSpace(messageCountEnv))
                {
                    MESSAGE_COUNT = Int32.Parse(messageCountEnv, NumberStyles.None, new CultureInfo("en-US"));
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Invalid number of messages in env variable DEVICE_MESSAGE_COUNT. MESSAGE_COUNT set to {0}\n", MESSAGE_COUNT);
            }

            Console.WriteLine("Creating device client from certificates\n");

            var rootCertificatePath         = Environment.GetEnvironmentVariable("CA_CERTIFICATE_PATH");
            var intermediateCertificatePath = Environment.GetEnvironmentVariable("CA_INTERMEDIATE_CERTIFICATE_PATH");
            var leafCertificatePath         = Environment.GetEnvironmentVariable("CA_LEAF_CERTIFICATE_PATH");
            var leafCertificatePassword     = Environment.GetEnvironmentVariable("CA_LEAF_CERTIFICATE_PASSWORD");
            var hostName = Environment.GetEnvironmentVariable("HOST_NAME");
            var dpsScope = Environment.GetEnvironmentVariable("DPS_IDSCOPE");

            // Add Root Certificate
            InstallCACert(certificatePath: rootCertificatePath);
            // Add Intermediate Certificate
            InstallCACert(certificatePath: intermediateCertificatePath);
            // Add Leaf Device Certificate
            InstallCACert(certificatePath: leafCertificatePath,
                          certificatePassword: leafCertificatePassword);

            var certificate = new X509Certificate2(leafCertificatePath, leafCertificatePassword);

            using (var security = new SecurityProviderX509Certificate(certificate))
                using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, dpsScope, security, transport);

                    var deviceAuthentication = GetDeviceRegistrationResultAsync(provClient, security).Result;

                    var auth = new DeviceAuthenticationWithX509Certificate(deviceAuthentication.DeviceId, security.GetAuthenticationCertificate());

                    var deviceClient = DeviceClient.Create(hostname: deviceAuthentication.AssignedHub,
                                                           authenticationMethod: auth,
                                                           transportType: TransportType.Mqtt);


                    if (deviceClient == null)
                    {
                        Console.WriteLine("Failed to create DeviceClient!");
                    }
                    else
                    {
                        SendEvents(deviceClient, MESSAGE_COUNT).Wait();
                    }
                }
            Console.WriteLine("Exiting!\n");
            Console.ReadLine();
        }