public static async Task <DeviceClient> CreateClientFromCert(string hostName, string deviceId, string x509, ILogger logger, string modelId = "") { DeviceClient client; if (String.IsNullOrWhiteSpace(modelId)) { client = DeviceClient.Create(hostName, new DeviceAuthenticationWithX509Certificate( deviceId, X509Loader.GetCertFromConnectionString(x509, logger)), TransportType.Mqtt); } else { client = DeviceClient.Create(hostName, new DeviceAuthenticationWithX509Certificate( deviceId, X509Loader.GetCertFromConnectionString(x509, logger)), TransportType.Mqtt, new ClientOptions { ModelId = modelId }); } logger.LogWarning($"Device {deviceId} connected to {hostName}"); return(await Task.FromResult(client)); }
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); } } } }