public async Task <ActionResult> VehicleEntry(VehicleRegistered msg, [FromServices] DaprClient daprClient)
        {
            // get vehicle details
            var apiKeySecret = await daprClient.GetSecretAsync("local-secret-store", "rdw-api-key");

            var apiKey      = apiKeySecret["rdw-api-key"];
            var vehicleInfo = await daprClient.InvokeMethodAsync <VehicleInfo>(
                "governmentservice",
                $"rdw/{apiKey}/vehicle/{msg.LicenseNumber}",
                new HttpInvocationOptions { Method = HttpMethod.Get });

            // log entry
            _logger.LogInformation($"ENTRY detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")}: " +
                                   $"{vehicleInfo.Brand} {vehicleInfo.Model} with license-number {msg.LicenseNumber}.");

            // store vehicle state
            var vehicleState = new VehicleState
            {
                LicenseNumber  = msg.LicenseNumber,
                Brand          = vehicleInfo.Brand,
                Model          = vehicleInfo.Model,
                EntryTimestamp = msg.Timestamp
            };

            await daprClient.SaveStateAsync <VehicleState>(DAPR_STORE_NAME, msg.LicenseNumber, vehicleState);

            return(Ok());
        }
        public async Task <IActionResult> RegisterAsync([FromBody] RegisterVehicle command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // check invariants
                    if (!Regex.IsMatch(command.LicenseNumber, NUMBER_PATTERN, RegexOptions.IgnoreCase))
                    {
                        return(BadRequest($"The specified license-number '{command.LicenseNumber}' was not in the correct format."));
                    }

                    // insert vehicle
                    Vehicle vehicle = command.MapToVehicle();
                    _dbContext.Vehicles.Add(vehicle);
                    await _dbContext.SaveChangesAsync();

                    // send event
                    var e = VehicleRegistered.FromCommand(command);
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

                    //return result
                    return(CreatedAtRoute("GetByLicenseNumber", new { licenseNumber = vehicle.LicenseNumber }, vehicle));
                }
                return(BadRequest());
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Exemplo n.º 3
0
        public void SendVehicleExit(VehicleRegistered vehicleRegistered)
        {
            var eventJson = JsonSerializer.Serialize(vehicleRegistered);
            var message   = JsonContent.Create <VehicleRegistered>(vehicleRegistered);

            _httpClient.PostAsync("http://localhost:5000/exitcam", message).Wait();
        }
        public async Task <ActionResult> VehicleEntry(VehicleRegistered msg, [FromServices] DaprClient daprClient)
        {
            // get vehicle details
            var vehicleInfo = await daprClient.InvokeMethodAsync <VehicleInfo>(
                "governmentservice",
                $"rdw/vehicle/{msg.LicenseNumber}",
                new HttpInvocationOptions { Method = HttpMethod.Get });

            // log entry
            _logger.LogInformation($"ENTRY detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")}: " +
                                   $"{vehicleInfo.Brand} {vehicleInfo.Model} with license-number {msg.LicenseNumber}.");

            // store vehicle state
            var vehicleState = new VehicleState
            {
                LicenseNumber  = msg.LicenseNumber,
                Brand          = vehicleInfo.Brand,
                Model          = vehicleInfo.Model,
                EntryTimestamp = msg.Timestamp
            };

            _repo.StoreVehicleState(vehicleState);

            return(Ok());
        }
Exemplo n.º 5
0
        public async Task RegisterEntry(VehicleRegistered msg)
        {
            try
            {
                Logger.LogInformation($"ENTRY detected in lane {msg.Lane} at " +
                                      $"{msg.Timestamp.ToString("hh:mm:ss")} " +
                                      $"of vehicle with license-number {msg.LicenseNumber}.");

                // store vehicle state
                var vehicleState = new VehicleState
                {
                    LicenseNumber  = msg.LicenseNumber,
                    EntryTimestamp = msg.Timestamp
                };
                await this.StateManager.SetStateAsync("VehicleState", vehicleState);

                // register a timer for cars that enter but don't exit within 20 seconds
                // (they might have broken down and need road assistence)
                //await RegisterTimerAsync("VehicleLost", "VehicleLost", null, TimeSpan.FromSeconds(20), TimeSpan.FromMilliseconds(20));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error in RegisterEntry");
            }
        }
        public void SendVehicleExit(VehicleRegistered vehicleRegistered)
        {
            var eventJson = JsonSerializer.Serialize(vehicleRegistered);
            var message   = new MqttApplicationMessage("trafficcontrol/exitcam", Encoding.UTF8.GetBytes(eventJson));

            _client.PublishAsync(message, MqttQualityOfService.AtMostOnce).Wait();
        }
        public async Task <ActionResult> VehicleEntry(VehicleRegistered msg, [FromServices] IHttpClientFactory httpClientFactory)
        {
            // get vehicle details
            var httpClient = httpClientFactory.CreateClient();
            var response   = await httpClient.GetAsync($"http://localhost:6000/rdw/vehicle/{msg.LicenseNumber}");

            using var responseStream = await response.Content.ReadAsStreamAsync();

            var vehicleInfo = await JsonSerializer.DeserializeAsync <VehicleInfo>(responseStream, _jsonSerializerOptions);

            // log entry
            _logger.LogInformation($"ENTRY detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")}: " +
                                   $"{vehicleInfo.Brand} {vehicleInfo.Model} with license-number {msg.LicenseNumber}.");

            // store vehicle state
            var vehicleState = new VehicleState
            {
                LicenseNumber  = msg.LicenseNumber,
                Brand          = vehicleInfo.Brand,
                Model          = vehicleInfo.Model,
                EntryTimestamp = msg.Timestamp
            };

            _repo.StoreVehicleState(vehicleState);

            return(Ok());
        }
Exemplo n.º 8
0
        public async Task <ActionResult> VehicleEntry(
            VehicleRegistered msg,
            [FromServices] DaprClient daprClient)
        {
            try
            {
                // use service-invocation to get vehicle info
                var vehicleInfo = await _governmentService.GetVehicleInfo(msg.LicenseNumber);

                // log entry
                _logger.LogInformation($"ENTRY detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")}: " +
                                       $"{vehicleInfo.Brand} {vehicleInfo.Model} with license-number {msg.LicenseNumber}.");

                // store vehicle state
                var vehicleState = new VehicleState
                {
                    LicenseNumber  = msg.LicenseNumber,
                    Brand          = vehicleInfo.Brand,
                    Model          = vehicleInfo.Model,
                    EntryTimestamp = msg.Timestamp
                };
                await daprClient.SaveStateAsync <VehicleState>(DAPR_STORE_NAME, msg.LicenseNumber, vehicleState);

                return(Ok());
            }
            catch
            {
                return(Ok(new { status = "RETRY" }));
            }
        }
Exemplo n.º 9
0
        public async Task <IActionResult> RegisterAsync([FromBody] RegisterVehicle command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // insert vehicle
                    Vehicle vehicle = command.MapToVehicle();
                    _dbContext.Vehicles.Add(vehicle);
                    await _dbContext.SaveChangesAsync();

                    // send event
                    var e = VehicleRegistered.FromCommand(command);
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

                    //return result
                    return(CreatedAtRoute("GetByLicenseNumber", new { licenseNumber = vehicle.LicenseNumber }, vehicle));
                }
                return(BadRequest());
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
        public async Task <ActionResult> VehicleExit(VehicleRegistered msg, [FromServices] DaprClient daprClient)
        {
            try
            {
                // get vehicle state
                var vehicleState = await _vehicleStateRepository.GetVehicleStateAsync(msg.LicenseNumber);

                if (vehicleState == null)
                {
                    return(NotFound());
                }

                // log exit
                _logger.LogInformation($"EXIT detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")} " +
                                       $"of vehicle with license-number {msg.LicenseNumber}.");

                // update state
                vehicleState.ExitTimestamp = msg.Timestamp;
                await _vehicleStateRepository.SaveVehicleStateAsync(vehicleState);

                // handle possible speeding violation
                int violation = _speedingViolationCalculator.DetermineSpeedingViolationInKmh(
                    vehicleState.EntryTimestamp, vehicleState.ExitTimestamp);
                if (violation > 0)
                {
                    _logger.LogInformation($"Speeding violation detected ({violation} KMh) of vehicle" +
                                           $"with license-number {vehicleState.LicenseNumber}.");

                    var speedingViolation = new SpeedingViolation
                    {
                        VehicleId      = msg.LicenseNumber,
                        RoadId         = _roadId,
                        ViolationInKmh = violation,
                        Timestamp      = msg.Timestamp
                    };

                    // In last half of Assignment 3, update pub/sub to use Dapr ASP.NET Core client
                    //   argument #1: Name of pub/sub component
                    //   argument #2: Name of topic to which to publish
                    //   argument #3: The message payload
                    // publish speedingviolation
                    await daprClient.PublishEventAsync("pubsub", "collectfine", speedingViolation);

                    // pub/sub code from first-half of Assignment 3
                    // var message = JsonContent.Create<SpeedingViolation>(speedingViolation);
                    // // Replace the hardcoded API code with a call to the Dapr pub/sub side car
                    // await _httpClient.PostAsync("http://localhost:3600/v1.0/publish/pubsub/collectfine", message);
                    // //await _httpClient.PostAsync("http://localhost:6001/collectfine", message);
                }

                return(Ok());
            }
            catch
            {
                return(StatusCode(500));
            }
        }
Exemplo n.º 11
0
 public async Task SendVehicleExitAsync(VehicleRegistered vehicleRegistered)
 {
     var eventJson = JsonSerializer.Serialize(vehicleRegistered);
     var message   = new MqttApplicationMessageBuilder()
                     .WithTopic("trafficcontrol/exitcam")
                     .WithPayload(Encoding.UTF8.GetBytes(eventJson))
                     .WithAtMostOnceQoS()
                     .Build();
     await _client.PublishAsync(message, CancellationToken.None);
 }
Exemplo n.º 12
0
        public void Start(int camNumber)
        {
            Console.WriteLine($"Start camera {camNumber} simulation.");

            // initialize state
            _rnd = new Random();
            var daprClient = new DaprClientBuilder()
                             .UseEndpoint("http://localhost:50003")
                             .Build();

            while (true)
            {
                try
                {
                    // simulate entry
                    TimeSpan entryDelay = TimeSpan.FromMilliseconds(_rnd.Next(_minEntryDelayInMS, _maxEntryDelayInMS) + _rnd.NextDouble());
                    Task.Delay(entryDelay).Wait();

                    Task.Run(() =>
                    {
                        // simulate entry
                        DateTime entryTimestamp = DateTime.Now;
                        var @event = new VehicleRegistered
                        {
                            Lane          = _rnd.Next(1, 4),
                            LicenseNumber = GenerateRandomLicenseNumber(),
                            Timestamp     = entryTimestamp
                        };

                        daprClient.PublishEventAsync("pubsub", "trafficcontrol.entrycam", @event).Wait();

                        Console.WriteLine($"Simulated ENTRY of vehicle with license-number {@event.LicenseNumber} in lane {@event.Lane}");

                        // simulate exit
                        TimeSpan exitDelay = TimeSpan.FromSeconds(_rnd.Next(_minExitDelayInS, _maxExitDelayInS) + _rnd.NextDouble());
                        Task.Delay(exitDelay).Wait();
                        @event.Timestamp = DateTime.Now;
                        @event.Lane      = _rnd.Next(1, 4);

                        daprClient.PublishEventAsync("pubsub", "trafficcontrol.exitcam", @event).Wait();

                        Console.WriteLine($"Simulated EXIT of vehicle with license-number {@event.LicenseNumber} in lane {@event.Lane}");
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
        public void Start(int camNumber)
        {
            Console.WriteLine($"Start camera {camNumber} simulation.");

            // initialize state
            _rnd = new Random();
            var httpClient = new HttpClient();

            while (true)
            {
                try
                {
                    // simulate entry
                    TimeSpan entryDelay = TimeSpan.FromMilliseconds(_rnd.Next(_minEntryDelayInMS, _maxEntryDelayInMS) + _rnd.NextDouble());
                    Task.Delay(entryDelay).Wait();

                    Task.Run(() =>
                    {
                        // simulate entry
                        DateTime entryTimestamp = DateTime.Now;
                        var @event = new VehicleRegistered
                        {
                            Lane          = _rnd.Next(1, 4),
                            LicenseNumber = GenerateRandomLicenseNumber(),
                            Timestamp     = entryTimestamp
                        };

                        var @eventJson = new StringContent(JsonSerializer.Serialize(@event, _jsonSerializerOptions), Encoding.UTF8, "application/json");
                        httpClient.PostAsync("http://localhost:5000/trafficcontrol/entrycam", @eventJson).Wait();

                        Console.WriteLine($"Simulated ENTRY of vehicle with license-number {@event.LicenseNumber} in lane {@event.Lane}");

                        // simulate exit
                        TimeSpan exitDelay = TimeSpan.FromSeconds(_rnd.Next(_minExitDelayInS, _maxExitDelayInS) + _rnd.NextDouble());
                        Task.Delay(exitDelay).Wait();
                        @event.Timestamp = DateTime.Now;
                        @event.Lane      = _rnd.Next(1, 4);

                        @eventJson = new StringContent(JsonSerializer.Serialize(@event, _jsonSerializerOptions), Encoding.UTF8, "application/json");
                        httpClient.PostAsync("http://localhost:5000/trafficcontrol/exitcam", @eventJson).Wait();

                        Console.WriteLine($"Simulated EXIT of vehicle with license-number {@event.LicenseNumber} in lane {@event.Lane}");
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    public async Task <ActionResult> VehicleExitAsync(VehicleRegistered msg, [FromServices] DaprClient daprClient)
    {
        try
        {
            // get vehicle state
            var state = await _vehicleStateRepository.GetVehicleStateAsync(msg.LicenseNumber);

            if (state == default(VehicleState))
            {
                return(NotFound());
            }

            // log exit
            _logger.LogInformation($"EXIT detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")} " +
                                   $"of vehicle with license-number {msg.LicenseNumber}.");

            // update state
            var exitState = state.Value with {
                ExitTimestamp = msg.Timestamp
            };
            await _vehicleStateRepository.SaveVehicleStateAsync(exitState);

            // handle possible speeding violation
            int violation = _speedingViolationCalculator.DetermineSpeedingViolationInKmh(exitState.EntryTimestamp, exitState.ExitTimestamp.Value);
            if (violation > 0)
            {
                _logger.LogInformation($"Speeding violation detected ({violation} KMh) of vehicle" +
                                       $"with license-number {state.Value.LicenseNumber}.");

                var speedingViolation = new SpeedingViolation
                {
                    VehicleId      = msg.LicenseNumber,
                    RoadId         = _roadId,
                    ViolationInKmh = violation,
                    Timestamp      = msg.Timestamp
                };

                // publish speedingviolation (Dapr publish / subscribe)
                await daprClient.PublishEventAsync("pubsub", "speedingviolations", speedingViolation);
            }

            return(Ok());
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error occurred while processing EXIT");
            return(StatusCode(500));
        }
    }
    public async Task <ActionResult> VehicleExitAsync(VehicleRegistered msg)
    {
        try
        {
            var actorId = new ActorId(msg.LicenseNumber);
            var proxy   = ActorProxy.Create <IVehicleActor>(actorId, nameof(VehicleActor));
            await proxy.RegisterExitAsync(msg);

            return(Ok());
        }
        catch
        {
            return(StatusCode(500));
        }
    }
Exemplo n.º 16
0
        public async Task <ActionResult> VehicleExit(VehicleRegistered msg)
        {
            try
            {
                var actorId = new ActorId(msg.LicenseNumber);
                var proxy   = ActorProxy.Create(actorId, "VehicleActor");
                await proxy.InvokeMethodAsync("RegisterExit", msg);

                return(Ok());
            }
            catch
            {
                return(StatusCode(500));
            }
        }
Exemplo n.º 17
0
        public async Task <ActionResult> VehicleExit(VehicleRegistered msg)
        {
            try
            {
                // get vehicle state
                var vehicleState = await _vehicleStateRepository.GetVehicleStateAsync(msg.LicenseNumber);

                if (vehicleState == null)
                {
                    return(NotFound());
                }

                // log exit
                _logger.LogInformation($"EXIT detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")} " +
                                       $"of vehicle with license-number {msg.LicenseNumber}.");

                // update state
                vehicleState.ExitTimestamp = msg.Timestamp;
                await _vehicleStateRepository.SaveVehicleStateAsync(vehicleState);

                // handle possible speeding violation
                int violation = _speedingViolationCalculator.DetermineSpeedingViolationInKmh(
                    vehicleState.EntryTimestamp, vehicleState.ExitTimestamp);
                if (violation > 0)
                {
                    _logger.LogInformation($"Speeding violation detected ({violation} KMh) of vehicle" +
                                           $"with license-number {vehicleState.LicenseNumber}.");

                    var speedingViolation = new SpeedingViolation
                    {
                        VehicleId      = msg.LicenseNumber,
                        RoadId         = _roadId,
                        ViolationInKmh = violation,
                        Timestamp      = msg.Timestamp
                    };

                    // publish speedingviolation
                    var message = JsonContent.Create <SpeedingViolation>(speedingViolation);
                    await _httpClient.PostAsync("http://localhost:5001/collectfine", message);
                }

                return(Ok());
            }
            catch
            {
                return(StatusCode(500));
            }
        }
Exemplo n.º 18
0
        public async Task <ActionResult> VehicleExit(
            VehicleRegistered msg,
            //[FromState(DAPR_STORE_NAME)]StateEntry<VehicleInfo> state,
            [FromServices] DaprClient daprClient)
        {
            try
            {
                // get vehicle state
                var state = await daprClient.GetStateEntryAsync <VehicleState>(DAPR_STORE_NAME, msg.LicenseNumber);

                if (state.Value == null)
                {
                    return(NotFound());
                }

                // log exit
                _logger.LogInformation($"EXIT detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")}: " +
                                       $"{state.Value.Brand} {state.Value.Model} with license-number {msg.LicenseNumber}.");

                // update state
                state.Value.ExitTimestamp = msg.Timestamp;
                await state.SaveAsync();

                // handle possible speeding violation
                int violation = _speedingViolationCalculator.DetermineSpeedingViolationInKmh(state.Value.EntryTimestamp, state.Value.ExitTimestamp);
                if (violation > 0)
                {
                    _logger.LogInformation($"Speeding violation detected ({violation} KMh) of {state.Value.Brand} {state.Value.Model} " +
                                           $"with license-number {state.Value.LicenseNumber}.");

                    var speedingViolation = new SpeedingViolation
                    {
                        VehicleId      = msg.LicenseNumber,
                        RoadId         = _roadId,
                        ViolationInKmh = violation,
                        Timestamp      = msg.Timestamp
                    };
                    await _governmentService.SendFine(speedingViolation);
                }

                return(Ok());
            }
            catch
            {
                return(Ok(new { status = "RETRY" }));
            }
        }
Exemplo n.º 19
0
    public async Task RegisterExitAsync(VehicleRegistered msg)
    {
        try
        {
            Logger.LogInformation($"EXIT detected in lane {msg.Lane} at " +
                                  $"{msg.Timestamp.ToString("hh:mm:ss")} " +
                                  $"of vehicle with license-number {msg.LicenseNumber}.");

            // remove lost vehicle timer
            await UnregisterReminderAsync("VehicleLost");

            // get vehicle state
            var vehicleState = await this.StateManager.GetStateAsync <VehicleState>("VehicleState");

            vehicleState = vehicleState with {
                ExitTimestamp = msg.Timestamp
            };
            await this.StateManager.SetStateAsync("VehicleState", vehicleState);

            // handle possible speeding violation
            int violation = _speedingViolationCalculator.DetermineSpeedingViolationInKmh(
                vehicleState.EntryTimestamp, vehicleState.ExitTimestamp.Value);
            if (violation > 0)
            {
                Logger.LogInformation($"Speeding violation detected ({violation} KMh) of vehicle " +
                                      $"with license-number {vehicleState.LicenseNumber}.");

                var speedingViolation = new SpeedingViolation
                {
                    VehicleId      = msg.LicenseNumber,
                    RoadId         = _roadId,
                    ViolationInKmh = violation,
                    Timestamp      = msg.Timestamp
                };

                // publish speedingviolation (Dapr publish / subscribe)
                await _daprClient.PublishEventAsync("pubsub", "speedingviolations", speedingViolation);
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "Error in RegisterExit");
        }
    }
        public void Start()
        {
            Console.WriteLine($"Start camera {_camNumber} simulation.");

            // initialize state
            _rnd = new Random();

            while (true)
            {
                try
                {
                    // simulate entry
                    TimeSpan entryDelay = TimeSpan.FromMilliseconds(_rnd.Next(_minEntryDelayInMS, _maxEntryDelayInMS) + _rnd.NextDouble());
                    Task.Delay(entryDelay).Wait();

                    Task.Run(() =>
                    {
                        // simulate entry
                        DateTime entryTimestamp = DateTime.Now;
                        var vehicleRegistered   = new VehicleRegistered
                        {
                            Lane          = _camNumber,
                            LicenseNumber = GenerateRandomLicenseNumber(),
                            Timestamp     = entryTimestamp
                        };
                        _trafficControlService.SendVehicleEntry(vehicleRegistered);
                        Console.WriteLine($"Simulated ENTRY of vehicle with license-number {vehicleRegistered.LicenseNumber} in lane {vehicleRegistered.Lane}");

                        // simulate exit
                        TimeSpan exitDelay = TimeSpan.FromSeconds(_rnd.Next(_minExitDelayInS, _maxExitDelayInS) + _rnd.NextDouble());
                        Task.Delay(exitDelay).Wait();
                        vehicleRegistered.Timestamp = DateTime.Now;
                        vehicleRegistered.Lane      = _rnd.Next(1, 4);
                        _trafficControlService.SendVehicleExit(vehicleRegistered);
                        Console.WriteLine($"Simulated EXIT of vehicle with license-number {vehicleRegistered.LicenseNumber} in lane {vehicleRegistered.Lane}");
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
Exemplo n.º 21
0
 public override VehicleState When(VehicleState state, object @event)
 {
     return(@event switch
     {
         VehicleRegistered e => With(state, x =>
         {
             x.Id = e.VehicleId;
             x.CustomerId = e.CustomerId;
             x.State = e.State;
             x.Registration = e.Registration;
             x.MaxSpeed = e.MaxSpeed;
             x.MaxTemperature = e.MaxTemperature;
         }),
         VehicleMaxSpeedAdjusted e => With(state, x => x.MaxSpeed = e.MaxSpeed),
         VehicleMaxTemperatureAdjusted e => With(state, x => x.MaxTemperature = e.MaxTemperature),
         VehicleOverheated e => Overheated(e.Temperature),
         VehicleSpeeingDetected e => Speeding(e.RecordedSpeed),
         _ => state
     });
    public async Task <ActionResult> VehicleEntryAsync(VehicleRegistered msg)
    {
        try
        {
            // log entry
            _logger.LogInformation($"ENTRY detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")} " +
                                   $"of vehicle with license-number {msg.LicenseNumber}.");

            // store vehicle state
            var vehicleState = new VehicleState(msg.LicenseNumber, msg.Timestamp, null);
            await _vehicleStateRepository.SaveVehicleStateAsync(vehicleState);

            return(Ok());
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error occurred while processing ENTRY");
            return(StatusCode(500));
        }
    }
        public async Task <ActionResult> VehicleExit(VehicleRegistered msg, [FromServices] IHttpClientFactory httpClientFactory)
        {
            // get vehicle state
            var state = _repo.GetVehicleState(msg.LicenseNumber);

            if (state == null)
            {
                return(NotFound());
            }

            // log exit
            _logger.LogInformation($"EXIT detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")}: " +
                                   $"{state.Brand} {state.Model} with license-number {state.LicenseNumber}.");

            // update state
            state.ExitTimestamp = msg.Timestamp;
            _repo.StoreVehicleState(state);

            // handle possible speeding violation
            int violation = _speedingViolationCalculator.DetermineSpeedingViolationInKmh(state.EntryTimestamp, state.ExitTimestamp);

            if (violation > 0)
            {
                _logger.LogInformation($"Speeding violation detected ({violation} KMh) of {state.Brand} {state.Model} " +
                                       $"with license-number {state.LicenseNumber}.");

                var @event = new SpeedingViolationDetected
                {
                    VehicleId      = msg.LicenseNumber,
                    RoadId         = _roadId,
                    ViolationInKmh = violation,
                    Timestamp      = msg.Timestamp
                };

                var @eventJson = new StringContent(JsonSerializer.Serialize(@event, _jsonSerializerOptions), Encoding.UTF8, "application/json");
                var httpClient = httpClientFactory.CreateClient();
                var response   = await httpClient.PostAsync("http://localhost:6000/cjib/speedingviolation", @eventJson);
            }

            return(Ok());
        }
Exemplo n.º 24
0
        public async Task <ActionResult> VehicleExit(VehicleRegistered msg, [FromServices] IHttpClientFactory httpClientFactory, [FromServices] DaprClient daprClient)
        {
            // get vehicle state
            var state = await daprClient.GetStateEntryAsync <VehicleState>(DAPR_STORE_NAME, msg.LicenseNumber);

            if (state.Value == null)
            {
                return(NotFound());
            }

            // log exit
            _logger.LogInformation($"EXIT detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")}: " +
                                   $"{state.Value.Brand} {state.Value.Model} with license-number {state.Value.LicenseNumber}.");

            // update state
            state.Value.ExitTimestamp = msg.Timestamp;
            await state.SaveAsync();

            // handle possible speeding violation
            int violation = _speedingViolationCalculator.DetermineSpeedingViolationInKmh(state.Value.EntryTimestamp, state.Value.ExitTimestamp);

            if (violation > 0)
            {
                _logger.LogInformation($"Speeding violation detected ({violation} KMh) of {state.Value.Brand} {state.Value.Model} " +
                                       $"with license-number {state.Value.LicenseNumber}.");

                var @event = new SpeedingViolationDetected
                {
                    VehicleId      = msg.LicenseNumber,
                    RoadId         = _roadId,
                    ViolationInKmh = violation,
                    Timestamp      = msg.Timestamp
                };

                await daprClient.PublishEventAsync <SpeedingViolationDetected>("pubsub", "cjib.speedingviolation", @event);
            }

            return(Ok());
        }
Exemplo n.º 25
0
 public static Func <Task> GetHandler(IAsyncDocumentSession session, object @event)
 {
     return(@event switch
     {
         VehicleRegistered e =>
         () =>
         session.StoreAsync(
             new VehicleItem
         {
             Id = GetDbId(e.VehicleId),
             Registration = e.Registration,
             MakeModel = e.MakeModel,
             MaxSpeed = e.MaxSpeed,
             MaxTemperature = e.MaxTemperature,
             State = e.State,
             Sensors = new List <VehicleItem.VehicleSensor>()
         }
             ),
         VehicleMaxSpeedAdjusted e =>
         () => Update(e.VehicleId, x => x.MaxSpeed = e.MaxSpeed),
         VehicleMaxTemperatureAdjusted e =>
         () => Update(e.VehicleId, x => x.MaxTemperature = e.MaxTemperature),
         VehicleSpeeingDetected e =>
         () => Update(e.VehicleId, x => x.State = "Speeding"),
         VehicleOverheated e =>
         () => Update(e.VehicleId, x => x.State = "Overheated"),
         Messages.Sensor.Events.SensorTelemetryReceived e =>
         () => UpdateOneSensor(
             e.VehicleId,
             e.SensorId,
             sensor =>
         {
             sensor.Speed = e.Speed;
             sensor.Temperature = e.Temperature;
         }
             ),
         _ => (Func <Task>)null
     });
Exemplo n.º 26
0
        public async Task <ActionResult> VehicleEntry(VehicleRegistered msg)
        {
            try
            {
                // log entry
                _logger.LogInformation($"ENTRY detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")} " +
                                       $"of vehicle with license-number {msg.LicenseNumber}.");

                // store vehicle state
                var vehicleState = new VehicleState
                {
                    LicenseNumber  = msg.LicenseNumber,
                    EntryTimestamp = msg.Timestamp
                };
                await _vehicleStateRepository.SaveVehicleStateAsync(vehicleState);

                return(Ok());
            }
            catch
            {
                return(StatusCode(500));
            }
        }
        public void It_should_book_registered_vehicle()
        {
            var licencePlate      = LicencePlate.Create("123-123");
            var registeredVehicle = new VehicleRegistered("123-123");

            var vehicle = Vehicle.FromStream(
                licencePlate: licencePlate,
                events: registeredVehicle);

            vehicle.Book(licencePlate, "Kernow", 1579132800, EndOf.Week);

            var expected = new object[] {
                new VehicleBooked(
                    licencePlate: "123-123",
                    location: "Kernow",
                    start: new DateTimeOffset(new DateTime(2020, 01, 16)).ToUnixTimeSeconds(),
                    finish: new DateTimeOffset(new DateTime(2020, 01, 16)).AddDays(7).AddSeconds(-1).ToUnixTimeSeconds()
                    )
            };

            DeepAssert.Equal(expected, vehicle.TakeChanges().ToArray());
            Assert.Equal(0, vehicle.Version);
        }
Exemplo n.º 28
0
        private async Task <bool> HandleAsync(VehicleRegistered e)
        {
            Console.WriteLine($"Vehicle registered: License = {e.LicenseNumber}, Brand = {e.Brand}, Type = {e.Type}, Owner Id: {e.OwnerId}");

            try
            {
                await _dbContext.Vehicles.AddAsync(new Vehicle
                {
                    LicenseNumber = e.LicenseNumber,
                    Brand         = e.Brand,
                    Type          = e.Type,
                    OwnerId       = e.OwnerId
                });

                await _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                Console.WriteLine($"Skipped adding vehicle with license number {e.LicenseNumber}.");
            }

            return(true);
        }
Exemplo n.º 29
0
        private async Task <bool> HandleAsync(VehicleRegistered e)
        {
            Log.Information("Vehicle registered: {LicenseNumber}, {Brand}, {Type}, Owner Id: {OwnerId}",
                            e.Matricula, e.Marca, e.Modelo, e.OwnerId);

            try
            {
                await _dbContext.Vehicles.AddAsync(new Vehicle
                {
                    Matricula = e.Matricula,
                    Marca     = e.Marca,
                    Modelo    = e.Modelo,
                    OwnerId   = e.OwnerId
                });

                await _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                Console.WriteLine($"Skipped adding vehicle with matricula {e.Matricula}.");
            }

            return(true);
        }