public static int Main(string[] args) { // foreach (DictionaryEntry de in Environment.GetEnvironmentVariables()) // Console.WriteLine(" {0} = {1}", de.Key, de.Value); if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"))) { // Create a new DPSClient to provision the device DPSClient dpsClient = new DPSClient(s_deviceId); // Start provisioning, and receive IoT Hub Device Client IoTHubDeviceClient iotHubClient = dpsClient.ProvisionDeviceAsync().GetAwaiter().GetResult(); if (iotHubClient != null) { iotHubClient.Initialize().Wait(); // Run the IoT Hub Device Client iotHubClient.Run().GetAwaiter().GetResult(); } } else { // Device Authentication is done by IoT Edge Runtime so we do not need to process device provisioning for IoT Edge Module // IoT Edge Module IoTEdgeModuleClient iotEdgeModuleClient = new IoTEdgeModuleClient(); iotEdgeModuleClient.Initialize().Wait(); iotEdgeModuleClient.Run().GetAwaiter().GetResult(); } return(0); }
public async Task <IoTHubDeviceClient> ProvisionDeviceAsync() { string connectionKey; IoTHubDeviceClient iotHubClient = null; Console.WriteLine("Provisioning..."); if (!String.IsNullOrEmpty(_deviceId) && !String.IsNullOrEmpty(s_sasKey) && !String.IsNullOrEmpty(s_idScope)) { connectionKey = GenerateSymmetricKey(); Console.WriteLine($"Connection Key : {connectionKey}"); using (var securityProvider = new SecurityProviderSymmetricKey(_deviceId, connectionKey, null)) using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly)) { _provClient = ProvisioningDeviceClient.Create(s_global_endpoint, s_idScope, securityProvider, transport); // Sanity check Console.WriteLine($"Device ID : {securityProvider.GetRegistrationID()}"); DeviceRegistrationResult result = await _provClient.RegisterAsync().ConfigureAwait(false); if (result.Status == ProvisioningRegistrationStatusType.Assigned) { Console.WriteLine($"Provisioned : {result.Status}"); Console.WriteLine($" Device ID : {result.DeviceId}"); Console.WriteLine($" IoT Hub : {result.AssignedHub}"); IAuthenticationMethod authenticationMethod = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, securityProvider.GetPrimaryKey()); iotHubClient = new IoTHubDeviceClient(result.AssignedHub, authenticationMethod); } else { Console.WriteLine($"Err : Provisioning Failed {result.Status}"); } } } else { Console.WriteLine("Please set following Environment Variables"); Console.WriteLine("DPS_IDSCOPE : ID Scope"); Console.WriteLine("SAS_KEY : SAS Key"); } return(iotHubClient); }