mirror of
https://github.com/davidalves04/Trabalho-Pratico-SD.git
synced 2025-12-08 20:43:32 +00:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 906e958729 | |||
| 19709f0d7a | |||
| 13fa2f877d | |||
| 96c5680f41 |
@@ -51,7 +51,7 @@
|
|||||||
<artifactId>exec-maven-plugin</artifactId>
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
<version>3.1.0</version>
|
<version>3.1.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<mainClass>sd.Entry</mainClass>
|
<mainClass>sd.dashboard.Launcher</mainClass>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<!-- JavaFX Maven Plugin -->
|
<!-- JavaFX Maven Plugin -->
|
||||||
@@ -60,7 +60,7 @@
|
|||||||
<artifactId>javafx-maven-plugin</artifactId>
|
<artifactId>javafx-maven-plugin</artifactId>
|
||||||
<version>0.0.8</version>
|
<version>0.0.8</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<mainClass>sd.dashboard.DashboardUI</mainClass>
|
<mainClass>sd.dashboard.Launcher</mainClass>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
@@ -76,7 +76,7 @@
|
|||||||
<configuration>
|
<configuration>
|
||||||
<transformers>
|
<transformers>
|
||||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||||
<mainClass>sd.Entry</mainClass>
|
<mainClass>sd.dashboard.Launcher</mainClass>
|
||||||
</transformer>
|
</transformer>
|
||||||
</transformers>
|
</transformers>
|
||||||
</configuration>
|
</configuration>
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.locks.Lock;
|
import java.util.concurrent.locks.Lock;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
@@ -47,6 +48,8 @@ public class IntersectionProcess {
|
|||||||
|
|
||||||
private final ExecutorService trafficLightPool;
|
private final ExecutorService trafficLightPool;
|
||||||
|
|
||||||
|
private ScheduledExecutorService statsExecutor;
|
||||||
|
|
||||||
private volatile boolean running; // Quando uma thread escreve um valor volatile, todas as outras
|
private volatile boolean running; // Quando uma thread escreve um valor volatile, todas as outras
|
||||||
// threads veem a mudança imediatamente.
|
// threads veem a mudança imediatamente.
|
||||||
|
|
||||||
@@ -67,7 +70,6 @@ public class IntersectionProcess {
|
|||||||
private SocketClient dashboardClient;
|
private SocketClient dashboardClient;
|
||||||
private volatile int totalArrivals = 0;
|
private volatile int totalArrivals = 0;
|
||||||
private volatile int totalDepartures = 0;
|
private volatile int totalDepartures = 0;
|
||||||
private long lastStatsUpdateTime;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new IntersectionProcess.
|
* Constructs a new IntersectionProcess.
|
||||||
@@ -83,8 +85,9 @@ public class IntersectionProcess {
|
|||||||
this.outgoingConnections = new HashMap<>();
|
this.outgoingConnections = new HashMap<>();
|
||||||
this.connectionHandlerPool = Executors.newCachedThreadPool();
|
this.connectionHandlerPool = Executors.newCachedThreadPool();
|
||||||
this.trafficLightPool = Executors.newFixedThreadPool(4); // Max 4 directions
|
this.trafficLightPool = Executors.newFixedThreadPool(4); // Max 4 directions
|
||||||
|
this.statsExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||||
this.running = false;
|
this.running = false;
|
||||||
this.trafficCoordinationLock = new ReentrantLock();
|
this.trafficCoordinationLock = new ReentrantLock(true); // Fair lock to prevent starvation
|
||||||
this.currentGreenDirection = null;
|
this.currentGreenDirection = null;
|
||||||
|
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
@@ -148,7 +151,6 @@ public class IntersectionProcess {
|
|||||||
dashboardClient.connect();
|
dashboardClient.connect();
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Connected to dashboard.");
|
System.out.println("[" + intersectionId + "] Connected to dashboard.");
|
||||||
lastStatsUpdateTime = System.currentTimeMillis();
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("[" + intersectionId + "] Failed to connect to dashboard: " +
|
System.err.println("[" + intersectionId + "] Failed to connect to dashboard: " +
|
||||||
@@ -365,6 +367,9 @@ public class IntersectionProcess {
|
|||||||
// Start traffic light threads when running is true
|
// Start traffic light threads when running is true
|
||||||
startTrafficLights();
|
startTrafficLights();
|
||||||
|
|
||||||
|
// Start stats updater
|
||||||
|
statsExecutor.scheduleAtFixedRate(this::sendStatsToDashboard, 1, 1, TimeUnit.SECONDS);
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Waiting for incoming connections...\n");
|
System.out.println("[" + intersectionId + "] Waiting for incoming connections...\n");
|
||||||
|
|
||||||
// Main accept loop
|
// Main accept loop
|
||||||
@@ -464,6 +469,12 @@ public class IntersectionProcess {
|
|||||||
|
|
||||||
// Record arrival for statistics
|
// Record arrival for statistics
|
||||||
recordVehicleArrival();
|
recordVehicleArrival();
|
||||||
|
} else if (message.getType() == MessageType.SHUTDOWN) {
|
||||||
|
System.out.println(
|
||||||
|
"[" + intersectionId + "] Received SHUTDOWN command from " + message.getSourceNode());
|
||||||
|
running = false;
|
||||||
|
// Close this specific connection
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (java.net.SocketTimeoutException e) {
|
} catch (java.net.SocketTimeoutException e) {
|
||||||
@@ -507,6 +518,9 @@ public class IntersectionProcess {
|
|||||||
System.out.println("\n[" + intersectionId + "] Shutting down...");
|
System.out.println("\n[" + intersectionId + "] Shutting down...");
|
||||||
running = false;
|
running = false;
|
||||||
|
|
||||||
|
// Send final stats before closing connections
|
||||||
|
sendStatsToDashboard();
|
||||||
|
|
||||||
// 1. Close ServerSocket first
|
// 1. Close ServerSocket first
|
||||||
if (serverSocket != null && !serverSocket.isClosed()) {
|
if (serverSocket != null && !serverSocket.isClosed()) {
|
||||||
try {
|
try {
|
||||||
@@ -523,6 +537,9 @@ public class IntersectionProcess {
|
|||||||
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
||||||
connectionHandlerPool.shutdownNow();
|
connectionHandlerPool.shutdownNow();
|
||||||
}
|
}
|
||||||
|
if (statsExecutor != null && !statsExecutor.isShutdown()) {
|
||||||
|
statsExecutor.shutdownNow();
|
||||||
|
}
|
||||||
|
|
||||||
// 3. Wait briefly for termination (don't block forever)
|
// 3. Wait briefly for termination (don't block forever)
|
||||||
try {
|
try {
|
||||||
@@ -532,6 +549,9 @@ public class IntersectionProcess {
|
|||||||
if (connectionHandlerPool != null) {
|
if (connectionHandlerPool != null) {
|
||||||
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
||||||
}
|
}
|
||||||
|
if (statsExecutor != null) {
|
||||||
|
statsExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
}
|
}
|
||||||
@@ -572,7 +592,6 @@ public class IntersectionProcess {
|
|||||||
*/
|
*/
|
||||||
public void recordVehicleArrival() {
|
public void recordVehicleArrival() {
|
||||||
totalArrivals++;
|
totalArrivals++;
|
||||||
checkAndSendStats();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -580,22 +599,6 @@ public class IntersectionProcess {
|
|||||||
*/
|
*/
|
||||||
public void recordVehicleDeparture() {
|
public void recordVehicleDeparture() {
|
||||||
totalDepartures++;
|
totalDepartures++;
|
||||||
checkAndSendStats();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if it's time to send statistics to the dashboard and sends them if
|
|
||||||
* needed.
|
|
||||||
*/
|
|
||||||
private void checkAndSendStats() {
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
long elapsed = now - lastStatsUpdateTime;
|
|
||||||
|
|
||||||
// Send stats every 5 seconds
|
|
||||||
if (elapsed >= 5000) {
|
|
||||||
sendStatsToDashboard();
|
|
||||||
lastStatsUpdateTime = now;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -227,6 +227,16 @@ public class SimulationConfig {
|
|||||||
return Double.parseDouble(properties.getProperty("simulation.duration", "3600.0"));
|
return Double.parseDouble(properties.getProperty("simulation.duration", "3600.0"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the drain time (in virtual seconds) to allow vehicles to exit after
|
||||||
|
* generation stops.
|
||||||
|
*
|
||||||
|
* @return The drain time.
|
||||||
|
*/
|
||||||
|
public double getDrainTime() {
|
||||||
|
return Double.parseDouble(properties.getProperty("simulation.drain.time", "60.0"));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the vehicle arrival model ("POISSON" or "FIXED").
|
* Gets the vehicle arrival model ("POISSON" or "FIXED").
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import sd.util.VehicleGenerator;
|
|||||||
* This is the main entry point for the distributed simulation architecture.
|
* This is the main entry point for the distributed simulation architecture.
|
||||||
*/
|
*/
|
||||||
public class CoordinatorProcess {
|
public class CoordinatorProcess {
|
||||||
|
|
||||||
private final SimulationConfig config;
|
private final SimulationConfig config;
|
||||||
private final VehicleGenerator vehicleGenerator;
|
private final VehicleGenerator vehicleGenerator;
|
||||||
private final Map<String, SocketClient> intersectionClients;
|
private final Map<String, SocketClient> intersectionClients;
|
||||||
@@ -30,28 +30,28 @@ public class CoordinatorProcess {
|
|||||||
private int vehicleCounter;
|
private int vehicleCounter;
|
||||||
private boolean running;
|
private boolean running;
|
||||||
private double nextGenerationTime;
|
private double nextGenerationTime;
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
System.out.println("COORDINATOR PROCESS - DISTRIBUTED TRAFFIC SIMULATION");
|
System.out.println("COORDINATOR PROCESS - DISTRIBUTED TRAFFIC SIMULATION");
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 1. Load configuration
|
// 1. Load configuration
|
||||||
String configFile = args.length > 0 ? args[0] : "src/main/resources/simulation.properties";
|
String configFile = args.length > 0 ? args[0] : "src/main/resources/simulation.properties";
|
||||||
System.out.println("Loading configuration from: " + configFile);
|
System.out.println("Loading configuration from: " + configFile);
|
||||||
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile);
|
SimulationConfig config = new SimulationConfig(configFile);
|
||||||
CoordinatorProcess coordinator = new CoordinatorProcess(config);
|
CoordinatorProcess coordinator = new CoordinatorProcess(config);
|
||||||
|
|
||||||
// 2. Connect to intersection processes
|
// 2. Connect to intersection processes
|
||||||
System.out.println("\n" + "=".repeat(60));
|
System.out.println("\n" + "=".repeat(60));
|
||||||
coordinator.initialize();
|
coordinator.initialize();
|
||||||
|
|
||||||
// 3. Run the sim
|
// 3. Run the sim
|
||||||
System.out.println("\n" + "=".repeat(60));
|
System.out.println("\n" + "=".repeat(60));
|
||||||
coordinator.run();
|
coordinator.run();
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("Failed to load configuration: " + e.getMessage());
|
System.err.println("Failed to load configuration: " + e.getMessage());
|
||||||
System.exit(1);
|
System.exit(1);
|
||||||
@@ -60,7 +60,7 @@ public class CoordinatorProcess {
|
|||||||
System.exit(1);
|
System.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public CoordinatorProcess(SimulationConfig config) {
|
public CoordinatorProcess(SimulationConfig config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
this.vehicleGenerator = new VehicleGenerator(config);
|
this.vehicleGenerator = new VehicleGenerator(config);
|
||||||
@@ -69,131 +69,148 @@ public class CoordinatorProcess {
|
|||||||
this.vehicleCounter = 0;
|
this.vehicleCounter = 0;
|
||||||
this.running = false;
|
this.running = false;
|
||||||
this.nextGenerationTime = 0.0;
|
this.nextGenerationTime = 0.0;
|
||||||
|
|
||||||
System.out.println("Coordinator initialized with configuration:");
|
System.out.println("Coordinator initialized with configuration:");
|
||||||
System.out.println(" - Simulation duration: " + config.getSimulationDuration() + "s");
|
System.out.println(" - Simulation duration: " + config.getSimulationDuration() + "s");
|
||||||
System.out.println(" - Arrival model: " + config.getArrivalModel());
|
System.out.println(" - Arrival model: " + config.getArrivalModel());
|
||||||
System.out.println(" - Arrival rate: " + config.getArrivalRate() + " vehicles/s");
|
System.out.println(" - Arrival rate: " + config.getArrivalRate() + " vehicles/s");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void initialize() {
|
public void initialize() {
|
||||||
// Connect to dashboard first
|
// Connect to dashboard first
|
||||||
connectToDashboard();
|
connectToDashboard();
|
||||||
|
|
||||||
System.out.println("Connecting to intersection processes...");
|
System.out.println("Connecting to intersection processes...");
|
||||||
|
|
||||||
String[] intersectionIds = {"Cr1", "Cr2", "Cr3", "Cr4", "Cr5"};
|
String[] intersectionIds = { "Cr1", "Cr2", "Cr3", "Cr4", "Cr5" };
|
||||||
|
|
||||||
for (String intersectionId : intersectionIds) {
|
for (String intersectionId : intersectionIds) {
|
||||||
try {
|
try {
|
||||||
String host = config.getIntersectionHost(intersectionId);
|
String host = config.getIntersectionHost(intersectionId);
|
||||||
int port = config.getIntersectionPort(intersectionId);
|
int port = config.getIntersectionPort(intersectionId);
|
||||||
|
|
||||||
SocketClient client = new SocketClient(intersectionId, host, port);
|
SocketClient client = new SocketClient(intersectionId, host, port);
|
||||||
client.connect();
|
client.connect();
|
||||||
intersectionClients.put(intersectionId, client);
|
intersectionClients.put(intersectionId, client);
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("Failed to connect to " + intersectionId + ": " + e.getMessage());
|
System.err.println("Failed to connect to " + intersectionId + ": " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println("Successfully connected to " + intersectionClients.size() + " intersection(s)");
|
System.out.println("Successfully connected to " + intersectionClients.size() + " intersection(s)");
|
||||||
|
|
||||||
if (intersectionClients.isEmpty()) {
|
if (intersectionClients.isEmpty()) {
|
||||||
System.err.println("WARNING: No intersections connected. Simulation cannot proceed.");
|
System.err.println("WARNING: No intersections connected. Simulation cannot proceed.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
double duration = config.getSimulationDuration();
|
double duration = config.getSimulationDuration();
|
||||||
running = true;
|
running = true;
|
||||||
|
|
||||||
System.out.println("Starting vehicle generation simulation...");
|
System.out.println("Starting vehicle generation simulation...");
|
||||||
System.out.println("Duration: " + duration + " seconds");
|
System.out.println("Duration: " + duration + " seconds");
|
||||||
System.out.println();
|
System.out.println();
|
||||||
|
|
||||||
// Send simulation start time to all processes for synchronization
|
// Send simulation start time to all processes for synchronization
|
||||||
sendSimulationStartTime();
|
sendSimulationStartTime();
|
||||||
|
|
||||||
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
||||||
final double TIME_STEP = 0.1;
|
final double TIME_STEP = 0.1;
|
||||||
|
|
||||||
while (running && currentTime < duration) {
|
double drainTime = config.getDrainTime();
|
||||||
if (currentTime >= nextGenerationTime) {
|
double totalDuration = duration + drainTime;
|
||||||
generateAndSendVehicle();
|
boolean draining = false;
|
||||||
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
|
||||||
}
|
while (running && currentTime < totalDuration) {
|
||||||
|
// Only generate vehicles during the main duration
|
||||||
|
if (currentTime < duration) {
|
||||||
|
if (currentTime >= nextGenerationTime) {
|
||||||
|
generateAndSendVehicle();
|
||||||
|
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
||||||
|
}
|
||||||
|
} else if (!draining) {
|
||||||
|
draining = true;
|
||||||
|
System.out.println("\n[t=" + String.format("%.2f", currentTime)
|
||||||
|
+ "] Generation complete. Entering DRAIN MODE for " + drainTime + "s...");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep((long) (TIME_STEP * 1000));
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
currentTime += TIME_STEP;
|
currentTime += TIME_STEP;
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println();
|
System.out.println();
|
||||||
System.out.println("Simulation complete at t=" + String.format("%.2f", currentTime) + "s");
|
System.out.println("Simulation complete at t=" + String.format("%.2f", currentTime) + "s");
|
||||||
System.out.println("Total vehicles generated: " + vehicleCounter);
|
System.out.println("Total vehicles generated: " + vehicleCounter);
|
||||||
|
|
||||||
shutdown();
|
shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void generateAndSendVehicle() {
|
private void generateAndSendVehicle() {
|
||||||
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
|
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
|
||||||
|
|
||||||
System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n",
|
System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n",
|
||||||
currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute());
|
currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute());
|
||||||
|
|
||||||
// Send generation count to dashboard
|
// Send generation count to dashboard
|
||||||
sendGenerationStatsToDashboard();
|
sendGenerationStatsToDashboard();
|
||||||
|
|
||||||
if (vehicle.getRoute().isEmpty()) {
|
if (vehicle.getRoute().isEmpty()) {
|
||||||
System.err.println("ERROR: Vehicle " + vehicle.getId() + " has empty route!");
|
System.err.println("ERROR: Vehicle " + vehicle.getId() + " has empty route!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
String entryIntersection = vehicle.getRoute().get(0);
|
String entryIntersection = vehicle.getRoute().get(0);
|
||||||
sendVehicleToIntersection(vehicle, entryIntersection);
|
sendVehicleToIntersection(vehicle, entryIntersection);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendVehicleToIntersection(Vehicle vehicle, String intersectionId) {
|
private void sendVehicleToIntersection(Vehicle vehicle, String intersectionId) {
|
||||||
SocketClient client = intersectionClients.get(intersectionId);
|
SocketClient client = intersectionClients.get(intersectionId);
|
||||||
|
|
||||||
if (client == null || !client.isConnected()) {
|
if (client == null || !client.isConnected()) {
|
||||||
System.err.println("ERROR: No connection to " + intersectionId + " for vehicle " + vehicle.getId());
|
System.err.println("ERROR: No connection to " + intersectionId + " for vehicle " + vehicle.getId());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Message message = new Message(
|
Message message = new Message(
|
||||||
MessageType.VEHICLE_SPAWN,
|
MessageType.VEHICLE_SPAWN,
|
||||||
"COORDINATOR",
|
"COORDINATOR",
|
||||||
intersectionId,
|
intersectionId,
|
||||||
vehicle
|
vehicle);
|
||||||
);
|
|
||||||
|
|
||||||
client.send(message);
|
client.send(message);
|
||||||
System.out.printf("->Sent to %s%n", intersectionId);
|
System.out.printf("->Sent to %s%n", intersectionId);
|
||||||
|
|
||||||
} catch (SerializationException | IOException e) {
|
} catch (SerializationException | IOException e) {
|
||||||
System.err.println("ERROR: Failed to send vehicle " + vehicle.getId() + " to " + intersectionId);
|
System.err.println("ERROR: Failed to send vehicle " + vehicle.getId() + " to " + intersectionId);
|
||||||
System.err.println("Reason: " + e.getMessage());
|
System.err.println("Reason: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
System.out.println();
|
System.out.println();
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
System.out.println("Shutting down coordinator...");
|
System.out.println("Shutting down coordinator...");
|
||||||
|
|
||||||
for (Map.Entry<String, SocketClient> entry : intersectionClients.entrySet()) {
|
for (Map.Entry<String, SocketClient> entry : intersectionClients.entrySet()) {
|
||||||
String intersectionId = entry.getKey();
|
String intersectionId = entry.getKey();
|
||||||
SocketClient client = entry.getValue();
|
SocketClient client = entry.getValue();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (client.isConnected()) {
|
if (client.isConnected()) {
|
||||||
Message personalizedShutdown = new Message(
|
Message personalizedShutdown = new Message(
|
||||||
MessageType.SHUTDOWN,
|
MessageType.SHUTDOWN,
|
||||||
"COORDINATOR",
|
"COORDINATOR",
|
||||||
intersectionId,
|
intersectionId,
|
||||||
"Simulation complete"
|
"Simulation complete");
|
||||||
);
|
|
||||||
client.send(personalizedShutdown);
|
client.send(personalizedShutdown);
|
||||||
System.out.println("Sent shutdown message to " + intersectionId);
|
System.out.println("Sent shutdown message to " + intersectionId);
|
||||||
}
|
}
|
||||||
@@ -203,21 +220,21 @@ public class CoordinatorProcess {
|
|||||||
client.close();
|
client.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println("Coordinator shutdown complete");
|
System.out.println("Coordinator shutdown complete");
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
System.out.println("\nStop signal received...");
|
System.out.println("\nStop signal received...");
|
||||||
running = false;
|
running = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void connectToDashboard() {
|
private void connectToDashboard() {
|
||||||
try {
|
try {
|
||||||
String host = config.getDashboardHost();
|
String host = config.getDashboardHost();
|
||||||
int port = config.getDashboardPort();
|
int port = config.getDashboardPort();
|
||||||
|
|
||||||
System.out.println("Connecting to dashboard at " + host + ":" + port);
|
System.out.println("Connecting to dashboard at " + host + ":" + port);
|
||||||
dashboardClient = new SocketClient("Dashboard", host, port);
|
dashboardClient = new SocketClient("Dashboard", host, port);
|
||||||
dashboardClient.connect();
|
dashboardClient.connect();
|
||||||
@@ -227,58 +244,55 @@ public class CoordinatorProcess {
|
|||||||
System.err.println("Coordinator will continue without dashboard connection\n");
|
System.err.println("Coordinator will continue without dashboard connection\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendGenerationStatsToDashboard() {
|
private void sendGenerationStatsToDashboard() {
|
||||||
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Create stats payload with vehicle generation count
|
// Create stats payload with vehicle generation count
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload();
|
StatsUpdatePayload payload = new StatsUpdatePayload();
|
||||||
payload.setTotalVehiclesGenerated(vehicleCounter);
|
payload.setTotalVehiclesGenerated(vehicleCounter);
|
||||||
|
|
||||||
Message message = new Message(
|
Message message = new Message(
|
||||||
MessageType.STATS_UPDATE,
|
MessageType.STATS_UPDATE,
|
||||||
"COORDINATOR",
|
"COORDINATOR",
|
||||||
"Dashboard",
|
"Dashboard",
|
||||||
payload
|
payload);
|
||||||
);
|
|
||||||
|
|
||||||
dashboardClient.send(message);
|
dashboardClient.send(message);
|
||||||
} catch (Exception e) { //This is fine - can add IOException if need be
|
} catch (Exception e) { // This is fine - can add IOException if need be
|
||||||
// Don't crash if dashboard update fails
|
// Don't crash if dashboard update fails
|
||||||
System.err.println("Failed to send stats to dashboard: " + e.getMessage());
|
System.err.println("Failed to send stats to dashboard: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendSimulationStartTime() {
|
private void sendSimulationStartTime() {
|
||||||
long startTimeMillis = System.currentTimeMillis();
|
long startTimeMillis = System.currentTimeMillis();
|
||||||
|
|
||||||
// Send to all intersections
|
// Send to all intersections
|
||||||
for (Map.Entry<String, SocketClient> entry : intersectionClients.entrySet()) {
|
for (Map.Entry<String, SocketClient> entry : intersectionClients.entrySet()) {
|
||||||
try {
|
try {
|
||||||
Message message = new Message(
|
Message message = new Message(
|
||||||
MessageType.SIMULATION_START,
|
MessageType.SIMULATION_START,
|
||||||
"COORDINATOR",
|
"COORDINATOR",
|
||||||
entry.getKey(),
|
entry.getKey(),
|
||||||
startTimeMillis
|
startTimeMillis);
|
||||||
);
|
|
||||||
entry.getValue().send(message);
|
entry.getValue().send(message);
|
||||||
} catch (Exception e) { // Same thing here
|
} catch (Exception e) { // Same thing here
|
||||||
System.err.println("Failed to send start time to " + entry.getKey() + ": " + e.getMessage());
|
System.err.println("Failed to send start time to " + entry.getKey() + ": " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send to dashboard
|
// Send to dashboard
|
||||||
if (dashboardClient != null && dashboardClient.isConnected()) {
|
if (dashboardClient != null && dashboardClient.isConnected()) {
|
||||||
try {
|
try {
|
||||||
Message message = new Message(
|
Message message = new Message(
|
||||||
MessageType.SIMULATION_START,
|
MessageType.SIMULATION_START,
|
||||||
"COORDINATOR",
|
"COORDINATOR",
|
||||||
"Dashboard",
|
"Dashboard",
|
||||||
startTimeMillis
|
startTimeMillis);
|
||||||
);
|
|
||||||
dashboardClient.send(message);
|
dashboardClient.send(message);
|
||||||
} catch (Exception e) { // And here
|
} catch (Exception e) { // And here
|
||||||
// Don't crash
|
// Don't crash
|
||||||
|
|||||||
@@ -12,10 +12,10 @@ import javafx.geometry.Insets;
|
|||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
import javafx.scene.Scene;
|
import javafx.scene.Scene;
|
||||||
import javafx.scene.control.Alert;
|
import javafx.scene.control.Alert;
|
||||||
|
import javafx.scene.control.Button;
|
||||||
import javafx.scene.control.Label;
|
import javafx.scene.control.Label;
|
||||||
import javafx.scene.control.TableColumn;
|
import javafx.scene.control.TableColumn;
|
||||||
import javafx.scene.control.TableView;
|
import javafx.scene.control.TableView;
|
||||||
import javafx.scene.control.TitledPane;
|
|
||||||
import javafx.scene.control.cell.PropertyValueFactory;
|
import javafx.scene.control.cell.PropertyValueFactory;
|
||||||
import javafx.scene.layout.BorderPane;
|
import javafx.scene.layout.BorderPane;
|
||||||
import javafx.scene.layout.GridPane;
|
import javafx.scene.layout.GridPane;
|
||||||
@@ -23,10 +23,7 @@ import javafx.scene.layout.HBox;
|
|||||||
import javafx.scene.layout.Priority;
|
import javafx.scene.layout.Priority;
|
||||||
import javafx.scene.layout.Region;
|
import javafx.scene.layout.Region;
|
||||||
import javafx.scene.layout.VBox;
|
import javafx.scene.layout.VBox;
|
||||||
import javafx.scene.paint.Color;
|
|
||||||
import javafx.scene.shape.Circle;
|
import javafx.scene.shape.Circle;
|
||||||
import javafx.scene.text.Font;
|
|
||||||
import javafx.scene.text.FontWeight;
|
|
||||||
import javafx.stage.Stage;
|
import javafx.stage.Stage;
|
||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.model.VehicleType;
|
import sd.model.VehicleType;
|
||||||
@@ -36,10 +33,10 @@ import sd.model.VehicleType;
|
|||||||
* Provides a graphical interface with auto-updating statistics panels.
|
* Provides a graphical interface with auto-updating statistics panels.
|
||||||
*/
|
*/
|
||||||
public class DashboardUI extends Application {
|
public class DashboardUI extends Application {
|
||||||
|
|
||||||
private DashboardServer server;
|
private DashboardServer server;
|
||||||
private DashboardStatistics statistics;
|
private DashboardStatistics statistics;
|
||||||
|
|
||||||
// Global Statistics Labels
|
// Global Statistics Labels
|
||||||
private Label lblVehiclesGenerated;
|
private Label lblVehiclesGenerated;
|
||||||
private Label lblVehiclesCompleted;
|
private Label lblVehiclesCompleted;
|
||||||
@@ -47,287 +44,343 @@ public class DashboardUI extends Application {
|
|||||||
private Label lblAvgSystemTime;
|
private Label lblAvgSystemTime;
|
||||||
private Label lblAvgWaitingTime;
|
private Label lblAvgWaitingTime;
|
||||||
private Label lblLastUpdate;
|
private Label lblLastUpdate;
|
||||||
|
|
||||||
// Vehicle Type Table
|
// Vehicle Type Table
|
||||||
private TableView<VehicleTypeRow> vehicleTypeTable;
|
private TableView<VehicleTypeRow> vehicleTypeTable;
|
||||||
|
|
||||||
// Intersection Table
|
// Intersection Table
|
||||||
private TableView<IntersectionRow> intersectionTable;
|
private TableView<IntersectionRow> intersectionTable;
|
||||||
|
|
||||||
// Update scheduler
|
// Update scheduler
|
||||||
private ScheduledExecutorService updateScheduler;
|
private ScheduledExecutorService updateScheduler;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start(Stage primaryStage) {
|
public void start(Stage primaryStage) {
|
||||||
try {
|
try {
|
||||||
// Initialize server
|
// Initialize server
|
||||||
String configFile = getParameters().getRaw().isEmpty()
|
String configFile = getParameters().getRaw().isEmpty()
|
||||||
? "src/main/resources/simulation.properties"
|
? "src/main/resources/simulation.properties"
|
||||||
: getParameters().getRaw().get(0);
|
: getParameters().getRaw().get(0);
|
||||||
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile);
|
SimulationConfig config = new SimulationConfig(configFile);
|
||||||
server = new DashboardServer(config);
|
server = new DashboardServer(config);
|
||||||
statistics = server.getStatistics();
|
statistics = server.getStatistics();
|
||||||
|
|
||||||
// Start the dashboard server
|
// Start the dashboard server
|
||||||
server.start();
|
server.start();
|
||||||
|
|
||||||
// Build UI
|
// Build UI
|
||||||
BorderPane root = new BorderPane();
|
BorderPane root = new BorderPane();
|
||||||
root.setStyle("-fx-background-color: #f5f5f5;");
|
root.getStyleClass().add("root");
|
||||||
|
|
||||||
// Header
|
// Header
|
||||||
VBox header = createHeader();
|
VBox header = createHeader();
|
||||||
root.setTop(header);
|
root.setTop(header);
|
||||||
|
|
||||||
// Main content
|
// Main content
|
||||||
VBox mainContent = createMainContent();
|
VBox mainContent = createMainContent();
|
||||||
root.setCenter(mainContent);
|
root.setCenter(mainContent);
|
||||||
|
|
||||||
// Footer
|
// Footer
|
||||||
HBox footer = createFooter();
|
HBox footer = createFooter();
|
||||||
root.setBottom(footer);
|
root.setBottom(footer);
|
||||||
|
|
||||||
// Create scene
|
// Create scene
|
||||||
Scene scene = new Scene(root, 1200, 800);
|
Scene scene = new Scene(root, 1200, 850);
|
||||||
|
|
||||||
|
// Load CSS
|
||||||
|
String cssUrl = getClass().getResource("/dashboard.css").toExternalForm();
|
||||||
|
scene.getStylesheets().add(cssUrl);
|
||||||
|
|
||||||
primaryStage.setTitle("Traffic Simulation Dashboard - Real-time Statistics");
|
primaryStage.setTitle("Traffic Simulation Dashboard - Real-time Statistics");
|
||||||
primaryStage.setScene(scene);
|
primaryStage.setScene(scene);
|
||||||
primaryStage.show();
|
primaryStage.show();
|
||||||
|
|
||||||
// Start periodic updates
|
// Start periodic updates
|
||||||
startPeriodicUpdates();
|
startPeriodicUpdates();
|
||||||
|
|
||||||
// Handle window close
|
// Handle window close
|
||||||
primaryStage.setOnCloseRequest(event -> {
|
primaryStage.setOnCloseRequest(event -> {
|
||||||
shutdown();
|
shutdown();
|
||||||
});
|
});
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (Exception e) {
|
||||||
showErrorAlert("Failed to start Dashboard Server", e.getMessage());
|
showErrorAlert("Failed to start Dashboard Server", e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
Platform.exit();
|
Platform.exit();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private VBox createHeader() {
|
private VBox createHeader() {
|
||||||
VBox header = new VBox(10);
|
VBox header = new VBox(10);
|
||||||
header.setPadding(new Insets(20));
|
header.getStyleClass().add("header");
|
||||||
header.setStyle("-fx-background-color: linear-gradient(to right, #2c3e50, #3498db);");
|
|
||||||
|
|
||||||
Label title = new Label("DISTRIBUTED TRAFFIC SIMULATION DASHBOARD");
|
|
||||||
title.setFont(Font.font("Arial", FontWeight.BOLD, 28));
|
|
||||||
title.setTextFill(Color.WHITE);
|
|
||||||
|
|
||||||
Label subtitle = new Label("Real-time Statistics and Monitoring");
|
|
||||||
subtitle.setFont(Font.font("Arial", FontWeight.NORMAL, 16));
|
|
||||||
subtitle.setTextFill(Color.web("#ecf0f1"));
|
|
||||||
|
|
||||||
header.getChildren().addAll(title, subtitle);
|
|
||||||
header.setAlignment(Pos.CENTER);
|
header.setAlignment(Pos.CENTER);
|
||||||
|
|
||||||
|
Label title = new Label("DISTRIBUTED TRAFFIC SIMULATION DASHBOARD");
|
||||||
|
title.getStyleClass().add("header-title");
|
||||||
|
|
||||||
|
Label subtitle = new Label("Real-time Statistics and Monitoring");
|
||||||
|
subtitle.getStyleClass().add("header-subtitle");
|
||||||
|
|
||||||
|
// Control Buttons
|
||||||
|
HBox controls = new HBox(15);
|
||||||
|
controls.setAlignment(Pos.CENTER);
|
||||||
|
|
||||||
|
Button btnStart = new Button("START SIMULATION");
|
||||||
|
btnStart.getStyleClass().add("button-start");
|
||||||
|
|
||||||
|
Button btnStop = new Button("STOP SIMULATION");
|
||||||
|
btnStop.getStyleClass().add("button-stop");
|
||||||
|
btnStop.setDisable(true);
|
||||||
|
|
||||||
|
SimulationProcessManager processManager = new SimulationProcessManager();
|
||||||
|
|
||||||
|
btnStart.setOnAction(e -> {
|
||||||
|
try {
|
||||||
|
processManager.startSimulation();
|
||||||
|
btnStart.setDisable(true);
|
||||||
|
btnStop.setDisable(false);
|
||||||
|
} catch (IOException ex) {
|
||||||
|
showErrorAlert("Start Failed", "Could not start simulation processes: " + ex.getMessage());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
btnStop.setOnAction(e -> {
|
||||||
|
processManager.stopSimulation();
|
||||||
|
btnStart.setDisable(false);
|
||||||
|
btnStop.setDisable(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
controls.getChildren().addAll(btnStart, btnStop);
|
||||||
|
|
||||||
|
header.getChildren().addAll(title, subtitle, controls);
|
||||||
|
|
||||||
return header;
|
return header;
|
||||||
}
|
}
|
||||||
|
|
||||||
private VBox createMainContent() {
|
private VBox createMainContent() {
|
||||||
VBox mainContent = new VBox(15);
|
VBox mainContent = new VBox(20);
|
||||||
mainContent.setPadding(new Insets(20));
|
mainContent.setPadding(new Insets(20));
|
||||||
|
|
||||||
// Global Statistics Panel
|
// Global Statistics Panel
|
||||||
TitledPane globalStatsPane = createGlobalStatisticsPanel();
|
VBox globalStatsCard = createGlobalStatisticsPanel();
|
||||||
|
|
||||||
|
// Tables Container
|
||||||
|
HBox tablesContainer = new HBox(20);
|
||||||
|
tablesContainer.setAlignment(Pos.TOP_CENTER);
|
||||||
|
|
||||||
// Vehicle Type Statistics Panel
|
// Vehicle Type Statistics Panel
|
||||||
TitledPane vehicleTypePane = createVehicleTypePanel();
|
VBox vehicleTypeCard = createVehicleTypePanel();
|
||||||
|
HBox.setHgrow(vehicleTypeCard, Priority.ALWAYS);
|
||||||
|
|
||||||
// Intersection Statistics Panel
|
// Intersection Statistics Panel
|
||||||
TitledPane intersectionPane = createIntersectionPanel();
|
VBox intersectionCard = createIntersectionPanel();
|
||||||
|
HBox.setHgrow(intersectionCard, Priority.ALWAYS);
|
||||||
mainContent.getChildren().addAll(globalStatsPane, vehicleTypePane, intersectionPane);
|
|
||||||
|
tablesContainer.getChildren().addAll(vehicleTypeCard, intersectionCard);
|
||||||
|
|
||||||
|
mainContent.getChildren().addAll(globalStatsCard, tablesContainer);
|
||||||
|
|
||||||
return mainContent;
|
return mainContent;
|
||||||
}
|
}
|
||||||
|
|
||||||
private TitledPane createGlobalStatisticsPanel() {
|
private VBox createGlobalStatisticsPanel() {
|
||||||
|
VBox card = new VBox();
|
||||||
|
card.getStyleClass().add("card");
|
||||||
|
|
||||||
|
// Card Header
|
||||||
|
HBox cardHeader = new HBox();
|
||||||
|
cardHeader.getStyleClass().add("card-header");
|
||||||
|
Label cardTitle = new Label("Global Statistics");
|
||||||
|
cardTitle.getStyleClass().add("card-title");
|
||||||
|
cardHeader.getChildren().add(cardTitle);
|
||||||
|
|
||||||
|
// Card Content
|
||||||
GridPane grid = new GridPane();
|
GridPane grid = new GridPane();
|
||||||
grid.setPadding(new Insets(15));
|
grid.getStyleClass().add("card-content");
|
||||||
grid.setHgap(20);
|
grid.setHgap(40);
|
||||||
grid.setVgap(15);
|
grid.setVgap(15);
|
||||||
grid.setStyle("-fx-background-color: white; -fx-border-radius: 5;");
|
grid.setAlignment(Pos.CENTER);
|
||||||
|
|
||||||
// Initialize labels
|
// Initialize labels
|
||||||
lblVehiclesGenerated = createStatLabel("0");
|
lblVehiclesGenerated = createStatValueLabel("0");
|
||||||
lblVehiclesCompleted = createStatLabel("0");
|
lblVehiclesCompleted = createStatValueLabel("0");
|
||||||
lblVehiclesInTransit = createStatLabel("0");
|
lblVehiclesInTransit = createStatValueLabel("0");
|
||||||
lblAvgSystemTime = createStatLabel("0.00 ms");
|
lblAvgSystemTime = createStatValueLabel("0.00 s");
|
||||||
lblAvgWaitingTime = createStatLabel("0.00 ms");
|
lblAvgWaitingTime = createStatValueLabel("0.00 s");
|
||||||
|
|
||||||
// Add labels with descriptions
|
// Add labels with descriptions
|
||||||
addStatRow(grid, 0, "Total Vehicles Generated:", lblVehiclesGenerated);
|
addStatRow(grid, 0, 0, "Total Vehicles Generated", lblVehiclesGenerated);
|
||||||
addStatRow(grid, 1, "Total Vehicles Completed:", lblVehiclesCompleted);
|
addStatRow(grid, 1, 0, "Total Vehicles Completed", lblVehiclesCompleted);
|
||||||
addStatRow(grid, 2, "Vehicles In Transit:", lblVehiclesInTransit);
|
addStatRow(grid, 2, 0, "Vehicles In Transit", lblVehiclesInTransit);
|
||||||
addStatRow(grid, 3, "Average System Time:", lblAvgSystemTime);
|
addStatRow(grid, 0, 1, "Average System Time", lblAvgSystemTime);
|
||||||
addStatRow(grid, 4, "Average Waiting Time:", lblAvgWaitingTime);
|
addStatRow(grid, 1, 1, "Average Waiting Time", lblAvgWaitingTime);
|
||||||
|
|
||||||
TitledPane pane = new TitledPane("Global Statistics", grid);
|
card.getChildren().addAll(cardHeader, grid);
|
||||||
pane.setCollapsible(false);
|
return card;
|
||||||
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
|
||||||
|
|
||||||
return pane;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private TitledPane createVehicleTypePanel() {
|
private VBox createVehicleTypePanel() {
|
||||||
|
VBox card = new VBox();
|
||||||
|
card.getStyleClass().add("card");
|
||||||
|
|
||||||
|
// Card Header
|
||||||
|
HBox cardHeader = new HBox();
|
||||||
|
cardHeader.getStyleClass().add("card-header");
|
||||||
|
Label cardTitle = new Label("Vehicle Type Statistics");
|
||||||
|
cardTitle.getStyleClass().add("card-title");
|
||||||
|
cardHeader.getChildren().add(cardTitle);
|
||||||
|
|
||||||
|
// Table
|
||||||
vehicleTypeTable = new TableView<>();
|
vehicleTypeTable = new TableView<>();
|
||||||
vehicleTypeTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
vehicleTypeTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
||||||
vehicleTypeTable.setPrefHeight(200);
|
vehicleTypeTable.setPrefHeight(300);
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, String> typeCol = new TableColumn<>("Vehicle Type");
|
TableColumn<VehicleTypeRow, String> typeCol = new TableColumn<>("Vehicle Type");
|
||||||
typeCol.setCellValueFactory(new PropertyValueFactory<>("vehicleType"));
|
typeCol.setCellValueFactory(new PropertyValueFactory<>("vehicleType"));
|
||||||
typeCol.setPrefWidth(200);
|
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, Integer> countCol = new TableColumn<>("Count");
|
TableColumn<VehicleTypeRow, Integer> countCol = new TableColumn<>("Count");
|
||||||
countCol.setCellValueFactory(new PropertyValueFactory<>("count"));
|
countCol.setCellValueFactory(new PropertyValueFactory<>("count"));
|
||||||
countCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, String> avgWaitCol = new TableColumn<>("Avg Wait Time");
|
TableColumn<VehicleTypeRow, String> avgWaitCol = new TableColumn<>("Avg Wait Time");
|
||||||
avgWaitCol.setCellValueFactory(new PropertyValueFactory<>("avgWaitTime"));
|
avgWaitCol.setCellValueFactory(new PropertyValueFactory<>("avgWaitTime"));
|
||||||
avgWaitCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
vehicleTypeTable.getColumns().addAll(typeCol, countCol, avgWaitCol);
|
vehicleTypeTable.getColumns().addAll(typeCol, countCol, avgWaitCol);
|
||||||
|
|
||||||
TitledPane pane = new TitledPane("Vehicle Type Statistics", vehicleTypeTable);
|
card.getChildren().addAll(cardHeader, vehicleTypeTable);
|
||||||
pane.setCollapsible(false);
|
return card;
|
||||||
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
|
||||||
|
|
||||||
return pane;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private TitledPane createIntersectionPanel() {
|
private VBox createIntersectionPanel() {
|
||||||
|
VBox card = new VBox();
|
||||||
|
card.getStyleClass().add("card");
|
||||||
|
|
||||||
|
// Card Header
|
||||||
|
HBox cardHeader = new HBox();
|
||||||
|
cardHeader.getStyleClass().add("card-header");
|
||||||
|
Label cardTitle = new Label("Intersection Statistics");
|
||||||
|
cardTitle.getStyleClass().add("card-title");
|
||||||
|
cardHeader.getChildren().add(cardTitle);
|
||||||
|
|
||||||
|
// Table
|
||||||
intersectionTable = new TableView<>();
|
intersectionTable = new TableView<>();
|
||||||
intersectionTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
intersectionTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
||||||
intersectionTable.setPrefHeight(250);
|
intersectionTable.setPrefHeight(300);
|
||||||
|
|
||||||
TableColumn<IntersectionRow, String> idCol = new TableColumn<>("Intersection ID");
|
TableColumn<IntersectionRow, String> idCol = new TableColumn<>("Intersection ID");
|
||||||
idCol.setCellValueFactory(new PropertyValueFactory<>("intersectionId"));
|
idCol.setCellValueFactory(new PropertyValueFactory<>("intersectionId"));
|
||||||
idCol.setPrefWidth(200);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> arrivalsCol = new TableColumn<>("Total Arrivals");
|
TableColumn<IntersectionRow, Integer> arrivalsCol = new TableColumn<>("Total Arrivals");
|
||||||
arrivalsCol.setCellValueFactory(new PropertyValueFactory<>("arrivals"));
|
arrivalsCol.setCellValueFactory(new PropertyValueFactory<>("arrivals"));
|
||||||
arrivalsCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> departuresCol = new TableColumn<>("Total Departures");
|
TableColumn<IntersectionRow, Integer> departuresCol = new TableColumn<>("Total Departures");
|
||||||
departuresCol.setCellValueFactory(new PropertyValueFactory<>("departures"));
|
departuresCol.setCellValueFactory(new PropertyValueFactory<>("departures"));
|
||||||
departuresCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> queueCol = new TableColumn<>("Current Queue");
|
TableColumn<IntersectionRow, Integer> queueCol = new TableColumn<>("Current Queue");
|
||||||
queueCol.setCellValueFactory(new PropertyValueFactory<>("queueSize"));
|
queueCol.setCellValueFactory(new PropertyValueFactory<>("queueSize"));
|
||||||
queueCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
intersectionTable.getColumns().addAll(idCol, arrivalsCol, departuresCol, queueCol);
|
intersectionTable.getColumns().addAll(idCol, arrivalsCol, departuresCol, queueCol);
|
||||||
|
|
||||||
TitledPane pane = new TitledPane("Intersection Statistics", intersectionTable);
|
card.getChildren().addAll(cardHeader, intersectionTable);
|
||||||
pane.setCollapsible(false);
|
return card;
|
||||||
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
|
||||||
|
|
||||||
return pane;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private HBox createFooter() {
|
private HBox createFooter() {
|
||||||
HBox footer = new HBox(10);
|
HBox footer = new HBox(10);
|
||||||
footer.setPadding(new Insets(10, 20, 10, 20));
|
footer.getStyleClass().add("footer");
|
||||||
footer.setStyle("-fx-background-color: #34495e;");
|
|
||||||
footer.setAlignment(Pos.CENTER_LEFT);
|
footer.setAlignment(Pos.CENTER_LEFT);
|
||||||
|
|
||||||
Label statusLabel = new Label("Status:");
|
Label statusLabel = new Label("Status:");
|
||||||
statusLabel.setTextFill(Color.WHITE);
|
statusLabel.getStyleClass().add("footer-text");
|
||||||
statusLabel.setFont(Font.font("Arial", FontWeight.BOLD, 12));
|
statusLabel.setStyle("-fx-font-weight: bold;");
|
||||||
|
|
||||||
Circle statusIndicator = new Circle(6);
|
Circle statusIndicator = new Circle(6);
|
||||||
statusIndicator.setFill(Color.LIME);
|
statusIndicator.setFill(javafx.scene.paint.Color.LIME);
|
||||||
|
|
||||||
Label statusText = new Label("Connected and Receiving Data");
|
Label statusText = new Label("Connected and Receiving Data");
|
||||||
statusText.setTextFill(Color.WHITE);
|
statusText.getStyleClass().add("footer-text");
|
||||||
statusText.setFont(Font.font("Arial", 12));
|
|
||||||
|
|
||||||
lblLastUpdate = new Label("Last Update: --:--:--");
|
lblLastUpdate = new Label("Last Update: --:--:--");
|
||||||
lblLastUpdate.setTextFill(Color.web("#ecf0f1"));
|
lblLastUpdate.getStyleClass().add("footer-text");
|
||||||
lblLastUpdate.setFont(Font.font("Arial", 12));
|
|
||||||
|
|
||||||
Region spacer = new Region();
|
Region spacer = new Region();
|
||||||
HBox.setHgrow(spacer, Priority.ALWAYS);
|
HBox.setHgrow(spacer, Priority.ALWAYS);
|
||||||
|
|
||||||
footer.getChildren().addAll(statusLabel, statusIndicator, statusText, spacer, lblLastUpdate);
|
footer.getChildren().addAll(statusLabel, statusIndicator, statusText, spacer, lblLastUpdate);
|
||||||
|
|
||||||
return footer;
|
return footer;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Label createStatLabel(String initialValue) {
|
private Label createStatValueLabel(String initialValue) {
|
||||||
Label label = new Label(initialValue);
|
Label label = new Label(initialValue);
|
||||||
label.setFont(Font.font("Arial", FontWeight.BOLD, 20));
|
label.getStyleClass().add("stat-value");
|
||||||
label.setTextFill(Color.web("#2980b9"));
|
|
||||||
return label;
|
return label;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addStatRow(GridPane grid, int row, String description, Label valueLabel) {
|
private void addStatRow(GridPane grid, int row, int colGroup, String description, Label valueLabel) {
|
||||||
|
VBox container = new VBox(5);
|
||||||
|
container.setAlignment(Pos.CENTER_LEFT);
|
||||||
|
|
||||||
Label descLabel = new Label(description);
|
Label descLabel = new Label(description);
|
||||||
descLabel.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
|
descLabel.getStyleClass().add("stat-label");
|
||||||
descLabel.setTextFill(Color.web("#34495e"));
|
|
||||||
|
container.getChildren().addAll(descLabel, valueLabel);
|
||||||
grid.add(descLabel, 0, row);
|
|
||||||
grid.add(valueLabel, 1, row);
|
grid.add(container, colGroup, row);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void startPeriodicUpdates() {
|
private void startPeriodicUpdates() {
|
||||||
updateScheduler = Executors.newSingleThreadScheduledExecutor();
|
updateScheduler = Executors.newSingleThreadScheduledExecutor();
|
||||||
updateScheduler.scheduleAtFixedRate(() -> {
|
updateScheduler.scheduleAtFixedRate(() -> {
|
||||||
Platform.runLater(this::updateUI);
|
Platform.runLater(this::updateUI);
|
||||||
}, 0, 5, TimeUnit.SECONDS);
|
}, 0, 5, TimeUnit.SECONDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void updateUI() {
|
private void updateUI() {
|
||||||
// Update global statistics
|
// Update global statistics
|
||||||
lblVehiclesGenerated.setText(String.valueOf(statistics.getTotalVehiclesGenerated()));
|
lblVehiclesGenerated.setText(String.valueOf(statistics.getTotalVehiclesGenerated()));
|
||||||
lblVehiclesCompleted.setText(String.valueOf(statistics.getTotalVehiclesCompleted()));
|
lblVehiclesCompleted.setText(String.valueOf(statistics.getTotalVehiclesCompleted()));
|
||||||
lblVehiclesInTransit.setText(String.valueOf(
|
lblVehiclesInTransit.setText(String.valueOf(
|
||||||
statistics.getTotalVehiclesGenerated() - statistics.getTotalVehiclesCompleted()));
|
statistics.getTotalVehiclesGenerated() - statistics.getTotalVehiclesCompleted()));
|
||||||
lblAvgSystemTime.setText(String.format("%.2f ms", statistics.getAverageSystemTime()));
|
lblAvgSystemTime.setText(String.format("%.2f s", statistics.getAverageSystemTime() / 1000.0));
|
||||||
lblAvgWaitingTime.setText(String.format("%.2f ms", statistics.getAverageWaitingTime()));
|
lblAvgWaitingTime.setText(String.format("%.2f s", statistics.getAverageWaitingTime() / 1000.0));
|
||||||
lblLastUpdate.setText(String.format("Last Update: %tT", statistics.getLastUpdateTime()));
|
lblLastUpdate.setText(String.format("Last Update: %tT", statistics.getLastUpdateTime()));
|
||||||
|
|
||||||
// Update vehicle type table
|
// Update vehicle type table
|
||||||
vehicleTypeTable.getItems().clear();
|
vehicleTypeTable.getItems().clear();
|
||||||
for (VehicleType type : VehicleType.values()) {
|
for (VehicleType type : VehicleType.values()) {
|
||||||
int count = statistics.getVehicleTypeCount(type);
|
int count = statistics.getVehicleTypeCount(type);
|
||||||
double avgWait = statistics.getAverageWaitingTimeByType(type);
|
double avgWait = statistics.getAverageWaitingTimeByType(type);
|
||||||
vehicleTypeTable.getItems().add(new VehicleTypeRow(
|
vehicleTypeTable.getItems().add(new VehicleTypeRow(
|
||||||
type.toString(), count, String.format("%.2f ms", avgWait)));
|
type.toString(), count, String.format("%.2f s", avgWait / 1000.0)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update intersection table
|
// Update intersection table
|
||||||
intersectionTable.getItems().clear();
|
intersectionTable.getItems().clear();
|
||||||
Map<String, DashboardStatistics.IntersectionStats> intersectionStats =
|
Map<String, DashboardStatistics.IntersectionStats> intersectionStats = statistics.getAllIntersectionStats();
|
||||||
statistics.getAllIntersectionStats();
|
|
||||||
for (DashboardStatistics.IntersectionStats stats : intersectionStats.values()) {
|
for (DashboardStatistics.IntersectionStats stats : intersectionStats.values()) {
|
||||||
intersectionTable.getItems().add(new IntersectionRow(
|
intersectionTable.getItems().add(new IntersectionRow(
|
||||||
stats.getIntersectionId(),
|
stats.getIntersectionId(),
|
||||||
stats.getTotalArrivals(),
|
stats.getTotalArrivals(),
|
||||||
stats.getTotalDepartures(),
|
stats.getTotalDepartures(),
|
||||||
stats.getCurrentQueueSize()
|
stats.getCurrentQueueSize()));
|
||||||
));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void shutdown() {
|
private void shutdown() {
|
||||||
System.out.println("Shutting down Dashboard UI...");
|
System.out.println("Shutting down Dashboard UI...");
|
||||||
|
|
||||||
if (updateScheduler != null && !updateScheduler.isShutdown()) {
|
if (updateScheduler != null && !updateScheduler.isShutdown()) {
|
||||||
updateScheduler.shutdownNow();
|
updateScheduler.shutdownNow();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (server != null) {
|
if (server != null) {
|
||||||
server.stop();
|
server.stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
Platform.exit();
|
Platform.exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void showErrorAlert(String title, String message) {
|
private void showErrorAlert(String title, String message) {
|
||||||
Alert alert = new Alert(Alert.AlertType.ERROR);
|
Alert alert = new Alert(Alert.AlertType.ERROR);
|
||||||
alert.setTitle(title);
|
alert.setTitle(title);
|
||||||
@@ -335,44 +388,63 @@ public class DashboardUI extends Application {
|
|||||||
alert.setContentText(message);
|
alert.setContentText(message);
|
||||||
alert.showAndWait();
|
alert.showAndWait();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
launch(args);
|
launch(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inner classes for TableView data models
|
// Inner classes for TableView data models
|
||||||
public static class VehicleTypeRow {
|
public static class VehicleTypeRow {
|
||||||
private final String vehicleType;
|
private final String vehicleType;
|
||||||
private final int count;
|
private final int count;
|
||||||
private final String avgWaitTime;
|
private final String avgWaitTime;
|
||||||
|
|
||||||
public VehicleTypeRow(String vehicleType, int count, String avgWaitTime) {
|
public VehicleTypeRow(String vehicleType, int count, String avgWaitTime) {
|
||||||
this.vehicleType = vehicleType;
|
this.vehicleType = vehicleType;
|
||||||
this.count = count;
|
this.count = count;
|
||||||
this.avgWaitTime = avgWaitTime;
|
this.avgWaitTime = avgWaitTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getVehicleType() { return vehicleType; }
|
public String getVehicleType() {
|
||||||
public int getCount() { return count; }
|
return vehicleType;
|
||||||
public String getAvgWaitTime() { return avgWaitTime; }
|
}
|
||||||
|
|
||||||
|
public int getCount() {
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAvgWaitTime() {
|
||||||
|
return avgWaitTime;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class IntersectionRow {
|
public static class IntersectionRow {
|
||||||
private final String intersectionId;
|
private final String intersectionId;
|
||||||
private final int arrivals;
|
private final int arrivals;
|
||||||
private final int departures;
|
private final int departures;
|
||||||
private final int queueSize;
|
private final int queueSize;
|
||||||
|
|
||||||
public IntersectionRow(String intersectionId, int arrivals, int departures, int queueSize) {
|
public IntersectionRow(String intersectionId, int arrivals, int departures, int queueSize) {
|
||||||
this.intersectionId = intersectionId;
|
this.intersectionId = intersectionId;
|
||||||
this.arrivals = arrivals;
|
this.arrivals = arrivals;
|
||||||
this.departures = departures;
|
this.departures = departures;
|
||||||
this.queueSize = queueSize;
|
this.queueSize = queueSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getIntersectionId() { return intersectionId; }
|
public String getIntersectionId() {
|
||||||
public int getArrivals() { return arrivals; }
|
return intersectionId;
|
||||||
public int getDepartures() { return departures; }
|
}
|
||||||
public int getQueueSize() { return queueSize; }
|
|
||||||
|
public int getArrivals() {
|
||||||
|
return arrivals;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getDepartures() {
|
||||||
|
return departures;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getQueueSize() {
|
||||||
|
return queueSize;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
7
main/src/main/java/sd/dashboard/Launcher.java
Normal file
7
main/src/main/java/sd/dashboard/Launcher.java
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package sd.dashboard;
|
||||||
|
|
||||||
|
public class Launcher {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
DashboardUI.main(args);
|
||||||
|
}
|
||||||
|
}
|
||||||
112
main/src/main/java/sd/dashboard/SimulationProcessManager.java
Normal file
112
main/src/main/java/sd/dashboard/SimulationProcessManager.java
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
package sd.dashboard;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manages the lifecycle of simulation processes (Intersections, Exit Node,
|
||||||
|
* Coordinator).
|
||||||
|
* Allows starting and stopping the distributed simulation from within the Java
|
||||||
|
* application.
|
||||||
|
*/
|
||||||
|
public class SimulationProcessManager {
|
||||||
|
|
||||||
|
private final List<Process> runningProcesses;
|
||||||
|
private final String classpath;
|
||||||
|
|
||||||
|
public SimulationProcessManager() {
|
||||||
|
this.runningProcesses = new ArrayList<>();
|
||||||
|
this.classpath = System.getProperty("java.class.path");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the full simulation: 5 Intersections, 1 Exit Node, and 1 Coordinator.
|
||||||
|
*
|
||||||
|
* @throws IOException If a process fails to start.
|
||||||
|
*/
|
||||||
|
public void startSimulation() throws IOException {
|
||||||
|
if (!runningProcesses.isEmpty()) {
|
||||||
|
stopSimulation();
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("Starting simulation processes...");
|
||||||
|
|
||||||
|
// 1. Start Intersections (Cr1 - Cr5)
|
||||||
|
String[] intersectionIds = { "Cr1", "Cr2", "Cr3", "Cr4", "Cr5" };
|
||||||
|
for (String id : intersectionIds) {
|
||||||
|
startProcess("sd.IntersectionProcess", id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Start Exit Node
|
||||||
|
startProcess("sd.ExitNodeProcess", null);
|
||||||
|
|
||||||
|
// 3. Start Coordinator (Wait a bit for others to initialize)
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
startProcess("sd.coordinator.CoordinatorProcess", null);
|
||||||
|
|
||||||
|
System.out.println("All simulation processes started.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stops all running simulation processes.
|
||||||
|
*/
|
||||||
|
public void stopSimulation() {
|
||||||
|
System.out.println("Stopping simulation processes...");
|
||||||
|
|
||||||
|
for (Process process : runningProcesses) {
|
||||||
|
if (process.isAlive()) {
|
||||||
|
process.destroy(); // Try graceful termination first
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait a bit and force kill if necessary
|
||||||
|
try {
|
||||||
|
Thread.sleep(500);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Process process : runningProcesses) {
|
||||||
|
if (process.isAlive()) {
|
||||||
|
process.destroyForcibly();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runningProcesses.clear();
|
||||||
|
System.out.println("All simulation processes stopped.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper to start a single Java process.
|
||||||
|
*/
|
||||||
|
private void startProcess(String className, String arg) throws IOException {
|
||||||
|
String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
|
||||||
|
|
||||||
|
ProcessBuilder builder;
|
||||||
|
if (arg != null) {
|
||||||
|
builder = new ProcessBuilder(javaBin, "-cp", classpath, className, arg);
|
||||||
|
} else {
|
||||||
|
builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||||
|
}
|
||||||
|
|
||||||
|
// this is a linux thing - not sure about windows
|
||||||
|
String logName = className.substring(className.lastIndexOf('.') + 1) + (arg != null ? "-" + arg : "") + ".log";
|
||||||
|
File logFile = new File("/tmp/" + logName);
|
||||||
|
builder.redirectOutput(logFile);
|
||||||
|
builder.redirectError(logFile);
|
||||||
|
|
||||||
|
Process process = builder.start();
|
||||||
|
runningProcesses.add(process);
|
||||||
|
System.out.println("Started " + className + (arg != null ? " " + arg : ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isSimulationRunning() {
|
||||||
|
return !runningProcesses.isEmpty() && runningProcesses.stream().anyMatch(Process::isAlive);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import sd.IntersectionProcess;
|
|||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.model.TrafficLight;
|
import sd.model.TrafficLight;
|
||||||
import sd.model.TrafficLightState;
|
import sd.model.TrafficLightState;
|
||||||
import sd.model.Vehicle;
|
import sd.model.Vehicle;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implements the control logic for a single TrafficLight
|
* Implements the control logic for a single TrafficLight
|
||||||
@@ -16,7 +16,7 @@ public class TrafficLightThread implements Runnable {
|
|||||||
private final IntersectionProcess process;
|
private final IntersectionProcess process;
|
||||||
private final SimulationConfig config;
|
private final SimulationConfig config;
|
||||||
private volatile boolean running;
|
private volatile boolean running;
|
||||||
|
|
||||||
// Store the thread reference for proper interruption
|
// Store the thread reference for proper interruption
|
||||||
private Thread currentThread;
|
private Thread currentThread;
|
||||||
|
|
||||||
@@ -35,33 +35,31 @@ public class TrafficLightThread implements Runnable {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
while (running && !Thread.currentThread().isInterrupted()) {
|
while (running && !Thread.currentThread().isInterrupted()) {
|
||||||
|
|
||||||
// Request permission to turn green (blocks until granted)
|
// Request permission to turn green (blocks until granted)
|
||||||
process.requestGreenLight(light.getDirection());
|
process.requestGreenLight(light.getDirection());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// --- GREEN Phase ---
|
// --- GREEN Phase ---
|
||||||
light.changeState(TrafficLightState.GREEN);
|
light.changeState(TrafficLightState.GREEN);
|
||||||
System.out.println("[" + light.getId() + "] State: GREEN");
|
System.out.println("[" + light.getId() + "] State: GREEN");
|
||||||
|
|
||||||
processGreenLightQueue();
|
// Process queue for the duration of the green light
|
||||||
|
long greenDurationMs = (long) (light.getGreenTime() * 1000);
|
||||||
if (!running || Thread.currentThread().isInterrupted()) break;
|
processGreenLightQueue(greenDurationMs);
|
||||||
|
|
||||||
// Wait for green duration
|
if (!running || Thread.currentThread().isInterrupted())
|
||||||
Thread.sleep((long) (light.getGreenTime() * 1000));
|
break;
|
||||||
|
|
||||||
if (!running || Thread.currentThread().isInterrupted()) break;
|
|
||||||
|
|
||||||
// --- RED Phase ---
|
// --- RED Phase ---
|
||||||
light.changeState(TrafficLightState.RED);
|
light.changeState(TrafficLightState.RED);
|
||||||
System.out.println("[" + light.getId() + "] State: RED");
|
System.out.println("[" + light.getId() + "] State: RED");
|
||||||
|
|
||||||
} finally {
|
} finally {
|
||||||
// Always release the green light permission
|
// Always release the green light permission
|
||||||
process.releaseGreenLight(light.getDirection());
|
process.releaseGreenLight(light.getDirection());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait for red duration
|
// Wait for red duration
|
||||||
Thread.sleep((long) (light.getRedTime() * 1000));
|
Thread.sleep((long) (light.getRedTime() * 1000));
|
||||||
}
|
}
|
||||||
@@ -74,21 +72,34 @@ public class TrafficLightThread implements Runnable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void processGreenLightQueue() throws InterruptedException {
|
private void processGreenLightQueue(long greenDurationMs) throws InterruptedException {
|
||||||
while (running && !Thread.currentThread().isInterrupted()
|
long startTime = System.currentTimeMillis();
|
||||||
&& light.getState() == TrafficLightState.GREEN
|
|
||||||
&& light.getQueueSize() > 0) {
|
while (running && !Thread.currentThread().isInterrupted()
|
||||||
|
&& light.getState() == TrafficLightState.GREEN) {
|
||||||
Vehicle vehicle = light.removeVehicle();
|
|
||||||
|
// Check if green time has expired
|
||||||
if (vehicle != null) {
|
long elapsed = System.currentTimeMillis() - startTime;
|
||||||
double crossingTime = getCrossingTimeForVehicle(vehicle);
|
if (elapsed >= greenDurationMs) {
|
||||||
|
break;
|
||||||
Thread.sleep((long) (crossingTime * 1000));
|
}
|
||||||
|
|
||||||
vehicle.addCrossingTime(crossingTime);
|
if (light.getQueueSize() > 0) {
|
||||||
process.getIntersection().incrementVehiclesSent();
|
Vehicle vehicle = light.removeVehicle();
|
||||||
process.sendVehicleToNextDestination(vehicle);
|
|
||||||
|
if (vehicle != null) {
|
||||||
|
double crossingTime = getCrossingTimeForVehicle(vehicle);
|
||||||
|
long crossingTimeMs = (long) (crossingTime * 1000);
|
||||||
|
|
||||||
|
Thread.sleep(crossingTimeMs);
|
||||||
|
|
||||||
|
vehicle.addCrossingTime(crossingTime);
|
||||||
|
process.getIntersection().incrementVehiclesSent();
|
||||||
|
process.sendVehicleToNextDestination(vehicle);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Queue is empty, wait briefly for new vehicles or until time expires
|
||||||
|
Thread.sleep(50);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,131 +0,0 @@
|
|||||||
package sd.model;
|
|
||||||
|
|
||||||
import java.io.Serializable;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Represents a single event in the discrete event simulation.
|
|
||||||
* * An Event is the fundamental unit of action in the simulation. It contains:
|
|
||||||
* - A {@code timestamp} (when the event should occur).
|
|
||||||
* - A {@link EventType} (what kind of event it is).
|
|
||||||
* - Associated {@code data} (e.g., the {@link Vehicle} or {@link TrafficLight} involved).
|
|
||||||
* - An optional {@code location} (e.g., the ID of the {@link Intersection}).
|
|
||||||
* * Events are {@link Comparable}, allowing them to be sorted in a
|
|
||||||
* {@link java.util.PriorityQueue}. The primary sorting key is the
|
|
||||||
* {@code timestamp}. If timestamps are equal, {@code EventType} is used
|
|
||||||
* as a tie-breaker to ensure a consistent, deterministic order.
|
|
||||||
* * Implements {@link Serializable} so events could (in theory) be sent
|
|
||||||
* across a network in a distributed simulation.
|
|
||||||
*/
|
|
||||||
public class Event implements Comparable<Event>, Serializable {
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The simulation time (in seconds) when this event is scheduled to occur.
|
|
||||||
*/
|
|
||||||
private final double timestamp;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The type of event (e.g., VEHICLE_ARRIVAL, TRAFFIC_LIGHT_CHANGE).
|
|
||||||
*/
|
|
||||||
private final EventType type;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The data payload associated with this event.
|
|
||||||
* This could be a {@link Vehicle}, {@link TrafficLight}, or null.
|
|
||||||
*/
|
|
||||||
private final Object data;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The ID of the location where the event occurs (e.g., "Cr1").
|
|
||||||
* Can be null if the event is not location-specific (like VEHICLE_GENERATION).
|
|
||||||
*/
|
|
||||||
private final String location;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a new Event.
|
|
||||||
*
|
|
||||||
* @param timestamp The simulation time when the event occurs.
|
|
||||||
* @param type The {@link EventType} of the event.
|
|
||||||
* @param data The associated data (e.g., a Vehicle object).
|
|
||||||
* @param location The ID of the location (e.g., an Intersection ID).
|
|
||||||
*/
|
|
||||||
public Event(double timestamp, EventType type, Object data, String location) {
|
|
||||||
this.timestamp = timestamp;
|
|
||||||
this.type = type;
|
|
||||||
this.data = data;
|
|
||||||
this.location = location;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convenience constructor for an Event without a specific location.
|
|
||||||
*
|
|
||||||
* @param timestamp The simulation time when the event occurs.
|
|
||||||
* @param type The {@link EventType} of the event.
|
|
||||||
* @param data The associated data (e.g., a Vehicle object).
|
|
||||||
*/
|
|
||||||
public Event(double timestamp, EventType type, Object data) {
|
|
||||||
this(timestamp, type, data, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compares this event to another event for ordering.
|
|
||||||
* * Events are ordered primarily by {@link #timestamp} (ascending).
|
|
||||||
* If timestamps are identical, they are ordered by {@link #type} (alphabetical)
|
|
||||||
* to provide a stable, deterministic tie-breaking mechanism.
|
|
||||||
*
|
|
||||||
* @param other The other Event to compare against.
|
|
||||||
* @return A negative integer if this event comes before {@code other},
|
|
||||||
* zero if they are "equal" in sorting (though this is rare),
|
|
||||||
* or a positive integer if this event comes after {@code other}.
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public int compareTo(Event other) {
|
|
||||||
// Primary sort: timestamp (earlier events come first)
|
|
||||||
int cmp = Double.compare(this.timestamp, other.timestamp);
|
|
||||||
if (cmp == 0) {
|
|
||||||
// Tie-breaker: event type (ensures deterministic order)
|
|
||||||
return this.type.compareTo(other.type);
|
|
||||||
}
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Getters ---
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The simulation time when the event occurs.
|
|
||||||
*/
|
|
||||||
public double getTimestamp() {
|
|
||||||
return timestamp;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The {@link EventType} of the event.
|
|
||||||
*/
|
|
||||||
public EventType getType() {
|
|
||||||
return type;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The data payload (e.g., {@link Vehicle}, {@link TrafficLight}).
|
|
||||||
* The caller must cast this to the expected type.
|
|
||||||
*/
|
|
||||||
public Object getData() {
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The location ID (e.g., "Cr1"), or null if not applicable.
|
|
||||||
*/
|
|
||||||
public String getLocation() {
|
|
||||||
return location;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return A string representation of the event for logging.
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return String.format("Event{t=%.2f, type=%s, loc=%s}",
|
|
||||||
timestamp, type, location);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package sd.model;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Enumeration representing all possible event types in the discrete event simulation.
|
|
||||||
* These types are used by the {@link sd.engine.SimulationEngine} to determine
|
|
||||||
* how to process a given {@link Event}.
|
|
||||||
*/
|
|
||||||
public enum EventType {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fired when a {@link Vehicle} arrives at an {@link Intersection}.
|
|
||||||
* Data: {@link Vehicle}, Location: Intersection ID
|
|
||||||
*/
|
|
||||||
VEHICLE_ARRIVAL,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fired when a {@link TrafficLight} is scheduled to change its state.
|
|
||||||
* Data: {@link TrafficLight}, Location: Intersection ID
|
|
||||||
*/
|
|
||||||
TRAFFIC_LIGHT_CHANGE,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fired when a {@link Vehicle} begins to cross an {@link Intersection}.
|
|
||||||
* Data: {@link Vehicle}, Location: Intersection ID
|
|
||||||
*/
|
|
||||||
CROSSING_START,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fired when a {@link Vehicle} finishes crossing an {@link Intersection}.
|
|
||||||
* Data: {@link Vehicle}, Location: Intersection ID
|
|
||||||
*/
|
|
||||||
CROSSING_END,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fired when a new {@link Vehicle} should be created and added to the system.
|
|
||||||
* Data: null, Location: null
|
|
||||||
*/
|
|
||||||
VEHICLE_GENERATION,
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fired periodically to trigger the printing or sending of simulation statistics.
|
|
||||||
* Data: null, Location: null
|
|
||||||
*/
|
|
||||||
STATISTICS_UPDATE
|
|
||||||
}
|
|
||||||
@@ -12,7 +12,7 @@ import java.util.List;
|
|||||||
* - Its complete, pre-determined {@code route} (a list of intersection IDs).
|
* - Its complete, pre-determined {@code route} (a list of intersection IDs).
|
||||||
* - Its current position in the route ({@code currentRouteIndex}).
|
* - Its current position in the route ({@code currentRouteIndex}).
|
||||||
* - Metrics for total time spent waiting at red lights and time spent crossing.
|
* - Metrics for total time spent waiting at red lights and time spent crossing.
|
||||||
* * This object is passed around the simulation, primarily inside {@link Event}
|
* * This object is passed around the simulation, primarily inside message
|
||||||
* payloads and stored in {@link TrafficLight} queues.
|
* payloads and stored in {@link TrafficLight} queues.
|
||||||
* * Implements {@link Serializable} so it can be sent between processes
|
* * Implements {@link Serializable} so it can be sent between processes
|
||||||
* or nodes (e.g., over a socket in a distributed version of the simulation).
|
* or nodes (e.g., over a socket in a distributed version of the simulation).
|
||||||
@@ -21,28 +21,28 @@ public class Vehicle implements Serializable {
|
|||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
// --- Identity and configuration ---
|
// --- Identity and configuration ---
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unique identifier for the vehicle (e.g., "V1", "V2").
|
* Unique identifier for the vehicle (e.g., "V1", "V2").
|
||||||
*/
|
*/
|
||||||
private final String id;
|
private final String id;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The type of vehicle (BIKE, LIGHT, HEAVY).
|
* The type of vehicle (BIKE, LIGHT, HEAVY).
|
||||||
*/
|
*/
|
||||||
private final VehicleType type;
|
private final VehicleType type;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The simulation time (in seconds) when the vehicle was generated.
|
* The simulation time (in seconds) when the vehicle was generated.
|
||||||
*/
|
*/
|
||||||
private final double entryTime;
|
private final double entryTime;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The complete, ordered list of destinations (intersection IDs and the
|
* The complete, ordered list of destinations (intersection IDs and the
|
||||||
* final exit "S"). Example: ["Cr1", "Cr3", "S"].
|
* final exit "S"). Example: ["Cr1", "Cr3", "S"].
|
||||||
*/
|
*/
|
||||||
private final List<String> route;
|
private final List<String> route;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An index that tracks the vehicle's progress along its {@link #route}.
|
* An index that tracks the vehicle's progress along its {@link #route}.
|
||||||
* {@code route.get(currentRouteIndex)} is the vehicle's *current*
|
* {@code route.get(currentRouteIndex)} is the vehicle's *current*
|
||||||
@@ -51,13 +51,13 @@ public class Vehicle implements Serializable {
|
|||||||
private int currentRouteIndex;
|
private int currentRouteIndex;
|
||||||
|
|
||||||
// --- Metrics ---
|
// --- Metrics ---
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The total accumulated time (in seconds) this vehicle has spent
|
* The total accumulated time (in seconds) this vehicle has spent
|
||||||
* waiting at red lights.
|
* waiting at red lights.
|
||||||
*/
|
*/
|
||||||
private double totalWaitingTime;
|
private double totalWaitingTime;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The total accumulated time (in seconds) this vehicle has spent
|
* The total accumulated time (in seconds) this vehicle has spent
|
||||||
* actively crossing intersections.
|
* actively crossing intersections.
|
||||||
@@ -67,10 +67,11 @@ public class Vehicle implements Serializable {
|
|||||||
/**
|
/**
|
||||||
* Constructs a new Vehicle.
|
* Constructs a new Vehicle.
|
||||||
*
|
*
|
||||||
* @param id The unique ID for the vehicle.
|
* @param id The unique ID for the vehicle.
|
||||||
* @param type The {@link VehicleType}.
|
* @param type The {@link VehicleType}.
|
||||||
* @param entryTime The simulation time when the vehicle is created.
|
* @param entryTime The simulation time when the vehicle is created.
|
||||||
* @param route The complete list of destination IDs (e.t., ["Cr1", "Cr2", "S"]).
|
* @param route The complete list of destination IDs (e.t., ["Cr1", "Cr2",
|
||||||
|
* "S"]).
|
||||||
*/
|
*/
|
||||||
public Vehicle(String id, VehicleType type, double entryTime, List<String> route) {
|
public Vehicle(String id, VehicleType type, double entryTime, List<String> route) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
@@ -90,8 +91,8 @@ public class Vehicle implements Serializable {
|
|||||||
* to set its *next* destination before it is queued.
|
* to set its *next* destination before it is queued.
|
||||||
*
|
*
|
||||||
* @return {@code true} if there is still at least one more destination
|
* @return {@code true} if there is still at least one more destination
|
||||||
* in the route, {@code false} if the vehicle has passed its
|
* in the route, {@code false} if the vehicle has passed its
|
||||||
* final destination.
|
* final destination.
|
||||||
*/
|
*/
|
||||||
public boolean advanceRoute() {
|
public boolean advanceRoute() {
|
||||||
currentRouteIndex++;
|
currentRouteIndex++;
|
||||||
@@ -103,7 +104,7 @@ public class Vehicle implements Serializable {
|
|||||||
* the vehicle is heading towards.
|
* the vehicle is heading towards.
|
||||||
*
|
*
|
||||||
* @return The ID of the current destination (e.g., "Cr1"), or
|
* @return The ID of the current destination (e.g., "Cr1"), or
|
||||||
* {@code null} if the route is complete.
|
* {@code null} if the route is complete.
|
||||||
*/
|
*/
|
||||||
public String getCurrentDestination() {
|
public String getCurrentDestination() {
|
||||||
return (currentRouteIndex < route.size()) ? route.get(currentRouteIndex) : null;
|
return (currentRouteIndex < route.size()) ? route.get(currentRouteIndex) : null;
|
||||||
@@ -113,7 +114,7 @@ public class Vehicle implements Serializable {
|
|||||||
* Checks if the vehicle has completed its entire route.
|
* Checks if the vehicle has completed its entire route.
|
||||||
*
|
*
|
||||||
* @return {@code true} if the route index is at or past the end
|
* @return {@code true} if the route index is at or past the end
|
||||||
* of the route list, {@code false} otherwise.
|
* of the route list, {@code false} otherwise.
|
||||||
*/
|
*/
|
||||||
public boolean hasReachedEnd() {
|
public boolean hasReachedEnd() {
|
||||||
return currentRouteIndex >= route.size();
|
return currentRouteIndex >= route.size();
|
||||||
@@ -151,7 +152,8 @@ public class Vehicle implements Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The current index pointing to the vehicle's destination in its route list.
|
* @return The current index pointing to the vehicle's destination in its route
|
||||||
|
* list.
|
||||||
*/
|
*/
|
||||||
public int getCurrentRouteIndex() {
|
public int getCurrentRouteIndex() {
|
||||||
return currentRouteIndex;
|
return currentRouteIndex;
|
||||||
@@ -199,7 +201,7 @@ public class Vehicle implements Serializable {
|
|||||||
*
|
*
|
||||||
* @param currentTime The current simulation time.
|
* @param currentTime The current simulation time.
|
||||||
* @return The total elapsed time (in seconds) since the vehicle
|
* @return The total elapsed time (in seconds) since the vehicle
|
||||||
* was generated ({@code currentTime - entryTime}).
|
* was generated ({@code currentTime - entryTime}).
|
||||||
*/
|
*/
|
||||||
public double getTotalTravelTime(double currentTime) {
|
public double getTotalTravelTime(double currentTime) {
|
||||||
return currentTime - entryTime;
|
return currentTime - entryTime;
|
||||||
@@ -211,8 +213,7 @@ public class Vehicle implements Serializable {
|
|||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return String.format(
|
return String.format(
|
||||||
"Vehicle{id='%s', type=%s, next='%s', route=%s}",
|
"Vehicle{id='%s', type=%s, next='%s', route=%s}",
|
||||||
id, type, getCurrentDestination(), route
|
id, type, getCurrentDestination(), route);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,6 @@ import java.io.Closeable;
|
|||||||
import java.io.DataInputStream;
|
import java.io.DataInputStream;
|
||||||
import java.io.DataOutputStream;
|
import java.io.DataOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.net.ConnectException;
|
import java.net.ConnectException;
|
||||||
@@ -127,7 +126,7 @@ public class SocketConnection implements Closeable {
|
|||||||
* @param message The "envelope" (which contains the Vehicle) to be sent.
|
* @param message The "envelope" (which contains the Vehicle) to be sent.
|
||||||
* @throws IOException If writing to the stream fails or socket is not connected.
|
* @throws IOException If writing to the stream fails or socket is not connected.
|
||||||
*/
|
*/
|
||||||
public void sendMessage(MessageProtocol message) throws IOException {
|
public synchronized void sendMessage(MessageProtocol message) throws IOException {
|
||||||
if (socket == null || !socket.isConnected()) {
|
if (socket == null || !socket.isConnected()) {
|
||||||
throw new IOException("Socket is not connected");
|
throw new IOException("Socket is not connected");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,134 +0,0 @@
|
|||||||
package sd.serialization;
|
|
||||||
|
|
||||||
import sd.model.Message;
|
|
||||||
import sd.model.MessageType;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Demonstration of JSON serialization usage in the traffic simulation system.
|
|
||||||
*
|
|
||||||
* This class shows practical examples of how to use JSON (Gson) serialization
|
|
||||||
* for network communication between simulation processes.
|
|
||||||
*/
|
|
||||||
public class SerializationExample {
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
System.out.println("=== JSON Serialization Example ===\n");
|
|
||||||
|
|
||||||
// Create a sample vehicle
|
|
||||||
List<String> route = Arrays.asList("Cr1", "Cr2", "Cr5", "S");
|
|
||||||
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 10.5, route);
|
|
||||||
vehicle.addWaitingTime(2.3);
|
|
||||||
vehicle.addCrossingTime(1.2);
|
|
||||||
|
|
||||||
// Create a message containing the vehicle
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.VEHICLE_TRANSFER,
|
|
||||||
"Cr1",
|
|
||||||
"Cr2",
|
|
||||||
vehicle
|
|
||||||
);
|
|
||||||
|
|
||||||
// ===== JSON Serialization =====
|
|
||||||
demonstrateJsonSerialization(message);
|
|
||||||
|
|
||||||
// ===== Factory Usage =====
|
|
||||||
demonstrateFactoryUsage(message);
|
|
||||||
|
|
||||||
// ===== Performance Test =====
|
|
||||||
performanceTest(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void demonstrateJsonSerialization(Message message) {
|
|
||||||
System.out.println("--- JSON Serialization ---");
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Create JSON serializer with pretty printing for readability
|
|
||||||
MessageSerializer serializer = new JsonMessageSerializer(true);
|
|
||||||
|
|
||||||
// Serialize to bytes
|
|
||||||
byte[] data = serializer.serialize(message);
|
|
||||||
|
|
||||||
// Display the JSON
|
|
||||||
String json = new String(data);
|
|
||||||
System.out.println("Serialized JSON (" + data.length + " bytes):");
|
|
||||||
System.out.println(json);
|
|
||||||
|
|
||||||
// Deserialize back
|
|
||||||
Message deserialized = serializer.deserialize(data, Message.class);
|
|
||||||
System.out.println("\nDeserialized: " + deserialized);
|
|
||||||
System.out.println("✓ JSON serialization successful\n");
|
|
||||||
|
|
||||||
} catch (SerializationException e) {
|
|
||||||
System.err.println("❌ JSON serialization failed: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void demonstrateFactoryUsage(Message message) {
|
|
||||||
System.out.println("--- Using SerializerFactory ---");
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Get default serializer (JSON)
|
|
||||||
MessageSerializer serializer = SerializerFactory.createDefault();
|
|
||||||
System.out.println("Default serializer: " + serializer.getName());
|
|
||||||
|
|
||||||
// Use it
|
|
||||||
byte[] data = serializer.serialize(message);
|
|
||||||
Message deserialized = serializer.deserialize(data, Message.class);
|
|
||||||
|
|
||||||
System.out.println("Message type: " + deserialized.getType());
|
|
||||||
System.out.println("From: " + deserialized.getSenderId() +
|
|
||||||
" → To: " + deserialized.getDestinationId());
|
|
||||||
System.out.println("✓ Factory usage successful\n");
|
|
||||||
|
|
||||||
} catch (SerializationException e) {
|
|
||||||
System.err.println("❌ Factory usage failed: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void performanceTest(Message message) {
|
|
||||||
System.out.println("--- Performance Test ---");
|
|
||||||
|
|
||||||
int iterations = 1000;
|
|
||||||
|
|
||||||
try {
|
|
||||||
MessageSerializer compactSerializer = new JsonMessageSerializer(false);
|
|
||||||
MessageSerializer prettySerializer = new JsonMessageSerializer(true);
|
|
||||||
|
|
||||||
// Warm up
|
|
||||||
for (int i = 0; i < 100; i++) {
|
|
||||||
compactSerializer.serialize(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test compact JSON
|
|
||||||
long compactStart = System.nanoTime();
|
|
||||||
byte[] compactData = null;
|
|
||||||
for (int i = 0; i < iterations; i++) {
|
|
||||||
compactData = compactSerializer.serialize(message);
|
|
||||||
}
|
|
||||||
long compactTime = System.nanoTime() - compactStart;
|
|
||||||
|
|
||||||
// Test pretty JSON
|
|
||||||
byte[] prettyData = prettySerializer.serialize(message);
|
|
||||||
|
|
||||||
// Results
|
|
||||||
System.out.println("Iterations: " + iterations);
|
|
||||||
System.out.println("\nJSON Compact:");
|
|
||||||
System.out.println(" Size: " + compactData.length + " bytes");
|
|
||||||
System.out.println(" Time: " + (compactTime / 1_000_000.0) + " ms total");
|
|
||||||
System.out.println(" Avg: " + (compactTime / iterations / 1_000.0) + " μs/operation");
|
|
||||||
|
|
||||||
System.out.println("\nJSON Pretty-Print:");
|
|
||||||
System.out.println(" Size: " + prettyData.length + " bytes");
|
|
||||||
System.out.println(" Size increase: " +
|
|
||||||
String.format("%.1f%%", ((double)prettyData.length / compactData.length - 1) * 100));
|
|
||||||
|
|
||||||
} catch (SerializationException e) {
|
|
||||||
System.err.println("❌ Performance test failed: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,381 +0,0 @@
|
|||||||
package sd.util;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.model.Intersection;
|
|
||||||
import sd.model.Vehicle;
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Collects, manages, and reports statistics throughout the simulation.
|
|
||||||
* * This class acts as the central bookkeeper for simulation metrics. It
|
|
||||||
* tracks:
|
|
||||||
* - Overall system statistics (total vehicles, completion time, wait time).
|
|
||||||
* - Per-vehicle-type statistics (counts, average wait time by type).
|
|
||||||
* - Per-intersection statistics (arrivals, departures).
|
|
||||||
* * It also maintains "in-flight" data, such as the arrival time of a
|
|
||||||
* vehicle at its *current* intersection, which is necessary to
|
|
||||||
* calculate waiting time when the vehicle later departs.
|
|
||||||
*/
|
|
||||||
public class StatisticsCollector {
|
|
||||||
|
|
||||||
// --- Vehicle tracking (for in-flight vehicles) ---
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tracks the simulation time when a vehicle arrives at its *current*
|
|
||||||
* intersection.
|
|
||||||
* This is used later to calculate waiting time (Depart_Time - Arrive_Time).
|
|
||||||
* Key: Vehicle ID (String)
|
|
||||||
* Value: Arrival Time (Double)
|
|
||||||
*/
|
|
||||||
private final Map<String, Double> vehicleArrivalTimes;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tracks the sequence of intersections a vehicle has visited.
|
|
||||||
* Key: Vehicle ID (String)
|
|
||||||
* Value: List of Intersection IDs (String)
|
|
||||||
*/
|
|
||||||
private final Map<String, List<String>> vehicleIntersectionHistory;
|
|
||||||
|
|
||||||
// --- Overall system statistics ---
|
|
||||||
|
|
||||||
/** Total number of vehicles created by the {@link VehicleGenerator}. */
|
|
||||||
private int totalVehiclesGenerated;
|
|
||||||
|
|
||||||
/** Total number of vehicles that have reached their final destination ("S"). */
|
|
||||||
private int totalVehiclesCompleted;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The sum of all *completed* vehicles' total travel times. Used for averaging.
|
|
||||||
*/
|
|
||||||
private double totalSystemTime;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The sum of all *completed* vehicles' total waiting times. Used for averaging.
|
|
||||||
*/
|
|
||||||
private double totalWaitingTime;
|
|
||||||
|
|
||||||
// --- Per-vehicle-type statistics ---
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tracks the total number of vehicles generated, broken down by type.
|
|
||||||
* Key: {@link VehicleType}
|
|
||||||
* Value: Count (Integer)
|
|
||||||
*/
|
|
||||||
private final Map<VehicleType, Integer> vehicleTypeCount;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tracks the total waiting time, broken down by vehicle type.
|
|
||||||
* Key: {@link VehicleType}
|
|
||||||
* Value: Total Wait Time (Double)
|
|
||||||
*/
|
|
||||||
private final Map<VehicleType, Double> vehicleTypeWaitTime;
|
|
||||||
|
|
||||||
// --- Per-intersection statistics ---
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A map to hold statistics objects for each intersection.
|
|
||||||
* Key: Intersection ID (String)
|
|
||||||
* Value: {@link IntersectionStats} object
|
|
||||||
*/
|
|
||||||
private final Map<String, IntersectionStats> intersectionStats;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a new StatisticsCollector.
|
|
||||||
* Initializes all maps and counters.
|
|
||||||
*
|
|
||||||
* @param config The {@link SimulationConfig} (not currently used, but
|
|
||||||
* could be for configuration-dependent stats).
|
|
||||||
*/
|
|
||||||
public StatisticsCollector(SimulationConfig config) {
|
|
||||||
this.vehicleArrivalTimes = new HashMap<>();
|
|
||||||
this.vehicleIntersectionHistory = new HashMap<>();
|
|
||||||
this.totalVehiclesGenerated = 0;
|
|
||||||
this.totalVehiclesCompleted = 0;
|
|
||||||
this.totalSystemTime = 0.0;
|
|
||||||
this.totalWaitingTime = 0.0;
|
|
||||||
this.vehicleTypeCount = new HashMap<>();
|
|
||||||
this.vehicleTypeWaitTime = new HashMap<>();
|
|
||||||
this.intersectionStats = new HashMap<>();
|
|
||||||
|
|
||||||
// Initialize vehicle type counters to 0
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
vehicleTypeCount.put(type, 0);
|
|
||||||
vehicleTypeWaitTime.put(type, 0.0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records that a new vehicle has been generated.
|
|
||||||
* This is called by the vehicle generation component
|
|
||||||
* during a {@code VEHICLE_GENERATION} event.
|
|
||||||
*
|
|
||||||
* @param vehicle The {@link Vehicle} that was just created.
|
|
||||||
* @param currentTime The simulation time of the event.
|
|
||||||
*/
|
|
||||||
public void recordVehicleGeneration(Vehicle vehicle, double currentTime) {
|
|
||||||
totalVehiclesGenerated++;
|
|
||||||
|
|
||||||
// Track by vehicle type
|
|
||||||
VehicleType type = vehicle.getType();
|
|
||||||
vehicleTypeCount.put(type, vehicleTypeCount.get(type) + 1);
|
|
||||||
|
|
||||||
// Initialize history tracking for this vehicle
|
|
||||||
vehicleIntersectionHistory.put(vehicle.getId(), new ArrayList<>());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records that a vehicle has arrived at an intersection queue.
|
|
||||||
* This is called by the vehicle generation component
|
|
||||||
* during a {@code VEHICLE_ARRIVAL} event.
|
|
||||||
*
|
|
||||||
* @param vehicle The {@link Vehicle} that arrived.
|
|
||||||
* @param intersectionId The ID of the intersection it arrived at.
|
|
||||||
* @param currentTime The simulation time of the arrival.
|
|
||||||
*/
|
|
||||||
public void recordVehicleArrival(Vehicle vehicle, String intersectionId, double currentTime) {
|
|
||||||
// Store arrival time - this is the "start waiting" time
|
|
||||||
vehicleArrivalTimes.put(vehicle.getId(), currentTime);
|
|
||||||
|
|
||||||
// Track intersection history
|
|
||||||
List<String> history = vehicleIntersectionHistory.get(vehicle.getId());
|
|
||||||
if (history != null) {
|
|
||||||
history.add(intersectionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update per-intersection statistics
|
|
||||||
getOrCreateIntersectionStats(intersectionId).recordArrival();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records that a vehicle has completed its route and exited the system.
|
|
||||||
* This is where final metrics for the vehicle are aggregated.
|
|
||||||
* This is called by the vehicle generation component
|
|
||||||
* when a vehicle reaches destination "S".
|
|
||||||
*
|
|
||||||
* @param vehicle The {@link Vehicle} that is exiting.
|
|
||||||
* @param currentTime The simulation time of the exit.
|
|
||||||
*/
|
|
||||||
public void recordVehicleExit(Vehicle vehicle, double currentTime) {
|
|
||||||
totalVehiclesCompleted++;
|
|
||||||
|
|
||||||
// Calculate and aggregate total system time
|
|
||||||
double systemTime = vehicle.getTotalTravelTime(currentTime);
|
|
||||||
totalSystemTime += systemTime;
|
|
||||||
|
|
||||||
// Aggregate waiting time
|
|
||||||
double waitTime = vehicle.getTotalWaitingTime();
|
|
||||||
totalWaitingTime += waitTime;
|
|
||||||
|
|
||||||
// Aggregate waiting time by vehicle type
|
|
||||||
VehicleType type = vehicle.getType();
|
|
||||||
vehicleTypeWaitTime.put(type, vehicleTypeWaitTime.get(type) + waitTime);
|
|
||||||
|
|
||||||
// Clean up tracking maps to save memory
|
|
||||||
vehicleArrivalTimes.remove(vehicle.getId());
|
|
||||||
vehicleIntersectionHistory.remove(vehicle.getId());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the time a vehicle arrived at its *current* intersection.
|
|
||||||
* This is used by the intersection component to calculate
|
|
||||||
* wait time just before the vehicle crosses.
|
|
||||||
*
|
|
||||||
* @param vehicle The {@link Vehicle} to check.
|
|
||||||
* @return The arrival time, or 0.0 if not found.
|
|
||||||
*/
|
|
||||||
public double getArrivalTime(Vehicle vehicle) {
|
|
||||||
return vehicleArrivalTimes.getOrDefault(vehicle.getId(), 0.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Prints a "snapshot" of the current simulation statistics.
|
|
||||||
* This is called periodically by the simulation components
|
|
||||||
* during a {@code STATISTICS_UPDATE} event.
|
|
||||||
*
|
|
||||||
* @param intersections A map of all intersections (to get queue data).
|
|
||||||
* @param currentTime The current simulation time.
|
|
||||||
*/
|
|
||||||
public void printCurrentStatistics(Map<String, Intersection> intersections, double currentTime) {
|
|
||||||
System.out.printf("--- Statistics at t=%.2f ---%n", currentTime);
|
|
||||||
System.out.printf("Vehicles: Generated=%d, Completed=%d, In-System=%d%n",
|
|
||||||
totalVehiclesGenerated,
|
|
||||||
totalVehiclesCompleted,
|
|
||||||
totalVehiclesGenerated - totalVehiclesCompleted);
|
|
||||||
|
|
||||||
if (totalVehiclesCompleted > 0) {
|
|
||||||
System.out.printf("Average System Time (so far): %.2fs%n", totalSystemTime / totalVehiclesCompleted);
|
|
||||||
System.out.printf("Average Waiting Time (so far): %.2fs%n", totalWaitingTime / totalVehiclesCompleted);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Print per-intersection queue sizes
|
|
||||||
System.out.println("\nIntersection Queues:");
|
|
||||||
for (Map.Entry<String, Intersection> entry : intersections.entrySet()) {
|
|
||||||
String id = entry.getKey();
|
|
||||||
Intersection intersection = entry.getValue();
|
|
||||||
System.out.printf(" %s: Queue=%d, Received=%d, Sent=%d%n",
|
|
||||||
id,
|
|
||||||
intersection.getTotalQueueSize(),
|
|
||||||
intersection.getTotalVehiclesReceived(),
|
|
||||||
intersection.getTotalVehiclesSent());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Prints the final simulation summary statistics at the end of the run.
|
|
||||||
*
|
|
||||||
* @param intersections A map of all intersections.
|
|
||||||
* @param currentTime The final simulation time.
|
|
||||||
*/
|
|
||||||
public void printFinalStatistics(Map<String, Intersection> intersections, double currentTime) {
|
|
||||||
System.out.println("\n=== SIMULATION SUMMARY ===");
|
|
||||||
System.out.printf("Duration: %.2f seconds%n", currentTime);
|
|
||||||
System.out.printf("Total Vehicles Generated: %d%n", totalVehiclesGenerated);
|
|
||||||
System.out.printf("Total Vehicles Completed: %d%n", totalVehiclesCompleted);
|
|
||||||
System.out.printf("Vehicles Still in System: %d%n", totalVehiclesGenerated - totalVehiclesCompleted);
|
|
||||||
|
|
||||||
// Overall averages
|
|
||||||
if (totalVehiclesCompleted > 0) {
|
|
||||||
System.out.printf("%nAVERAGE METRICS (for completed vehicles):%n");
|
|
||||||
System.out.printf(" System Time: %.2f seconds%n", totalSystemTime / totalVehiclesCompleted);
|
|
||||||
System.out.printf(" Waiting Time: %.2f seconds%n", totalWaitingTime / totalVehiclesCompleted);
|
|
||||||
System.out.printf(" Throughput: %.2f vehicles/second%n", totalVehiclesCompleted / currentTime);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Vehicle type breakdown
|
|
||||||
System.out.println("\nVEHICLE TYPE DISTRIBUTION:");
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
int count = vehicleTypeCount.get(type);
|
|
||||||
if (count > 0) {
|
|
||||||
double percentage = (count * 100.0) / totalVehiclesGenerated;
|
|
||||||
// Calculate avg wait *only* for this type
|
|
||||||
// This assumes all generated vehicles of this type *completed*
|
|
||||||
// A more accurate way would be to track completed vehicle types
|
|
||||||
double avgWait = vehicleTypeWaitTime.get(type) / count;
|
|
||||||
System.out.printf(" %s: %d (%.1f%%), Avg Wait: %.2fs%n",
|
|
||||||
type, count, percentage, avgWait);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Per-intersection statistics
|
|
||||||
System.out.println("\nINTERSECTION STATISTICS:");
|
|
||||||
for (Map.Entry<String, Intersection> entry : intersections.entrySet()) {
|
|
||||||
String id = entry.getKey();
|
|
||||||
Intersection intersection = entry.getValue();
|
|
||||||
|
|
||||||
System.out.printf(" %s:%n", id);
|
|
||||||
System.out.printf(" Vehicles Received: %d%n", intersection.getTotalVehiclesReceived());
|
|
||||||
System.out.printf(" Vehicles Sent: %d%n", intersection.getTotalVehiclesSent());
|
|
||||||
System.out.printf(" Final Queue Size: %d%n", intersection.getTotalQueueSize());
|
|
||||||
|
|
||||||
// Traffic light details
|
|
||||||
intersection.getTrafficLights().forEach(light -> {
|
|
||||||
System.out.printf(" Light %s: State=%s, Queue=%d, Processed=%d%n",
|
|
||||||
light.getDirection(),
|
|
||||||
light.getState(),
|
|
||||||
light.getQueueSize(),
|
|
||||||
light.getTotalVehiclesProcessed());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// System health indicators
|
|
||||||
System.out.println("\nSYSTEM HEALTH:");
|
|
||||||
int totalQueuedVehicles = intersections.values().stream()
|
|
||||||
.mapToInt(Intersection::getTotalQueueSize)
|
|
||||||
.sum();
|
|
||||||
System.out.printf(" Total Queued Vehicles (at end): %d%n", totalQueuedVehicles);
|
|
||||||
|
|
||||||
if (totalVehiclesGenerated > 0) {
|
|
||||||
double completionRate = (totalVehiclesCompleted * 100.0) / totalVehiclesGenerated;
|
|
||||||
System.out.printf(" Completion Rate: %.1f%%%n", completionRate);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets or creates the statistics object for a given intersection.
|
|
||||||
* Uses {@code computeIfAbsent} for efficient, thread-safe-like instantiation.
|
|
||||||
*
|
|
||||||
* @param intersectionId The ID of the intersection.
|
|
||||||
* @return The {@link IntersectionStats} object for that ID.
|
|
||||||
*/
|
|
||||||
private IntersectionStats getOrCreateIntersectionStats(String intersectionId) {
|
|
||||||
// If 'intersectionId' is not in the map, create a new IntersectionStats()
|
|
||||||
// and put it in the map, then return it.
|
|
||||||
// Otherwise, just return the one that's already there.
|
|
||||||
return intersectionStats.computeIfAbsent(intersectionId, k -> new IntersectionStats());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Inner class to track per-intersection statistics.
|
|
||||||
* This is a simple data holder.
|
|
||||||
*/
|
|
||||||
private static class IntersectionStats {
|
|
||||||
private int totalArrivals;
|
|
||||||
private int totalDepartures;
|
|
||||||
|
|
||||||
public IntersectionStats() {
|
|
||||||
this.totalArrivals = 0;
|
|
||||||
this.totalDepartures = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void recordArrival() {
|
|
||||||
totalArrivals++;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalArrivals() {
|
|
||||||
return totalArrivals;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalDepartures() {
|
|
||||||
return totalDepartures;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Public Getters for Final Statistics ---
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return Total vehicles generated during the simulation.
|
|
||||||
*/
|
|
||||||
public int getTotalVehiclesGenerated() {
|
|
||||||
return totalVehiclesGenerated;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return Total vehicles that completed their route.
|
|
||||||
*/
|
|
||||||
public int getTotalVehiclesCompleted() {
|
|
||||||
return totalVehiclesCompleted;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The sum of all travel times for *completed* vehicles.
|
|
||||||
*/
|
|
||||||
public double getTotalSystemTime() {
|
|
||||||
return totalSystemTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The sum of all waiting times for *completed* vehicles.
|
|
||||||
*/
|
|
||||||
public double getTotalWaitingTime() {
|
|
||||||
return totalWaitingTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The average travel time for *completed* vehicles.
|
|
||||||
*/
|
|
||||||
public double getAverageSystemTime() {
|
|
||||||
return totalVehiclesCompleted > 0 ? totalSystemTime / totalVehiclesCompleted : 0.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The average waiting time for *completed* vehicles.
|
|
||||||
*/
|
|
||||||
public double getAverageWaitingTime() {
|
|
||||||
return totalVehiclesCompleted > 0 ? totalWaitingTime / totalVehiclesCompleted : 0.0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
142
main/src/main/resources/dashboard.css
Normal file
142
main/src/main/resources/dashboard.css
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
/* Global Styles */
|
||||||
|
.root {
|
||||||
|
-fx-background-color: #f4f7f6;
|
||||||
|
-fx-font-family: 'Segoe UI', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Header */
|
||||||
|
.header {
|
||||||
|
-fx-background-color: linear-gradient(to right, #2c3e50, #4ca1af);
|
||||||
|
-fx-padding: 20;
|
||||||
|
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 10, 0, 0, 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-title {
|
||||||
|
-fx-font-size: 28px;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
-fx-text-fill: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-subtitle {
|
||||||
|
-fx-font-size: 16px;
|
||||||
|
-fx-text-fill: #ecf0f1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.button-start {
|
||||||
|
-fx-background-color: #2ecc71;
|
||||||
|
-fx-text-fill: white;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
-fx-padding: 10 20;
|
||||||
|
-fx-background-radius: 5;
|
||||||
|
-fx-cursor: hand;
|
||||||
|
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-start:hover {
|
||||||
|
-fx-background-color: #27ae60;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-start:disabled {
|
||||||
|
-fx-background-color: #95a5a6;
|
||||||
|
-fx-opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-stop {
|
||||||
|
-fx-background-color: #e74c3c;
|
||||||
|
-fx-text-fill: white;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
-fx-padding: 10 20;
|
||||||
|
-fx-background-radius: 5;
|
||||||
|
-fx-cursor: hand;
|
||||||
|
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-stop:hover {
|
||||||
|
-fx-background-color: #c0392b;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-stop:disabled {
|
||||||
|
-fx-background-color: #95a5a6;
|
||||||
|
-fx-opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cards / Panels */
|
||||||
|
.card {
|
||||||
|
-fx-background-color: white;
|
||||||
|
-fx-background-radius: 8;
|
||||||
|
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.05), 10, 0, 0, 2);
|
||||||
|
-fx-padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
-fx-background-color: #ecf0f1;
|
||||||
|
-fx-background-radius: 8 8 0 0;
|
||||||
|
-fx-padding: 10 15;
|
||||||
|
-fx-border-color: #bdc3c7;
|
||||||
|
-fx-border-width: 0 0 1 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-title {
|
||||||
|
-fx-font-size: 16px;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
-fx-text-fill: #2c3e50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-content {
|
||||||
|
-fx-padding: 15;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Statistics Grid */
|
||||||
|
.stat-label {
|
||||||
|
-fx-font-size: 14px;
|
||||||
|
-fx-text-fill: #7f8c8d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-value {
|
||||||
|
-fx-font-size: 20px;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
-fx-text-fill: #2980b9;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tables */
|
||||||
|
.table-view {
|
||||||
|
-fx-background-color: transparent;
|
||||||
|
-fx-border-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-view .column-header-background {
|
||||||
|
-fx-background-color: #ecf0f1;
|
||||||
|
-fx-border-color: #bdc3c7;
|
||||||
|
-fx-border-width: 0 0 1 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-view .column-header .label {
|
||||||
|
-fx-text-fill: #2c3e50;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-row-cell {
|
||||||
|
-fx-background-color: white;
|
||||||
|
-fx-border-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-row-cell:odd {
|
||||||
|
-fx-background-color: #f9f9f9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-row-cell:selected {
|
||||||
|
-fx-background-color: #3498db;
|
||||||
|
-fx-text-fill: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Footer */
|
||||||
|
.footer {
|
||||||
|
-fx-background-color: #34495e;
|
||||||
|
-fx-padding: 10 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer-text {
|
||||||
|
-fx-text-fill: #ecf0f1;
|
||||||
|
-fx-font-size: 12px;
|
||||||
|
}
|
||||||
@@ -6,14 +6,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
|||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.model.Event;
|
|
||||||
import sd.model.EventType;
|
|
||||||
import sd.model.Intersection;
|
import sd.model.Intersection;
|
||||||
import sd.model.TrafficLight;
|
import sd.model.TrafficLight;
|
||||||
import sd.model.TrafficLightState;
|
import sd.model.TrafficLightState;
|
||||||
import sd.model.Vehicle;
|
import sd.model.Vehicle;
|
||||||
import sd.model.VehicleType;
|
import sd.model.VehicleType;
|
||||||
import sd.util.StatisticsCollector;
|
|
||||||
import sd.util.VehicleGenerator;
|
import sd.util.VehicleGenerator;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,16 +42,6 @@ class SimulationTest {
|
|||||||
assertTrue(!vehicle.getRoute().isEmpty());
|
assertTrue(!vehicle.getRoute().isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
void testEventOrdering() {
|
|
||||||
Event e1 = new Event(5.0, EventType.VEHICLE_ARRIVAL, null, "Cr1");
|
|
||||||
Event e2 = new Event(3.0, EventType.VEHICLE_ARRIVAL, null, "Cr2");
|
|
||||||
Event e3 = new Event(7.0, EventType.TRAFFIC_LIGHT_CHANGE, null, "Cr1");
|
|
||||||
|
|
||||||
assertTrue(e2.compareTo(e1) < 0); // e2 should come before e1
|
|
||||||
assertTrue(e1.compareTo(e3) < 0); // e1 should come before e3
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testIntersectionVehicleQueue() {
|
void testIntersectionVehicleQueue() {
|
||||||
Intersection intersection = new Intersection("TestCr");
|
Intersection intersection = new Intersection("TestCr");
|
||||||
@@ -92,20 +79,4 @@ class SimulationTest {
|
|||||||
// Removed testSimulationEngineInitialization as SimulationEngine has been
|
// Removed testSimulationEngineInitialization as SimulationEngine has been
|
||||||
// removed.
|
// removed.
|
||||||
|
|
||||||
@Test
|
|
||||||
void testStatisticsCollector() throws IOException {
|
|
||||||
SimulationConfig config = new SimulationConfig("src/main/resources/simulation.properties");
|
|
||||||
StatisticsCollector collector = new StatisticsCollector(config);
|
|
||||||
|
|
||||||
Vehicle v1 = new Vehicle("V1", VehicleType.LIGHT, 0.0,
|
|
||||||
java.util.Arrays.asList("Cr1", "Cr2", "S"));
|
|
||||||
|
|
||||||
collector.recordVehicleGeneration(v1, 0.0);
|
|
||||||
assertEquals(1, collector.getTotalVehiclesGenerated());
|
|
||||||
|
|
||||||
collector.recordVehicleArrival(v1, "Cr1", 1.0);
|
|
||||||
|
|
||||||
collector.recordVehicleExit(v1, 10.0);
|
|
||||||
assertEquals(1, collector.getTotalVehiclesCompleted());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ public class TrafficLightCoordinationTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testOnlyOneGreenLightAtATime() throws InterruptedException {
|
public void testOnlyOneGreenLightAtATime() throws InterruptedException {
|
||||||
System.out.println("\n=== Testing Traffic Light Mutual Exclusion ===");
|
System.out.println("\n=== Testing Traffic Light Mutual Exclusion ===");
|
||||||
|
|
||||||
// Start the intersection
|
// Start the intersection
|
||||||
Thread intersectionThread = new Thread(() -> {
|
Thread intersectionThread = new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
@@ -59,55 +59,55 @@ public class TrafficLightCoordinationTest {
|
|||||||
AtomicInteger maxGreenSimultaneously = new AtomicInteger(0);
|
AtomicInteger maxGreenSimultaneously = new AtomicInteger(0);
|
||||||
AtomicInteger violationCount = new AtomicInteger(0);
|
AtomicInteger violationCount = new AtomicInteger(0);
|
||||||
List<String> violations = new ArrayList<>();
|
List<String> violations = new ArrayList<>();
|
||||||
|
|
||||||
// Monitor for 10 seconds
|
// Monitor for 10 seconds
|
||||||
long endTime = System.currentTimeMillis() + 10000;
|
long endTime = System.currentTimeMillis() + 10000;
|
||||||
|
|
||||||
while (System.currentTimeMillis() < endTime) {
|
while (System.currentTimeMillis() < endTime) {
|
||||||
int greenCount = 0;
|
int greenCount = 0;
|
||||||
StringBuilder currentState = new StringBuilder("States: ");
|
StringBuilder currentState = new StringBuilder("States: ");
|
||||||
|
|
||||||
for (TrafficLight light : intersectionProcess.getIntersection().getTrafficLights()) {
|
for (TrafficLight light : intersectionProcess.getIntersection().getTrafficLights()) {
|
||||||
TrafficLightState state = light.getState();
|
TrafficLightState state = light.getState();
|
||||||
currentState.append(light.getDirection()).append("=").append(state).append(" ");
|
currentState.append(light.getDirection()).append("=").append(state).append(" ");
|
||||||
|
|
||||||
if (state == TrafficLightState.GREEN) {
|
if (state == TrafficLightState.GREEN) {
|
||||||
greenCount++;
|
greenCount++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update maximum simultaneous green lights
|
// Update maximum simultaneous green lights
|
||||||
if (greenCount > maxGreenSimultaneously.get()) {
|
if (greenCount > maxGreenSimultaneously.get()) {
|
||||||
maxGreenSimultaneously.set(greenCount);
|
maxGreenSimultaneously.set(greenCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for violations (more than one green)
|
// Check for violations (more than one green)
|
||||||
if (greenCount > 1) {
|
if (greenCount > 1) {
|
||||||
violationCount.incrementAndGet();
|
violationCount.incrementAndGet();
|
||||||
String violation = String.format("[VIOLATION] %d lights GREEN simultaneously: %s",
|
String violation = String.format("[VIOLATION] %d lights GREEN simultaneously: %s",
|
||||||
greenCount, currentState.toString());
|
greenCount, currentState.toString());
|
||||||
violations.add(violation);
|
violations.add(violation);
|
||||||
System.err.println(violation);
|
System.err.println(violation);
|
||||||
}
|
}
|
||||||
|
|
||||||
Thread.sleep(50); // Check every 50ms
|
Thread.sleep(50); // Check every 50ms
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println("\n=== Test Results ===");
|
System.out.println("\n=== Test Results ===");
|
||||||
System.out.println("Maximum simultaneous GREEN lights: " + maxGreenSimultaneously.get());
|
System.out.println("Maximum simultaneous GREEN lights: " + maxGreenSimultaneously.get());
|
||||||
System.out.println("Total violations detected: " + violationCount.get());
|
System.out.println("Total violations detected: " + violationCount.get());
|
||||||
|
|
||||||
if (!violations.isEmpty()) {
|
if (!violations.isEmpty()) {
|
||||||
System.err.println("\nViolation details:");
|
System.err.println("\nViolation details:");
|
||||||
violations.forEach(System.err::println);
|
violations.forEach(System.err::println);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Assert that we never had more than one green light
|
// Assert that we never had more than one green light
|
||||||
assertEquals(0, violationCount.get(),
|
assertEquals(0, violationCount.get(),
|
||||||
"Traffic light coordination violated! Multiple lights were GREEN simultaneously.");
|
"Traffic light coordination violated! Multiple lights were GREEN simultaneously.");
|
||||||
assertTrue(maxGreenSimultaneously.get() <= 1,
|
assertTrue(maxGreenSimultaneously.get() <= 1,
|
||||||
"At most ONE light should be GREEN at any time. Found: " + maxGreenSimultaneously.get());
|
"At most ONE light should be GREEN at any time. Found: " + maxGreenSimultaneously.get());
|
||||||
|
|
||||||
System.out.println("\nTraffic light coordination working correctly!");
|
System.out.println("\nTraffic light coordination working correctly!");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,7 +118,7 @@ public class TrafficLightCoordinationTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testAllLightsGetGreenTime() throws InterruptedException {
|
public void testAllLightsGetGreenTime() throws InterruptedException {
|
||||||
System.out.println("\n=== Testing Traffic Light Fairness ===");
|
System.out.println("\n=== Testing Traffic Light Fairness ===");
|
||||||
|
|
||||||
// Start the intersection
|
// Start the intersection
|
||||||
Thread intersectionThread = new Thread(() -> {
|
Thread intersectionThread = new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
@@ -132,10 +132,10 @@ public class TrafficLightCoordinationTest {
|
|||||||
// Track which lights have been green
|
// Track which lights have been green
|
||||||
List<TrafficLight> lights = intersectionProcess.getIntersection().getTrafficLights();
|
List<TrafficLight> lights = intersectionProcess.getIntersection().getTrafficLights();
|
||||||
boolean[] hasBeenGreen = new boolean[lights.size()];
|
boolean[] hasBeenGreen = new boolean[lights.size()];
|
||||||
|
|
||||||
// Monitor for 15 seconds (enough time for all lights to cycle)
|
// Monitor for 60 seconds (enough time for all lights to cycle: 18+18+12 = 48s)
|
||||||
long endTime = System.currentTimeMillis() + 15000;
|
long endTime = System.currentTimeMillis() + 60000;
|
||||||
|
|
||||||
while (System.currentTimeMillis() < endTime) {
|
while (System.currentTimeMillis() < endTime) {
|
||||||
for (int i = 0; i < lights.size(); i++) {
|
for (int i = 0; i < lights.size(); i++) {
|
||||||
if (lights.get(i).getState() == TrafficLightState.GREEN) {
|
if (lights.get(i).getState() == TrafficLightState.GREEN) {
|
||||||
@@ -145,16 +145,17 @@ public class TrafficLightCoordinationTest {
|
|||||||
}
|
}
|
||||||
Thread.sleep(100);
|
Thread.sleep(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if all lights got green time
|
// Check if all lights got green time
|
||||||
int greenCount = 0;
|
int greenCount = 0;
|
||||||
System.out.println("\n=== Fairness Results ===");
|
System.out.println("\n=== Fairness Results ===");
|
||||||
for (int i = 0; i < lights.size(); i++) {
|
for (int i = 0; i < lights.size(); i++) {
|
||||||
String status = hasBeenGreen[i] ? "✓ YES" : "✗ NO";
|
String status = hasBeenGreen[i] ? "✓ YES" : "✗ NO";
|
||||||
System.out.println(lights.get(i).getDirection() + " got GREEN time: " + status);
|
System.out.println(lights.get(i).getDirection() + " got GREEN time: " + status);
|
||||||
if (hasBeenGreen[i]) greenCount++;
|
if (hasBeenGreen[i])
|
||||||
|
greenCount++;
|
||||||
}
|
}
|
||||||
|
|
||||||
assertTrue(greenCount > 0, "At least one light should have been GREEN during the test");
|
assertTrue(greenCount > 0, "At least one light should have been GREEN during the test");
|
||||||
System.out.println("\n" + greenCount + "/" + lights.size() + " lights were GREEN during test period");
|
System.out.println("\n" + greenCount + "/" + lights.size() + " lights were GREEN during test period");
|
||||||
}
|
}
|
||||||
@@ -165,7 +166,7 @@ public class TrafficLightCoordinationTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testStateTransitionsAreConsistent() throws InterruptedException {
|
public void testStateTransitionsAreConsistent() throws InterruptedException {
|
||||||
System.out.println("\n=== Testing State Transition Consistency ===");
|
System.out.println("\n=== Testing State Transition Consistency ===");
|
||||||
|
|
||||||
Thread intersectionThread = new Thread(() -> {
|
Thread intersectionThread = new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
intersectionProcess.start();
|
intersectionProcess.start();
|
||||||
@@ -177,29 +178,29 @@ public class TrafficLightCoordinationTest {
|
|||||||
|
|
||||||
List<TrafficLight> lights = intersectionProcess.getIntersection().getTrafficLights();
|
List<TrafficLight> lights = intersectionProcess.getIntersection().getTrafficLights();
|
||||||
TrafficLightState[] previousStates = new TrafficLightState[lights.size()];
|
TrafficLightState[] previousStates = new TrafficLightState[lights.size()];
|
||||||
|
|
||||||
// Initialize previous states
|
// Initialize previous states
|
||||||
for (int i = 0; i < lights.size(); i++) {
|
for (int i = 0; i < lights.size(); i++) {
|
||||||
previousStates[i] = lights.get(i).getState();
|
previousStates[i] = lights.get(i).getState();
|
||||||
}
|
}
|
||||||
|
|
||||||
int transitionCount = 0;
|
int transitionCount = 0;
|
||||||
long endTime = System.currentTimeMillis() + 8000;
|
long endTime = System.currentTimeMillis() + 8000;
|
||||||
|
|
||||||
while (System.currentTimeMillis() < endTime) {
|
while (System.currentTimeMillis() < endTime) {
|
||||||
for (int i = 0; i < lights.size(); i++) {
|
for (int i = 0; i < lights.size(); i++) {
|
||||||
TrafficLightState currentState = lights.get(i).getState();
|
TrafficLightState currentState = lights.get(i).getState();
|
||||||
|
|
||||||
if (currentState != previousStates[i]) {
|
if (currentState != previousStates[i]) {
|
||||||
transitionCount++;
|
transitionCount++;
|
||||||
System.out.println(lights.get(i).getDirection() + " transitioned: " +
|
System.out.println(lights.get(i).getDirection() + " transitioned: " +
|
||||||
previousStates[i] + " → " + currentState);
|
previousStates[i] + " → " + currentState);
|
||||||
previousStates[i] = currentState;
|
previousStates[i] = currentState;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Thread.sleep(100);
|
Thread.sleep(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println("\nTotal state transitions observed: " + transitionCount);
|
System.out.println("\nTotal state transitions observed: " + transitionCount);
|
||||||
assertTrue(transitionCount > 0, "There should be state transitions during the test period");
|
assertTrue(transitionCount > 0, "There should be state transitions during the test period");
|
||||||
}
|
}
|
||||||
|
|||||||
1055
main/testing.txt
Normal file
1055
main/testing.txt
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user