public async Task <IEventTransmitter> CreateTransmitter(string segmentId, CameraType cameraId) { var iotHubOwnerConnectionString = _configurationReader.GetConfigValue <string>("IOTHUB_OWNER_CONNECTIONSTRING", true); try { var policy = Policy .Handle <TimeoutException>() .Or <DeviceMessageLockLostException>() .Or <IotHubCommunicationException>() .Or <IotHubThrottledException>() .Or <ServerBusyException>() .WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (exception, span, retryCount, context) => { _logger.Warn(exception, $"Retry {retryCount}/{5} sending to IoT Hub, because of exception {exception}"); }); // Retry maximum 5 times with exponential backoff for the above exceptions return(await policy.ExecuteAsync(async() => { var iotHubServiceClient = RegistryManager.CreateFromConnectionString(iotHubOwnerConnectionString); string deviceId = $"{segmentId}-{cameraId}"; var camDevice = await iotHubServiceClient.GetDeviceAsync(deviceId) ?? await iotHubServiceClient.AddDeviceAsync(new Device(deviceId)); var deviceConnectionString = $"HostName={GetIoTHubUri(iotHubOwnerConnectionString)};DeviceId={deviceId};SharedAccessKey={camDevice.Authentication.SymmetricKey.PrimaryKey}"; if (cameraId == CameraType.Camera1) { ConfigurationCache.CacheValue("deviceConnectionString", deviceConnectionString); } return new IoTHubTransmitter(deviceConnectionString); })); } catch (Exception e) { _logger.Error(e, $"An error occurred when trying read device on IoT Hub: {e.Message}"); throw; } }