public async Task <TrafficSegmentConfiguration> GetConfiguration() { var storageAccountConnection = _configurationReader.GetConfigValue <string>("STORAGE_CONNECTION_STRING", true); var segmentId = _configurationReader.GetConfigValue <string>("SEGMENT_ID", true); var storageAccount = CloudStorageAccount.Parse(storageAccountConnection); var blobClient = storageAccount.CreateCloudBlobClient(); var configBlob = blobClient.GetContainerReference("traffic-config").GetBlockBlobReference("segment-configs.json"); var configText = await configBlob.DownloadTextAsync(); var segmentConfigs = JsonConvert.DeserializeObject <List <TrafficSegmentConfiguration> >(configText); return(segmentConfigs.FirstOrDefault(c => c.SegmentId.Equals(segmentId, StringComparison.InvariantCultureIgnoreCase))); }
public Task <TrafficSegmentConfiguration> GetConfiguration() { return(Task.FromResult(new TrafficSegmentConfiguration { SegmentId = _configurationReader.GetConfigValue <string>("SEGMENT_ID", true), NumberOfLanes = _configurationReader.GetConfigValue("SEGMENT_LANE_COUNT", false, 3), AverageCarsPerMinute = _configurationReader.GetConfigValue("SEGMENT_AVG_CARS_PER_MINUTE", false, 60), SpeedLimit = _configurationReader.GetConfigValue("SEGMENT_SPEED_LIMIT", false, 120), RushHours = GetRushHours(), CameraDistance = _configurationReader.GetConfigValue("SEGMENT_CAMERA_DISTANCE", false, 2000), SpeedingPercentage = _configurationReader.GetConfigValue("SEGMENT_SPEEDING_PERCENTAGE", false, 2), MinSpeed = _configurationReader.GetConfigValue("SEGMENT_MIN_SPEED", false, 10), MaxSpeed = _configurationReader.GetConfigValue("SEGMENT_MAX_SPEED", false, 180) })); }
public async Task <IEventTransmitter> CreateTransmitter(string segmentId, CameraType cameraId) { try { return(new IoTEdgeModuleTransmitter(_configurationReader.GetConfigValue("EDGE_MODULE_OUTPUT", false, cameraId.ToString()))); } catch (Exception e) { _logger.Error(e, $"An error occurred when trying to create iot edge transmitter: {e.Message}"); throw; } }
public Task <IEventTransmitter> CreateTransmitter(string segmentId, CameraType cameraId) { var configuredColor = _configurationReader.GetConfigValue <string>($"CONSOLE_{cameraId.ToString().ToUpper().Replace("-", "")}_COLOR", false); if (!Enum.TryParse(configuredColor, true, out ConsoleColor consoleColor)) { consoleColor = cameraId == CameraType.Camera1 ? ConsoleColor.Green : ConsoleColor.Red; } return(Task.FromResult <IEventTransmitter>(new ConsoleTransmitter { ConsoleColor = consoleColor })); }
public async Task Run(CancellationToken cancellationToken) { SimulatedClock.Init(_simulationSettings.TimeSimulationAccelerator); var segmentId = _configurationReader.GetConfigValue <string>("SEGMENT_ID", true); var startCameraEventTransmitter = await _transmitterConfigurator.CreateTransmitter(segmentId, CameraType.Camera1); var endCameraEventTransmitter = await _transmitterConfigurator.CreateTransmitter(segmentId, CameraType.Camera2); var segmentConfiguration = await _configurator.GetConfiguration(); if (segmentConfiguration == null) { _logger.Error($"The segment configuration was not found and resulted to null"); return; } if (string.IsNullOrEmpty(segmentConfiguration.SegmentId)) { segmentConfiguration.SegmentId = segmentId; } var segmentSituation = new TrafficSegmentSituation(_configurator, segmentConfiguration); var random = new Random(); // Initialize transmitters try { while (!cancellationToken.IsCancellationRequested) { segmentSituation.Resimulate(random); var releaseInterval = TimeSpan.FromMilliseconds(Convert.ToInt32(60000 / segmentSituation.AverageCarsPerMinute)); // replace with function var currentMinute = SimulatedClock.Time.Minute; while (SimulatedClock.Time.Minute == currentMinute) { cancellationToken.ThrowIfCancellationRequested(); Task.Factory.StartNew(() => MakeOneCarDrive(random, segmentConfiguration, segmentSituation, startCameraEventTransmitter, endCameraEventTransmitter, cancellationToken), cancellationToken); await Task.Delay(releaseInterval, cancellationToken); } } } catch (TaskCanceledException) { } catch (Exception ex) { _logger.Error(ex, "Error happened in the simulator: " + ex.ToString()); } }
public async Task <TrafficSegmentConfiguration> GetConfiguration() { _deviceConnectionString = ConfigurationCache.GetValue("deviceConnectionString"); _deviceClient = DeviceClient.CreateFromConnectionString(_deviceConnectionString); await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(TwinPropertiesChanged, null); var iotHubOwnerConnectionString = _configurationReader.GetConfigValue <string>("IOTHUB_OWNER_CONNECTIONSTRING", true); try { var twin = await _deviceClient.GetTwinAsync(); return(GetConfigurationFromTwin(twin.Properties.Desired)); } catch (Exception e) { _logger.Error(e, $"An error occurred when trying read device on IoT Hub: {e.Message}"); throw; } }
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; } }