├── src ├── Messages │ ├── Shutdown.cs │ ├── Messages.csproj │ ├── GetVehicleInfo.cs │ ├── MissingCarDetected.cs │ ├── SimulatePassingCar.cs │ ├── StartSimulation.cs │ ├── VehiclePassed.cs │ ├── VehicleEntryRegistered.cs │ ├── VehicleExitRegistered.cs │ ├── VehicleInfoAvailable.cs │ └── RegisterSpeedingViolation.cs ├── global.json ├── TrafficControl.code-workspace ├── directory.packages.props ├── PersistencePlugins │ ├── PersistencePlugins.csproj │ └── FileJournal.cs ├── Actors │ ├── ConsoleHelpers.cs │ ├── Actors.csproj │ ├── RoadInfo.cs │ ├── ExitCamActor.cs │ ├── EntryCamActor.cs │ ├── CJCAActor.cs │ ├── TrafficControlActor.cs │ ├── CJCALogic.cs │ ├── DMVActor.cs │ ├── PersistentCJCAActor.cs │ ├── VehicleActor.cs │ └── SimulationActor.cs ├── Host │ ├── Akkaconfig.hocon │ ├── Host.csproj │ └── Program.cs ├── CJCAHost │ ├── Akkaconfig.hocon │ ├── CJCAHost.csproj │ └── Program.cs ├── .vscode │ ├── tasks.json │ └── launch.json └── TrafficControl.sln ├── img ├── actor-hierarchy.png ├── sequence-diagram.png └── speed-trap-overview.png ├── .gitattributes ├── README.md ├── .gitignore └── LICENSE /src/Messages/Shutdown.cs: -------------------------------------------------------------------------------- 1 | namespace Messages 2 | { 3 | public class Shutdown 4 | { 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "6.0.0", 4 | "rollForward": "latestFeature" 5 | } 6 | } -------------------------------------------------------------------------------- /img/actor-hierarchy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EdwinVW/akka-net-traffic-control/HEAD/img/actor-hierarchy.png -------------------------------------------------------------------------------- /img/sequence-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EdwinVW/akka-net-traffic-control/HEAD/img/sequence-diagram.png -------------------------------------------------------------------------------- /img/speed-trap-overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EdwinVW/akka-net-traffic-control/HEAD/img/speed-trap-overview.png -------------------------------------------------------------------------------- /src/TrafficControl.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "." 5 | } 6 | ], 7 | "settings": {} 8 | } -------------------------------------------------------------------------------- /src/Messages/Messages.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/Messages/GetVehicleInfo.cs: -------------------------------------------------------------------------------- 1 | namespace Messages 2 | { 3 | public class GetVehicleInfo 4 | { 5 | public string VehicleId { get; private set; } 6 | 7 | public GetVehicleInfo(string vehicleId) 8 | { 9 | VehicleId = vehicleId; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Messages/MissingCarDetected.cs: -------------------------------------------------------------------------------- 1 | namespace Messages 2 | { 3 | public class MissingCarDetected 4 | { 5 | public string VehicleId { get; private set; } 6 | 7 | public MissingCarDetected(string vehicleId) 8 | { 9 | VehicleId = vehicleId; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/Messages/SimulatePassingCar.cs: -------------------------------------------------------------------------------- 1 | namespace Messages 2 | { 3 | public class SimulatePassingCar 4 | { 5 | public string VehicleId { get; private set; } 6 | 7 | public SimulatePassingCar(string vehicleId) 8 | { 9 | VehicleId = vehicleId; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Messages/StartSimulation.cs: -------------------------------------------------------------------------------- 1 | namespace Messages 2 | { 3 | public class StartSimulation 4 | { 5 | public int NumberOfCars { get; private set; } 6 | 7 | public StartSimulation(int numberOfCars) 8 | { 9 | NumberOfCars = numberOfCars; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/directory.packages.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/PersistencePlugins/PersistencePlugins.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | true 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Messages/VehiclePassed.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Messages 4 | { 5 | public class VehiclePassed 6 | { 7 | public string VehicleId { get; private set; } 8 | 9 | public DateTime Timestamp { get; private set; } 10 | 11 | public VehiclePassed(string vehicleId, DateTime timestamp) 12 | { 13 | VehicleId = vehicleId; 14 | Timestamp = timestamp; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Messages/VehicleEntryRegistered.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Messages 4 | { 5 | public class VehicleEntryRegistered 6 | { 7 | public string VehicleId { get; private set; } 8 | 9 | public DateTime Timestamp { get; private set; } 10 | 11 | public VehicleEntryRegistered(string vehicleId, DateTime timestamp) 12 | { 13 | VehicleId = vehicleId; 14 | Timestamp = timestamp; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Messages/VehicleExitRegistered.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Messages 4 | { 5 | public class VehicleExitRegistered 6 | { 7 | public string VehicleId { get; private set; } 8 | 9 | public DateTime Timestamp { get; private set; } 10 | 11 | public VehicleExitRegistered(string vehicleId, DateTime timestamp) 12 | { 13 | VehicleId = vehicleId; 14 | Timestamp = timestamp; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Actors/ConsoleHelpers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Actors 4 | { 5 | public static class ConsoleHelpers 6 | { 7 | public static void PrintAtLocation(int left, int top, string text) 8 | { 9 | int currentLeft = Console.CursorLeft; 10 | int currentTop = Console.CursorTop; 11 | 12 | Console.SetCursorPosition(left, top); 13 | Console.Write(text); 14 | Console.SetCursorPosition(currentLeft, currentTop); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /src/Messages/VehicleInfoAvailable.cs: -------------------------------------------------------------------------------- 1 | namespace Messages 2 | { 3 | public class VehicleInfoAvailable 4 | { 5 | public string VehicleId { get; private set; } 6 | 7 | public string Brand { get; private set; } 8 | 9 | public string Color { get; private set; } 10 | 11 | public VehicleInfoAvailable(string vehicleId, string brand, string color) 12 | { 13 | VehicleId = vehicleId; 14 | Brand = brand; 15 | Color = color; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Actors/Actors.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | true 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/Messages/RegisterSpeedingViolation.cs: -------------------------------------------------------------------------------- 1 | namespace Messages 2 | { 3 | public class RegisterSpeedingViolation 4 | { 5 | public string VehicleId { get; private set; } 6 | public string RoadId { get; private set; } 7 | public double ViolationInKmh { get; private set; } 8 | 9 | public RegisterSpeedingViolation(string vehicleId, string roadId, double violationInKmh) 10 | { 11 | VehicleId = vehicleId; 12 | RoadId = roadId; 13 | ViolationInKmh = violationInKmh; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Host/Akkaconfig.hocon: -------------------------------------------------------------------------------- 1 | akka 2 | { 3 | stdout-loglevel = ERROR 4 | loglevel = ERROR 5 | log-config-on-start = on 6 | 7 | actor 8 | { 9 | debug 10 | { 11 | receive = on 12 | autoreceive = on 13 | lifecycle = on 14 | event-stream = on 15 | unhandled = on 16 | } 17 | 18 | provider = remote 19 | 20 | deployment 21 | { 22 | /cjcaactor 23 | { 24 | remote = "akka.tcp://cjcasystem@localhost:9999" 25 | } 26 | } 27 | } 28 | 29 | remote 30 | { 31 | dot-netty.tcp 32 | { 33 | port = 0 34 | hostname = localhost 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Actors/RoadInfo.cs: -------------------------------------------------------------------------------- 1 | namespace Actors 2 | { 3 | public class RoadInfo 4 | { 5 | public string RoadId { get; } 6 | public int SectionLengthInKm { get; } 7 | public int MaxAllowedSpeedInKmh { get; } 8 | public int LegalCorrectionInKmh { get; } 9 | 10 | public RoadInfo(string roadId, int sectionLengthInKm, 11 | int maxAllowedSpeedInKmh, int legalCorrectionInKmh) 12 | { 13 | RoadId = roadId; 14 | SectionLengthInKm = sectionLengthInKm; 15 | MaxAllowedSpeedInKmh = maxAllowedSpeedInKmh; 16 | LegalCorrectionInKmh = legalCorrectionInKmh; 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /src/CJCAHost/Akkaconfig.hocon: -------------------------------------------------------------------------------- 1 | akka 2 | { 3 | stdout-loglevel = ERROR 4 | loglevel = ERROR 5 | log-config-on-start = on 6 | 7 | actor 8 | { 9 | debug 10 | { 11 | receive = on 12 | autoreceive = on 13 | lifecycle = on 14 | event-stream = on 15 | unhandled = on 16 | } 17 | 18 | provider = remote 19 | } 20 | 21 | remote 22 | { 23 | dot-netty.tcp 24 | { 25 | port = 9999 26 | hostname = localhost 27 | } 28 | } 29 | 30 | persistence 31 | { 32 | journal 33 | { 34 | plugin = "akka.persistence.journal.file" 35 | file 36 | { 37 | class = "PersistencePlugins.FileJournal, PersistencePlugins" 38 | plugin-dispatcher = "akka.actor.default-dispatcher" 39 | folder = "d:\\temp\\akkajournal" 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build Host", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/Host/Host.csproj" 11 | ], 12 | "problemMatcher": "$msCompile", 13 | "group": { 14 | "kind": "build", 15 | "isDefault": true 16 | } 17 | }, 18 | { 19 | "label": "build CJCAHost", 20 | "command": "dotnet", 21 | "type": "process", 22 | "args": [ 23 | "build", 24 | "${workspaceFolder}/CJCAHost/CJCAHost.csproj" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | } 28 | ] 29 | } -------------------------------------------------------------------------------- /src/CJCAHost/CJCAHost.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | true 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Always 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/CJCAHost/Program.cs: -------------------------------------------------------------------------------- 1 | using Actors; 2 | using Akka.Actor; 3 | using Akka.Configuration; 4 | using System; 5 | using System.IO; 6 | 7 | namespace CollectionAgencyHost 8 | { 9 | class Program 10 | { 11 | static void Main(string[] args) 12 | { 13 | Console.OutputEncoding = System.Text.Encoding.Unicode; 14 | 15 | var config = ConfigurationFactory.ParseString(File.ReadAllText("akkaconfig.hocon")); 16 | 17 | using (ActorSystem system = ActorSystem.Create("cjcasystem", config)) 18 | { 19 | Console.WriteLine("Remote actorsystem for the Central Judicial Collection Agency ready\n"); 20 | Console.ReadKey(true); 21 | 22 | System.Console.WriteLine("Stopped. Press any key to exit."); 23 | Console.ReadKey(true); 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Host/Host.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | true 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Always 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/Actors/ExitCamActor.cs: -------------------------------------------------------------------------------- 1 | using Akka.Actor; 2 | using Messages; 3 | 4 | namespace Actors 5 | { 6 | /// 7 | /// Actor that represents an exit camera. 8 | /// 9 | public class ExitCamActor : UntypedActor 10 | { 11 | private ActorSelection _trafficControlActor; 12 | 13 | public ExitCamActor() 14 | { 15 | // initialize state 16 | _trafficControlActor = Context.System.ActorSelection("/user/traffic-control"); 17 | } 18 | 19 | /// 20 | /// Handle received message. 21 | /// 22 | /// The message to handle. 23 | protected override void OnReceive(object message) 24 | { 25 | switch(message) 26 | { 27 | case VehiclePassed vp: 28 | Handle(vp); 29 | break; 30 | } 31 | } 32 | 33 | /// 34 | /// Handle VehiclePassed message 35 | /// 36 | /// The message to handle. 37 | private void Handle(VehiclePassed msg) 38 | { 39 | VehicleExitRegistered vehicleExitRegistered = new VehicleExitRegistered(msg.VehicleId, msg.Timestamp); 40 | _trafficControlActor.Tell(vehicleExitRegistered); 41 | 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Actors/EntryCamActor.cs: -------------------------------------------------------------------------------- 1 | using Akka.Actor; 2 | using Messages; 3 | 4 | namespace Actors 5 | { 6 | /// 7 | /// Actor that represents an entry camera. 8 | /// 9 | public class EntryCamActor : UntypedActor 10 | { 11 | private ActorSelection _trafficControlActor; 12 | 13 | public EntryCamActor() 14 | { 15 | // initialize state 16 | _trafficControlActor = Context.System.ActorSelection("/user/traffic-control"); 17 | } 18 | 19 | /// 20 | /// Handle received message. 21 | /// 22 | /// The message to handle. 23 | protected override void OnReceive(object message) 24 | { 25 | switch(message) 26 | { 27 | case VehiclePassed vp: 28 | Handle(vp); 29 | break; 30 | } 31 | } 32 | 33 | /// 34 | /// Handle VehiclePassed message 35 | /// 36 | /// The message to handle. 37 | private void Handle(VehiclePassed msg) 38 | { 39 | VehicleEntryRegistered vehicleEntryRegistered = 40 | new VehicleEntryRegistered(msg.VehicleId, msg.Timestamp); 41 | _trafficControlActor.Tell(vehicleEntryRegistered); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Actors/CJCAActor.cs: -------------------------------------------------------------------------------- 1 | using Akka.Actor; 2 | using Messages; 3 | using System; 4 | 5 | namespace Actors 6 | { 7 | /// 8 | /// Actor that handles communication with the department of justice (for registering violations). 9 | /// 10 | public class CJCAActor : UntypedActor 11 | { 12 | private decimal _totalAmountFined = 0; 13 | 14 | public CJCAActor() 15 | { 16 | Console.WriteLine($"Total amount fined: € {_totalAmountFined}\n"); 17 | } 18 | 19 | /// 20 | /// Handle received message. 21 | /// 22 | /// The message to handle. 23 | protected override void OnReceive(object message) 24 | { 25 | switch(message) 26 | { 27 | case RegisterSpeedingViolation rsv: 28 | Handle(rsv); 29 | break; 30 | } 31 | } 32 | 33 | /// 34 | /// Handle a RegisterSpeedingViolation message. 35 | /// 36 | /// The message to handle. 37 | private void Handle(RegisterSpeedingViolation msg) 38 | { 39 | decimal fine = CJCALogic.CalculateFine(msg.ViolationInKmh); 40 | 41 | _totalAmountFined += fine; 42 | 43 | string fineString = fine == 0 ? "tbd by the prosecutor" : fine.ToString(); 44 | System.Console.WriteLine($"Sent speeding ticket. Road: {msg.RoadId}, Licensenumber: {msg.VehicleId}" + 45 | $", Violation: {msg.ViolationInKmh} Km/h, Fine: € {fineString}"); 46 | 47 | ConsoleHelpers.PrintAtLocation(0, 2, $"Total amount fined: € {_totalAmountFined}"); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Actors/TrafficControlActor.cs: -------------------------------------------------------------------------------- 1 | using Akka.Actor; 2 | using Messages; 3 | 4 | namespace Actors 5 | { 6 | /// 7 | /// Actor that handles traffic control. 8 | /// 9 | public class TrafficControlActor : UntypedActor 10 | { 11 | private RoadInfo _roadInfo; 12 | 13 | public TrafficControlActor(RoadInfo roadInfo) 14 | { 15 | // initialize state 16 | _roadInfo = roadInfo; 17 | } 18 | 19 | /// 20 | /// Handle received message. 21 | /// 22 | /// The message to handle. 23 | protected override void OnReceive(object message) 24 | { 25 | switch(message) 26 | { 27 | case VehicleEntryRegistered ver: 28 | Handle(ver); 29 | break; 30 | case VehicleExitRegistered vxr: 31 | Handle(vxr); 32 | break; 33 | } 34 | } 35 | 36 | /// 37 | /// Handle VehicleEntryRegistered message. 38 | /// 39 | /// The message to handle. 40 | private void Handle(VehicleEntryRegistered msg) 41 | { 42 | var props = Props.Create(_roadInfo); 43 | var vehicleActor = Context.ActorOf(props, $"vehicle-{msg.VehicleId}"); 44 | vehicleActor.Tell(msg); 45 | } 46 | 47 | /// 48 | /// Handle VehicleExitRegistered message. 49 | /// 50 | /// The message to handle. 51 | private void Handle(VehicleExitRegistered msg) 52 | { 53 | var vehicleActor = Context.ActorSelection($"/user/traffic-control/*/vehicle-{msg.VehicleId}"); 54 | vehicleActor.Tell(msg); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/Actors/CJCALogic.cs: -------------------------------------------------------------------------------- 1 | namespace Actors 2 | { 3 | public static class CJCALogic 4 | { 5 | /// 6 | /// Calculate fine based on the violation. 7 | /// 8 | /// The amount of Km/h the driver was speeding. 9 | /// The fine. 10 | public static decimal CalculateFine(double violationInKmh) 11 | { 12 | switch(violationInKmh) 13 | { 14 | case 1: return 10; 15 | case 2: return 14; 16 | case 3: return 18; 17 | case 4: return 23; 18 | case 5: return 29; 19 | case 6: return 35; 20 | case 7: return 40; 21 | case 8: return 47; 22 | case 9: return 53; 23 | case 10: return 60; 24 | case 11: return 82; 25 | case 12: return 90; 26 | case 13: return 96; 27 | case 14: return 103; 28 | case 15: return 114; 29 | case 16: return 123; 30 | case 17: return 133; 31 | case 18: return 142; 32 | case 19: return 153; 33 | case 20: return 164; 34 | case 21: return 176; 35 | case 22: return 185; 36 | case 23: return 197; 37 | case 24: return 208; 38 | case 25: return 216; 39 | case 26: return 227; 40 | case 27: return 238; 41 | case 28: return 249; 42 | case 29: return 261; 43 | case 30: return 275; 44 | case 31: return 283; 45 | case 32: return 295; 46 | case 33: return 313; 47 | case 34: return 329; 48 | case 35: return 338; 49 | case 36: return 356; 50 | case 37: return 373; 51 | case 38: return 384; 52 | case 39: return 407; 53 | case 40: return 409; 54 | } 55 | 56 | return 0; 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /src/Host/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using Akka.Actor; 4 | using Akka.Configuration; 5 | using Akka.Routing; 6 | using Messages; 7 | using Actors; 8 | 9 | namespace Host 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | Console.OutputEncoding = System.Text.Encoding.Unicode; 16 | 17 | var config = ConfigurationFactory.ParseString(File.ReadAllText("akkaconfig.hocon")); 18 | 19 | using (ActorSystem system = ActorSystem.Create("TrafficControlSystem", config)) 20 | { 21 | var roadInfo = new RoadInfo("A2", 10, 100, 5); 22 | var trafficControlProps = Props.Create(roadInfo) 23 | .WithRouter(new RoundRobinPool(3)); 24 | var trafficControlActor = system.ActorOf(trafficControlProps, "traffic-control"); 25 | 26 | var entryCamActor1 = system.ActorOf("entrycam1"); 27 | var entryCamActor2 = system.ActorOf("entrycam2"); 28 | var entryCamActor3 = system.ActorOf("entrycam3"); 29 | 30 | var exitCamActor1 = system.ActorOf("exitcam1"); 31 | var exitCamActor2 = system.ActorOf("exitcam2"); 32 | var exitCamActor3 = system.ActorOf("exitcam3"); 33 | 34 | var cjcaActor = system.ActorOf("cjcaactor"); 35 | //var cjcaActor = system.ActorOf("cjcaactor"); 36 | 37 | var simulationProps = Props.Create().WithRouter(new BroadcastPool(3)); 38 | var simulationActor = system.ActorOf(simulationProps); 39 | 40 | Console.WriteLine("Actorsystem and actor created. Press any key to start simulation\n"); 41 | Console.ReadKey(true); 42 | 43 | simulationActor.Tell(new StartSimulation(15)); 44 | 45 | Console.ReadKey(true); 46 | system.Terminate(); 47 | 48 | System.Console.WriteLine("Stopped. Press any key to exit."); 49 | Console.ReadKey(true); 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Actors/DMVActor.cs: -------------------------------------------------------------------------------- 1 | using Akka.Actor; 2 | using Messages; 3 | using System; 4 | 5 | namespace Actors 6 | { 7 | /// 8 | /// Actor that handles communication with the department of motorvehicles. 9 | /// 10 | public class DMVActor : UntypedActor 11 | { 12 | private Random _rnd = new Random(); 13 | 14 | /// 15 | /// Handle received message. 16 | /// 17 | /// The message to handle. 18 | protected override void OnReceive(object message) 19 | { 20 | switch(message) 21 | { 22 | case GetVehicleInfo gvi: 23 | Handle(gvi); 24 | break; 25 | } 26 | } 27 | 28 | /// 29 | /// Handle a GetVehicleInfo message. 30 | /// 31 | /// The message to process. 32 | private void Handle(GetVehicleInfo msg) 33 | { 34 | // simulate web-service call ... 35 | 36 | // create event 37 | string brand = GetRandomBrand(); 38 | string color = GetRandomColor(); 39 | VehicleInfoAvailable info = 40 | new VehicleInfoAvailable(msg.VehicleId, brand, color); 41 | 42 | // send response to sender 43 | Sender.Tell(info); 44 | } 45 | 46 | #region Private helper methods 47 | 48 | private string[] _vehicleBrands = new string[] { "Mercedes", "Toyota", "Saab", "Audi", "BWW", "Volkswagen", "Seat", "Renault", "Skoda", "Kia", "Seat" }; 49 | private string[] _vehicleColors = new string[] { "Black", "White", "Grey", "Red", "Blue", "Green", "Silver" }; 50 | 51 | 52 | /// 53 | /// Get a random VehicleType. 54 | /// 55 | private string GetRandomBrand() 56 | { 57 | return _vehicleBrands[_rnd.Next(_vehicleBrands.Length)]; 58 | } 59 | 60 | /// 61 | /// Get a random Color. 62 | /// 63 | private string GetRandomColor() 64 | { 65 | return _vehicleColors[_rnd.Next(_vehicleColors.Length)]; 66 | } 67 | 68 | #endregion 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Start Host", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build Host", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/Host/bin/Debug/net6.0/Host.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/Host", 16 | // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window 17 | "console": "externalTerminal", 18 | "stopAtEntry": false, 19 | "internalConsoleOptions": "openOnSessionStart" 20 | }, 21 | { 22 | "name": "Start CJCAHost", 23 | "type": "coreclr", 24 | "request": "launch", 25 | "preLaunchTask": "build CJCAHost", 26 | // If you have changed target frameworks, make sure to update the program path. 27 | "program": "${workspaceFolder}/CJCAHost/bin/Debug/net6.0/CJCAHost.dll", 28 | "args": [], 29 | "cwd": "${workspaceFolder}/CJCAHost", 30 | // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window 31 | "console": "externalTerminal", 32 | "stopAtEntry": false, 33 | "internalConsoleOptions": "openOnSessionStart" 34 | } 35 | ], 36 | "compounds": [ 37 | { 38 | "name": "Start Host & CJCAHost", 39 | "configurations": [ 40 | { 41 | "name": "Start CJCAHost", 42 | "folder": "src" 43 | }, 44 | { 45 | "name": "Start Host", 46 | "folder": "src" 47 | } 48 | ] 49 | } 50 | ] 51 | } -------------------------------------------------------------------------------- /src/Actors/PersistentCJCAActor.cs: -------------------------------------------------------------------------------- 1 | using Akka.Persistence; 2 | using Messages; 3 | using System; 4 | 5 | namespace Actors 6 | { 7 | /// 8 | /// Actor that handles communication with the department of justice (for registering violations). 9 | /// 10 | public class PersistentCJCAActor : UntypedPersistentActor 11 | { 12 | private decimal _totalAmountFined = 0; 13 | 14 | public override string PersistenceId => "PersistentCJCAActor"; 15 | 16 | public PersistentCJCAActor() 17 | { 18 | Console.WriteLine(); 19 | Console.WriteLine(); 20 | } 21 | 22 | protected override void OnCommand(object message) 23 | { 24 | switch(message) 25 | { 26 | case RegisterSpeedingViolation rsv: 27 | Persist(rsv, Handle); 28 | break; 29 | 30 | } 31 | } 32 | 33 | protected override void OnRecover(object message) 34 | { 35 | switch(message) 36 | { 37 | case RegisterSpeedingViolation rsv: 38 | Handle(rsv); 39 | break; 40 | case RecoveryCompleted: 41 | ShowTotal(); 42 | break; 43 | } 44 | } 45 | 46 | /// 47 | /// Handle a RegisterSpeedingViolation message. 48 | /// 49 | /// The message to handle. 50 | private void Handle(RegisterSpeedingViolation msg) 51 | { 52 | decimal fine = CJCALogic.CalculateFine(msg.ViolationInKmh); 53 | 54 | _totalAmountFined += fine; 55 | 56 | if (!IsRecovering) 57 | { 58 | string fineString = fine == 0 ? "tbd by the prosecutor" : fine.ToString(); 59 | System.Console.WriteLine($"Sent speeding ticket. Road: {msg.RoadId}, Licensenumber: {msg.VehicleId}" + 60 | $", Violation: {msg.ViolationInKmh} Km/h, Fine: € {fineString}"); 61 | 62 | ShowTotal(); 63 | } 64 | } 65 | 66 | #region Private helper methods 67 | 68 | /// 69 | /// Show total amount fined. 70 | /// 71 | private void ShowTotal() 72 | { 73 | ConsoleHelpers.PrintAtLocation(0, 2, $"Total amount fined: € {_totalAmountFined}"); 74 | } 75 | 76 | #endregion 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /src/TrafficControl.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26730.10 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Actors", "Actors\Actors.csproj", "{854C20F5-4810-4EF2-8813-44599934AD29}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Messages", "Messages\Messages.csproj", "{0A3CC540-D614-41DF-92A7-C79ECC4F09E7}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Host", "Host\Host.csproj", "{42759D4B-0042-496D-B533-F4A57567CBCB}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CJCAHost", "CJCAHost\CJCAHost.csproj", "{FD210760-63BC-470B-997B-ABEC71E3C1F6}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PersistencePlugins", "PersistencePlugins\PersistencePlugins.csproj", "{250ADB7B-B96F-4FF5-8A1D-111BF373DD66}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {854C20F5-4810-4EF2-8813-44599934AD29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {854C20F5-4810-4EF2-8813-44599934AD29}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {854C20F5-4810-4EF2-8813-44599934AD29}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {854C20F5-4810-4EF2-8813-44599934AD29}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {0A3CC540-D614-41DF-92A7-C79ECC4F09E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {0A3CC540-D614-41DF-92A7-C79ECC4F09E7}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {0A3CC540-D614-41DF-92A7-C79ECC4F09E7}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {0A3CC540-D614-41DF-92A7-C79ECC4F09E7}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {42759D4B-0042-496D-B533-F4A57567CBCB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {42759D4B-0042-496D-B533-F4A57567CBCB}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {42759D4B-0042-496D-B533-F4A57567CBCB}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {42759D4B-0042-496D-B533-F4A57567CBCB}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {FD210760-63BC-470B-997B-ABEC71E3C1F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {FD210760-63BC-470B-997B-ABEC71E3C1F6}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {FD210760-63BC-470B-997B-ABEC71E3C1F6}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {FD210760-63BC-470B-997B-ABEC71E3C1F6}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {250ADB7B-B96F-4FF5-8A1D-111BF373DD66}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {250ADB7B-B96F-4FF5-8A1D-111BF373DD66}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {250ADB7B-B96F-4FF5-8A1D-111BF373DD66}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {250ADB7B-B96F-4FF5-8A1D-111BF373DD66}.Release|Any CPU.Build.0 = Release|Any CPU 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | GlobalSection(ExtensibilityGlobals) = postSolution 47 | SolutionGuid = {6D91A965-C7A9-420C-B55B-4F002784A182} 48 | EndGlobalSection 49 | EndGlobal 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Akka.NET Traffic Control Sample 2 | Sample code of an Actor Model based traffic-control system using Akka.Net. For this sample I've used a speeding-camera setup as can be found on several Dutch highways. Over the entire stretch the average speed of a vehicle is measured and if it is above the speeding limit on this highway, the driver of the vehicle receives a speeding ticket. 3 | 4 | ### Overview 5 | This is an overview of the fictitious setup I used for this sample: 6 | 7 | ![](img/speed-trap-overview.png) 8 | 9 | There's 1 entry-camera and 1 exit-camera per lane. When a car passes an entry-camera, the license-number of the car is registered. 10 | 11 | In the background, information about the vehicle is retrieved from the Department Of Motor-vehicles - DMV (or RDW in Dutch) by calling their web-service. 12 | 13 | When the car passes an exit-camera, this is registered by the system. The system then calculates the average speed of the car based on the entry- and exit-timestamp. If a speeding violation is detected, a message is sent to the Central Judicial Collection Agency - CJCA (or CJIB in Dutch) will send a speeding-ticket to the driver of the vehicle. 14 | 15 | ### Actor hierarchy 16 | I've used an Actor model approach to build this sample using [Akka.NET](http://getakka.net). The actor hierarchy used in the sample looks like this: 17 | 18 | ![](img/actor-hierarchy.png) 19 | 20 | - There is 1 actor per entry/ exit-cam. 21 | - The *Traffic Control Actor* handles vehicles detected by the camera's. Because this is the actor that has to take care of the load in this system, I've used a router using a round-robin routing-strategy to distribute the messages over multiple actors. 22 | - The *Vehicle Actor* represents a single detected vehicle. I've chosen to create an actor for every registered vehicle because this actor needs to manage the state for a vehicle. After a vehicle has left the area and is handled, the accompanying vehicle actor is removed. 23 | - The *DMV Actor* handles communication with the DMV for retrieving vehicle information. The *CJCA Actor* handles communication with the department of justice for registering speeding violations and sending speeding-tickets. 24 | - The *Simulation Actor* simulates traffic driving on the highway. It sends messages to the entryand exit-camera actors with random intervals. Because I want to be able to vary the load on the system, I've used a Broadcast router here. 25 | 26 | ### Interaction 27 | To describe how the actors interact with each-other in this system, I've created the following sequence-diagram: 28 | 29 | ![](img/sequence-diagram.png) 30 | 31 | ### Solution 32 | The solution contains several projects: 33 | 34 | - Actors - contains all the actors in the system. 35 | - Messages - contains a definition of all the messages used in the system. 36 | - Host - a console application hosting the actors in the system (except the CJCA Actor). 37 | - CJCAHost - a console application hosting the CJCA actor. 38 | - PersistencePlugin - a custom file-based implementation of a persistence provider for persistent actors. 39 | 40 | The solution contains 2 console-apps that act as a hosting process for an actor-system. This is because by default, the CJCA Actor is created in a separate process in order to demo Akka.Remote. When testing the application, make sure you have both the Host as the CJCAHost project configured as startup-project in the solution. By looking at the *AkkaConfig.hocon* configuration in both the projects, you can see how remote actor-deployment is configured. 41 | 42 | In the CJCAHost project, the custom persistence-provider is configured. This is used by the *PersistentCJCAActor* defined in the *Actors* project. If you create a *PersistentCJCAActor* in stead of a *CJCAActor* in the *Program.cs* file in the *Host* project, this will make sure the state of the actor is stored in a file on disk and loaded when the actor starts. In the *AkkaConfig.hocon* file in the *CJCAHost* project, the target folder for the file is configured. By default this is `d:\temp\akkajournal`. You can change this by changing the config file. Make sure you use double backslashes in the path! 43 | 44 | ### Disclaimer 45 | The code in this repo is NOT production grade and lacks any automated testing. It is intentionally kept as simple as possible (KISS). Its primary purpose is demonstrating several Actor Model concepts and not being a full fledged application that can be put into production as is. 46 | 47 | The author can in no way be held liable for damage caused directly or indirectly by using this code. 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /src/PersistencePlugins/FileJournal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Immutable; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Akka.Actor; 7 | using Akka.Util.Internal; 8 | using Akka.Persistence; 9 | using Akka.Persistence.Journal; 10 | using Akka.Configuration; 11 | using System.IO; 12 | using Newtonsoft.Json; 13 | 14 | namespace PersistencePlugins 15 | { 16 | using Messages = List; 17 | 18 | public class FileJournal : AsyncWriteJournal 19 | { 20 | JsonSerializerSettings _serializationsettings = new JsonSerializerSettings 21 | { 22 | Formatting = Formatting.Indented, 23 | TypeNameHandling = TypeNameHandling.All 24 | }; 25 | 26 | private Messages _messages = new Messages(); 27 | 28 | private string _folder; 29 | 30 | protected virtual Messages Messages { get { return _messages; } } 31 | 32 | public FileJournal(Config config) 33 | { 34 | _folder = config.GetString("folder"); 35 | 36 | if (_folder == null) 37 | { 38 | throw new ConfigurationException("Setting 'folder' was not specified in the FileJournal configuration."); 39 | } 40 | 41 | if (!Directory.Exists(_folder)) 42 | { 43 | Directory.CreateDirectory(_folder); 44 | } 45 | } 46 | 47 | protected override Task> WriteMessagesAsync(IEnumerable messages) 48 | { 49 | foreach (var w in messages) 50 | { 51 | LoadMessages(w.PersistenceId); 52 | foreach (var p in (IEnumerable)w.Payload) 53 | { 54 | Add(p); 55 | } 56 | SaveMessages(w.PersistenceId); 57 | } 58 | 59 | return Task.FromResult((IImmutableList)null); // all good 60 | } 61 | 62 | public override Task ReadHighestSequenceNrAsync(string persistenceId, long fromSequenceNr) 63 | { 64 | LoadMessages(persistenceId); 65 | return Task.FromResult(HighestSequenceNr(persistenceId)); 66 | } 67 | 68 | public override Task ReplayMessagesAsync(IActorContext context, string persistenceId, long fromSequenceNr, long toSequenceNr, long max, 69 | Action recoveryCallback) 70 | { 71 | LoadMessages(persistenceId); 72 | var highest = HighestSequenceNr(persistenceId); 73 | if (highest != 0L && max != 0L) 74 | Read(persistenceId, fromSequenceNr, Math.Min(toSequenceNr, highest), max).ForEach(recoveryCallback); 75 | return Task.FromResult(new object()); 76 | } 77 | 78 | protected override Task DeleteMessagesToAsync(string persistenceId, long toSequenceNr) 79 | { 80 | LoadMessages(persistenceId); 81 | var highestSeqNr = HighestSequenceNr(persistenceId); 82 | var toSeqNr = Math.Min(toSequenceNr, highestSeqNr); 83 | for (var snr = 1L; snr <= toSeqNr; snr++) 84 | Delete(persistenceId, snr); 85 | SaveMessages(persistenceId); 86 | return Task.FromResult(new object()); 87 | } 88 | 89 | private Messages Add(IPersistentRepresentation persistent) 90 | { 91 | Messages.Add((Persistent)persistent); 92 | return Messages; 93 | } 94 | 95 | private Messages Delete(string pid, long seqNr) 96 | { 97 | Messages.RemoveAt((int)seqNr); 98 | return Messages; 99 | } 100 | 101 | private IEnumerable Read(string pid, long fromSeqNr, long toSeqNr, long max) 102 | { 103 | if (Messages.Count > 0) 104 | { 105 | return Messages 106 | .Where(x => x.SequenceNr >= fromSeqNr && x.SequenceNr <= toSeqNr) 107 | .Take(max > int.MaxValue ? int.MaxValue : (int)max); 108 | } 109 | 110 | return Enumerable.Empty(); 111 | } 112 | 113 | private long HighestSequenceNr(string pid) 114 | { 115 | if (Messages.Count > 0) 116 | { 117 | var last = Messages.LastOrDefault(); 118 | return last?.SequenceNr ?? 0L; 119 | } 120 | 121 | return 0L; 122 | } 123 | 124 | private void LoadMessages(string persistenceId) 125 | { 126 | string filePath = Path.Combine(_folder, $"{persistenceId}.journal.json"); 127 | if (File.Exists(filePath)) 128 | { 129 | string jsonData = File.ReadAllText(filePath); 130 | 131 | _messages = JsonConvert.DeserializeObject(jsonData, _serializationsettings); 132 | } 133 | else 134 | { 135 | _messages = new Messages(); 136 | } 137 | } 138 | 139 | private void SaveMessages(string persistenceId) 140 | { 141 | string filePath = Path.Combine(_folder, $"{persistenceId}.journal.json"); 142 | if (File.Exists(filePath)) 143 | { 144 | File.Delete(filePath); 145 | } 146 | string jsonData = JsonConvert.SerializeObject(Messages, _serializationsettings); 147 | File.WriteAllText(filePath, jsonData); 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/Actors/VehicleActor.cs: -------------------------------------------------------------------------------- 1 | using Akka.Actor; 2 | using Messages; 3 | using System; 4 | 5 | namespace Actors 6 | { 7 | /// 8 | /// Actor that represents a registered vehicle. 9 | /// 10 | public class VehicleActor : UntypedActor 11 | { 12 | string _vehicleId; 13 | string _brand = "Unknown color"; 14 | string _color = "Unknown brand"; 15 | DateTime _entryTimestamp; 16 | DateTime? _exitTimestamp; 17 | 18 | private RoadInfo _roadInfo; 19 | 20 | double _elapsedMinutes; 21 | double _avgSpeedInKmh; 22 | 23 | IActorRef _dmvActor; 24 | ActorSelection _cjcaActor; 25 | 26 | public VehicleActor(RoadInfo roadInfo) 27 | { 28 | // initialize state 29 | _roadInfo = roadInfo; 30 | } 31 | 32 | /// 33 | /// Handle received message. 34 | /// 35 | /// The message to handle. 36 | protected override void OnReceive(object message) 37 | { 38 | switch(message) 39 | { 40 | case VehicleEntryRegistered ver: 41 | Handle(ver); 42 | break; 43 | case VehicleExitRegistered vxr: 44 | Handle(vxr); 45 | break; 46 | case VehicleInfoAvailable via: 47 | Handle(via); 48 | break; 49 | case MissingCarDetected mcd: 50 | Handle(mcd); 51 | break; 52 | case Shutdown sd: 53 | Handle(sd); 54 | break; 55 | } 56 | } 57 | 58 | /// 59 | /// Handle VehicleEntryRegistered message. 60 | /// 61 | /// The message to handle. 62 | private void Handle(VehicleEntryRegistered msg) 63 | { 64 | FluentConsole.Green.Line($"Vehicle '{msg.VehicleId}' entered at {msg.Timestamp.ToString("HH:mm:ss.ffffff")}"); 65 | 66 | _vehicleId = msg.VehicleId; 67 | _entryTimestamp = msg.Timestamp; 68 | 69 | _dmvActor = Context.ActorOf(); 70 | _dmvActor.Tell(new GetVehicleInfo(_vehicleId)); 71 | 72 | // set a time-out after wich we consider a car missing 73 | Context.System.Scheduler.ScheduleTellOnce( 74 | TimeSpan.FromMinutes(5), Self, new MissingCarDetected(msg.VehicleId), Self); 75 | } 76 | 77 | /// 78 | /// Handle VehicleInfoAvailable message. 79 | /// 80 | /// Message to handle. 81 | private void Handle(VehicleInfoAvailable msg) 82 | { 83 | _brand = msg.Brand; 84 | _color = msg.Color; 85 | } 86 | 87 | /// 88 | /// Handle VehicleExitRegistered message. 89 | /// 90 | /// The message to handle. 91 | private void Handle(VehicleExitRegistered msg) 92 | { 93 | _exitTimestamp = msg.Timestamp; 94 | 95 | // check speed limit 96 | int speedingViolation = DetermineSpeedingViolation(); 97 | 98 | // log exit 99 | if (speedingViolation > 0) 100 | { 101 | FluentConsole.Red.Line($"{_color} {_brand} '{msg.VehicleId}' exited at {msg.Timestamp.ToString("HH:mm:ss.ffffff")}" + 102 | $"(avg speed {_avgSpeedInKmh} km/h - {speedingViolation} km/h over speed-limit (after correction))"); 103 | 104 | // register speeding violation 105 | _cjcaActor = Context.ActorSelection("/user/cjcaactor"); 106 | var rsv = new RegisterSpeedingViolation(_vehicleId, _roadInfo.RoadId, speedingViolation); 107 | _cjcaActor.Tell(rsv); 108 | } 109 | else 110 | { 111 | FluentConsole.Yellow.Line($"{_color} {_brand} '{msg.VehicleId}' exited at {msg.Timestamp.ToString("HH:mm:ss.ffffff")}" + 112 | $"(avg speed {_avgSpeedInKmh} km/h)"); 113 | } 114 | 115 | Self.Tell(new Shutdown()); 116 | } 117 | 118 | /// 119 | /// Handle Shutdown message. 120 | /// 121 | /// The message to handle. 122 | private void Handle(Shutdown msg) 123 | { 124 | if (_dmvActor != null) 125 | { 126 | Context.Stop(_dmvActor); 127 | } 128 | Context.Stop(Self); 129 | } 130 | 131 | /// 132 | /// Handle MissingCarDetected message. 133 | /// 134 | /// The message to handle. 135 | private void Handle(MissingCarDetected msg) 136 | { 137 | FluentConsole.Magenta.Line($"Vehicle '{msg.VehicleId}' is missing. Sending road assistance."); 138 | 139 | // ... 140 | } 141 | 142 | #region Private helper methods 143 | 144 | /// 145 | /// Determine whether or not the vehicle was speeding. 146 | /// 147 | /// Violation in Km/h after correction. 148 | private int DetermineSpeedingViolation() 149 | { 150 | //_elapsedMinutes = _exitTimestamp.Value.Subtract(_entryTimestamp).TotalMinutes; 151 | _elapsedMinutes = _exitTimestamp.Value.Subtract(_entryTimestamp).TotalSeconds; // 1 sec. == 1 min. in simulation 152 | _avgSpeedInKmh = Math.Round((_roadInfo.SectionLengthInKm / _elapsedMinutes) * 60); 153 | int violation = Convert.ToInt32(_avgSpeedInKmh - _roadInfo.MaxAllowedSpeedInKmh - _roadInfo.LegalCorrectionInKmh); 154 | return violation; 155 | } 156 | 157 | #endregion 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/Actors/SimulationActor.cs: -------------------------------------------------------------------------------- 1 | using Akka.Actor; 2 | using Messages; 3 | using System; 4 | 5 | namespace Actors 6 | { 7 | /// 8 | /// Actor that simulates traffic. 9 | /// 10 | public class SimulationActor : UntypedActor 11 | { 12 | private int _numberOfCars; 13 | private int _carsSimulated; 14 | private Random _rnd; 15 | 16 | private int _minEntryDelayInMS = 50; 17 | private int _maxEntryDelayInMS = 5000; 18 | private int _minExitDelayInS = 5; 19 | private int _maxExitDelayInS = 7; 20 | 21 | /// 22 | /// Handle received message. 23 | /// 24 | /// The message to handle. 25 | protected override void OnReceive(object message) 26 | { 27 | switch(message) 28 | { 29 | case StartSimulation ss: 30 | Handle(ss); 31 | break; 32 | case SimulatePassingCar spc: 33 | Handle(spc); 34 | break; 35 | case Shutdown sd: 36 | Context.Stop(Self); 37 | break; 38 | } 39 | } 40 | 41 | /// 42 | /// Handle StartSimulation message. 43 | /// 44 | /// The message to handle. 45 | private void Handle(StartSimulation msg) 46 | { 47 | // initialize state 48 | _numberOfCars = msg.NumberOfCars; 49 | _carsSimulated = 0; 50 | _rnd = new Random(); 51 | 52 | // start simulationloop 53 | SimulatePassingCar simulatePassingCar = new SimulatePassingCar(GenerateRandomLicenseNumber()); 54 | Context.System.Scheduler.ScheduleTellOnce( 55 | _rnd.Next(_minEntryDelayInMS, _maxEntryDelayInMS), Self, simulatePassingCar, Self); 56 | } 57 | 58 | /// 59 | /// Handle SimulatePassingCar message. 60 | /// 61 | /// The message to handle. 62 | private void Handle(SimulatePassingCar msg) 63 | { 64 | // simulate car entry 65 | int entryLane = _rnd.Next(1, 4); 66 | ActorSelection entryCamera = Context.System.ActorSelection($"/user/entrycam{entryLane}"); 67 | DateTime entryTimestamp = DateTime.Now; 68 | VehiclePassed vehiclePassed = new VehiclePassed(msg.VehicleId, entryTimestamp); 69 | entryCamera.Tell(vehiclePassed); 70 | 71 | // simulate car exit 72 | int exitLane = _rnd.Next(1, 4); 73 | TimeSpan delay = TimeSpan.FromSeconds(_rnd.Next(_minExitDelayInS, _maxExitDelayInS) + _rnd.NextDouble()); 74 | DateTime exitTimestamp = entryTimestamp.Add(delay); 75 | ActorSelection exitCamera = Context.System.ActorSelection($"/user/exitcam{entryLane}"); 76 | vehiclePassed = new VehiclePassed(msg.VehicleId, exitTimestamp); 77 | Context.System.Scheduler.ScheduleTellOnce(delay, exitCamera, vehiclePassed, Self); 78 | 79 | // handle progress 80 | _carsSimulated++; 81 | if (_carsSimulated < _numberOfCars) 82 | { 83 | SimulatePassingCar simulatePassingCar = new SimulatePassingCar(GenerateRandomLicenseNumber()); 84 | Context.System.Scheduler.ScheduleTellOnce( 85 | _rnd.Next(_minEntryDelayInMS, _maxEntryDelayInMS), Self, simulatePassingCar, Self); 86 | } 87 | else 88 | { 89 | Self.Tell(new Shutdown()); 90 | } 91 | } 92 | 93 | #region Private helper methods 94 | 95 | private string _validLicenseNumberChars = "DFGHJKLNPRSTXYZ"; 96 | 97 | /// 98 | /// Generate random licensenumber. 99 | /// 100 | private string GenerateRandomLicenseNumber() 101 | { 102 | int type = _rnd.Next(1, 9); 103 | string kenteken = null; 104 | switch (type) 105 | { 106 | case 1: // 99-AA-99 107 | kenteken = string.Format("{0:00}-{1}-{2:00}", _rnd.Next(1, 99), GenerateRandomCharacters(2), _rnd.Next(1, 99)); 108 | break; 109 | case 2: // AA-99-AA 110 | kenteken = string.Format("{0}-{1:00}-{2}", GenerateRandomCharacters(2), _rnd.Next(1, 99), GenerateRandomCharacters(2)); 111 | break; 112 | case 3: // AA-AA-99 113 | kenteken = string.Format("{0}-{1}-{2:00}", GenerateRandomCharacters(2), GenerateRandomCharacters(2), _rnd.Next(1, 99)); 114 | break; 115 | case 4: // 99-AA-AA 116 | kenteken = string.Format("{0:00}-{1}-{2}", _rnd.Next(1, 99), GenerateRandomCharacters(2), GenerateRandomCharacters(2)); 117 | break; 118 | case 5: // 99-AAA-9 119 | kenteken = string.Format("{0:00}-{1}-{2}", _rnd.Next(1, 99), GenerateRandomCharacters(3), _rnd.Next(1, 10)); 120 | break; 121 | case 6: // 9-AAA-99 122 | kenteken = string.Format("{0}-{1}-{2:00}", _rnd.Next(1, 9), GenerateRandomCharacters(3), _rnd.Next(1, 10)); 123 | break; 124 | case 7: // AA-999-A 125 | kenteken = string.Format("{0}-{1:000}-{2}", GenerateRandomCharacters(2), _rnd.Next(1, 999), GenerateRandomCharacters(1)); 126 | break; 127 | case 8: // A-999-AA 128 | kenteken = string.Format("{0}-{1:000}-{2}", GenerateRandomCharacters(1), _rnd.Next(1, 999), GenerateRandomCharacters(2)); 129 | break; 130 | } 131 | 132 | return kenteken; 133 | } 134 | 135 | private string GenerateRandomCharacters(int aantal) 136 | { 137 | char[] chars = new char[aantal]; 138 | for (int i = 0; i < aantal; i++) 139 | { 140 | chars[i] = _validLicenseNumberChars[_rnd.Next(_validLicenseNumberChars.Length - 1)]; 141 | } 142 | return new string(chars); 143 | } 144 | 145 | #endregion 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------