mirror of
https://github.com/davidalves04/Trabalho-Pratico-SD.git
synced 2025-12-08 20:43:32 +00:00
Compare commits
1 Commits
v0.7.5
...
16-integra
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a31ac61a9a |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -48,6 +48,3 @@ build/
|
|||||||
# Other
|
# Other
|
||||||
*.swp
|
*.swp
|
||||||
*.pdf
|
*.pdf
|
||||||
|
|
||||||
# JAR built pom file
|
|
||||||
dependency-reduced-pom.xml
|
|
||||||
25
main/pom.xml
25
main/pom.xml
@@ -29,18 +29,6 @@
|
|||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>2.10.1</version>
|
<version>2.10.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- JavaFX for UI -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.openjfx</groupId>
|
|
||||||
<artifactId>javafx-controls</artifactId>
|
|
||||||
<version>17.0.2</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.openjfx</groupId>
|
|
||||||
<artifactId>javafx-fxml</artifactId>
|
|
||||||
<version>17.0.2</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@@ -51,16 +39,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.dashboard.DashboardUI</mainClass>
|
<mainClass>sd.Entry</mainClass>
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<!-- JavaFX Maven Plugin -->
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.openjfx</groupId>
|
|
||||||
<artifactId>javafx-maven-plugin</artifactId>
|
|
||||||
<version>0.0.8</version>
|
|
||||||
<configuration>
|
|
||||||
<mainClass>sd.dashboard.DashboardUI</mainClass>
|
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
@@ -76,7 +55,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.dashboard.DashboardUI</mainClass>
|
<mainClass>sd.Entry</mainClass>
|
||||||
</transformer>
|
</transformer>
|
||||||
</transformers>
|
</transformers>
|
||||||
</configuration>
|
</configuration>
|
||||||
|
|||||||
94
main/src/main/java/sd/Entry.java
Normal file
94
main/src/main/java/sd/Entry.java
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
package sd;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import sd.config.SimulationConfig;
|
||||||
|
import sd.engine.SimulationEngine;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main entry point for the traffic simulation.
|
||||||
|
* * This class is responsible for loading the simulation configuration,
|
||||||
|
* initializing the {@link SimulationEngine}, and starting the simulation run.
|
||||||
|
* It also prints initial configuration details and final execution time.
|
||||||
|
*/
|
||||||
|
public class Entry {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The default path to the simulation configuration file.
|
||||||
|
* This is used if no command-line arguments are provided.
|
||||||
|
*/
|
||||||
|
private static final String DEFAULT_CONFIG_FILE = "src/main/resources/simulation.properties";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The main method to start the simulation.
|
||||||
|
* * @param args Command-line arguments. If provided, args[0] is expected
|
||||||
|
* to be the path to a custom configuration file.
|
||||||
|
*/
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println("=".repeat(60));
|
||||||
|
System.out.println("TRAFFIC SIMULATION - DISCRETE EVENT SIMULATOR");
|
||||||
|
System.out.println("=".repeat(60));
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Load configuration
|
||||||
|
String configFile = args.length > 0 ? args[0] : DEFAULT_CONFIG_FILE;
|
||||||
|
System.out.println("Loading configuration from: " + configFile);
|
||||||
|
|
||||||
|
SimulationConfig config = new SimulationConfig(configFile);
|
||||||
|
|
||||||
|
// 2. Display configuration
|
||||||
|
displayConfiguration(config);
|
||||||
|
|
||||||
|
// 3. Create and initialize simulation engine
|
||||||
|
SimulationEngine engine = new SimulationEngine(config);
|
||||||
|
engine.initialize();
|
||||||
|
|
||||||
|
System.out.println("\n" + "=".repeat(60));
|
||||||
|
|
||||||
|
// 4. Run simulation
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
engine.run();
|
||||||
|
long endTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// 5. Display execution time
|
||||||
|
double executionTime = (endTime - startTime) / 1000.0;
|
||||||
|
System.out.println("\nExecution time: " + String.format("%.2f", executionTime) + " seconds");
|
||||||
|
System.out.println("=".repeat(60));
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("Error loading configuration: " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("Error during simulation: " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays the main configuration parameters to the console.
|
||||||
|
* This provides a summary of the simulation settings before it starts.
|
||||||
|
*
|
||||||
|
* @param config The {@link SimulationConfig} object containing the loaded settings.
|
||||||
|
*/
|
||||||
|
private static void displayConfiguration(SimulationConfig config) {
|
||||||
|
System.out.println("\nSIMULATION CONFIGURATION:");
|
||||||
|
System.out.println(" Duration: " + config.getSimulationDuration() + " seconds");
|
||||||
|
System.out.println(" Arrival Model: " + config.getArrivalModel());
|
||||||
|
|
||||||
|
if ("POISSON".equalsIgnoreCase(config.getArrivalModel())) {
|
||||||
|
System.out.println(" Arrival Rate (λ): " + config.getArrivalRate() + " vehicles/second");
|
||||||
|
} else {
|
||||||
|
System.out.println(" Fixed Interval: " + config.getFixedArrivalInterval() + " seconds");
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println(" Statistics Update Interval: " + config.getStatisticsUpdateInterval() + " seconds");
|
||||||
|
|
||||||
|
System.out.println("\nVEHICLE TYPES:");
|
||||||
|
System.out.println(" Bike: " + (config.getBikeVehicleProbability() * 100) + "% " +
|
||||||
|
"(crossing time: " + config.getBikeVehicleCrossingTime() + "s)");
|
||||||
|
System.out.println(" Light: " + (config.getLightVehicleProbability() * 100) + "% " +
|
||||||
|
"(crossing time: " + config.getLightVehicleCrossingTime() + "s)");
|
||||||
|
System.out.println(" Heavy: " + (config.getHeavyVehicleProbability() * 100) + "% " +
|
||||||
|
"(crossing time: " + config.getHeavyVehicleCrossingTime() + "s)");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,20 +11,18 @@ import java.util.concurrent.TimeUnit;
|
|||||||
|
|
||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.coordinator.SocketClient;
|
import sd.coordinator.SocketClient;
|
||||||
import sd.dashboard.StatsUpdatePayload;
|
|
||||||
import sd.model.Message;
|
import sd.model.Message;
|
||||||
import sd.model.MessageType;
|
import sd.model.MessageType;
|
||||||
import sd.model.Vehicle;
|
import sd.model.Vehicle;
|
||||||
import sd.model.VehicleType;
|
import sd.model.VehicleType;
|
||||||
import sd.protocol.MessageProtocol;
|
import sd.protocol.MessageProtocol;
|
||||||
import sd.protocol.SocketConnection;
|
import sd.protocol.SocketConnection;
|
||||||
|
import sd.serialization.SerializationException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Processo responsável pelo nó de saída do sistema de simulação de tráfego
|
* Processo responsável pelo nó de saída do sistema de simulação de tráfego distribuído.
|
||||||
* distribuído.
|
|
||||||
*
|
*
|
||||||
* Este processo representa o ponto final ("S") onde os veículos completam as
|
* Este processo representa o ponto final ("S") onde os veículos completam as suas rotas.
|
||||||
* suas rotas.
|
|
||||||
* As suas principais responsabilidades são:
|
* As suas principais responsabilidades são:
|
||||||
* - Receber veículos que terminam a sua rota vindos das interseções
|
* - Receber veículos que terminam a sua rota vindos das interseções
|
||||||
* - Calcular e agregar estatísticas finais dos veículos
|
* - Calcular e agregar estatísticas finais dos veículos
|
||||||
@@ -37,15 +35,9 @@ public class ExitNodeProcess {
|
|||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
private final ExecutorService connectionHandlerPool;
|
private final ExecutorService connectionHandlerPool;
|
||||||
|
|
||||||
/**
|
/** Flag para controlar a execução do processo (volatile para visibilidade entre threads) */
|
||||||
* Flag para controlar a execução do processo (volatile para visibilidade entre
|
|
||||||
* threads)
|
|
||||||
*/
|
|
||||||
private volatile boolean running;
|
private volatile boolean running;
|
||||||
|
|
||||||
/** Simulation start time (milliseconds) to calculate relative times */
|
|
||||||
private long simulationStartMillis;
|
|
||||||
|
|
||||||
/** Counter de veículos que completaram a rota */
|
/** Counter de veículos que completaram a rota */
|
||||||
private int totalVehiclesReceived;
|
private int totalVehiclesReceived;
|
||||||
|
|
||||||
@@ -103,12 +95,10 @@ public class ExitNodeProcess {
|
|||||||
/**
|
/**
|
||||||
* Constrói um novo processo de nó de saída.
|
* Constrói um novo processo de nó de saída.
|
||||||
*
|
*
|
||||||
* Inicializa todas as estruturas de dados necessárias para recolher
|
* Inicializa todas as estruturas de dados necessárias para recolher estatísticas
|
||||||
* estatísticas
|
|
||||||
* e configura o pool de threads para processar as ligações concorrentes.
|
* e configura o pool de threads para processar as ligações concorrentes.
|
||||||
*
|
*
|
||||||
* @param config Configuração da simulação contendo portas e endereços dos
|
* @param config Configuração da simulação contendo portas e endereços dos serviços
|
||||||
* serviços
|
|
||||||
*/
|
*/
|
||||||
public ExitNodeProcess(SimulationConfig config) {
|
public ExitNodeProcess(SimulationConfig config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
@@ -165,17 +155,15 @@ public class ExitNodeProcess {
|
|||||||
* 2. Aguarda pelas ligações das interseções
|
* 2. Aguarda pelas ligações das interseções
|
||||||
* 3. Delega cada ligação a uma thread da pool para processamento assíncrono
|
* 3. Delega cada ligação a uma thread da pool para processamento assíncrono
|
||||||
*
|
*
|
||||||
* @throws IOException Se o socket não puder ser criado ou houver erro na
|
* @throws IOException Se o socket não puder ser criado ou houver erro na aceitação
|
||||||
* aceitação
|
|
||||||
*/
|
*/
|
||||||
public void start() throws IOException {
|
public void start() throws IOException {
|
||||||
int port = config.getExitPort();
|
int port = config.getExitPort();
|
||||||
serverSocket = new ServerSocket(port);
|
serverSocket = new ServerSocket(port);
|
||||||
running = true;
|
running = true;
|
||||||
simulationStartMillis = System.currentTimeMillis();
|
|
||||||
|
|
||||||
System.out.println("Exit node started on port " + port);
|
System.out.println("Exit node started on port " + port);
|
||||||
System.out.println("Waiting for vehicles...\\n");
|
System.out.println("Waiting for vehicles...\n");
|
||||||
|
|
||||||
while (running) {
|
while (running) {
|
||||||
try {
|
try {
|
||||||
@@ -193,60 +181,33 @@ public class ExitNodeProcess {
|
|||||||
* Processa uma ligação recebida de uma interseção.
|
* Processa uma ligação recebida de uma interseção.
|
||||||
*
|
*
|
||||||
* Mantém a ligação aberta e processa continuamente mensagens do tipo
|
* Mantém a ligação aberta e processa continuamente mensagens do tipo
|
||||||
* VEHICLE_TRANSFER. Cada mensagem representa um veículo que chegou ao nó de
|
* VEHICLE_TRANSFER. Cada mensagem representa um veículo que chegou ao nó de saída.
|
||||||
* saída.
|
|
||||||
*
|
*
|
||||||
* @param clientSocket Socket da ligação estabelecida com a interseção
|
* @param clientSocket Socket da ligação estabelecida com a interseção
|
||||||
*/
|
*/
|
||||||
private void handleIncomingConnection(Socket clientSocket) {
|
private void handleIncomingConnection(Socket clientSocket) {
|
||||||
String clientAddress = clientSocket.getInetAddress().getHostAddress();
|
|
||||||
System.out.println("New connection accepted from " + clientAddress);
|
|
||||||
|
|
||||||
try (SocketConnection connection = new SocketConnection(clientSocket)) {
|
try (SocketConnection connection = new SocketConnection(clientSocket)) {
|
||||||
|
|
||||||
|
System.out.println("New connection accepted from " +
|
||||||
|
clientSocket.getInetAddress().getHostAddress());
|
||||||
|
|
||||||
while (running && connection.isConnected()) {
|
while (running && connection.isConnected()) {
|
||||||
try {
|
try {
|
||||||
System.out.println("[Exit] Waiting for message from " + clientAddress);
|
|
||||||
MessageProtocol message = connection.receiveMessage();
|
MessageProtocol message = connection.receiveMessage();
|
||||||
System.out.println("[Exit] Received message type: " + message.getType() +
|
|
||||||
" from " + message.getSourceNode());
|
|
||||||
|
|
||||||
if (message.getType() == MessageType.SIMULATION_START) {
|
|
||||||
// Coordinator sends start time - use it instead of our local start
|
|
||||||
simulationStartMillis = ((Number) message.getPayload()).longValue();
|
|
||||||
System.out.println("[Exit] Simulation start time synchronized");
|
|
||||||
} else if (message.getType() == MessageType.VEHICLE_TRANSFER) {
|
|
||||||
Object payload = message.getPayload();
|
|
||||||
System.out.println("[Exit] Payload type: " + payload.getClass().getName());
|
|
||||||
|
|
||||||
// Handle Gson LinkedHashMap
|
|
||||||
Vehicle vehicle;
|
|
||||||
if (payload instanceof com.google.gson.internal.LinkedTreeMap ||
|
|
||||||
payload instanceof java.util.LinkedHashMap) {
|
|
||||||
String json = new com.google.gson.Gson().toJson(payload);
|
|
||||||
vehicle = new com.google.gson.Gson().fromJson(json, Vehicle.class);
|
|
||||||
} else {
|
|
||||||
vehicle = (Vehicle) payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (message.getType() == MessageType.VEHICLE_TRANSFER) {
|
||||||
|
Vehicle vehicle = (Vehicle) message.getPayload();
|
||||||
processExitingVehicle(vehicle);
|
processExitingVehicle(vehicle);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (ClassNotFoundException e) {
|
} catch (ClassNotFoundException e) {
|
||||||
System.err.println("[Exit] Unknown message type: " + e.getMessage());
|
System.err.println("Unknown message type received: " + e.getMessage());
|
||||||
e.printStackTrace();
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("[Exit] Error processing message: " + e.getMessage());
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println("[Exit] Connection closed from " + clientAddress);
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
if (running) {
|
if (running) {
|
||||||
System.err.println("[Exit] Connection error from " + clientAddress + ": " + e.getMessage());
|
System.err.println("Connection error: " + e.getMessage());
|
||||||
e.printStackTrace();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -265,14 +226,10 @@ public class ExitNodeProcess {
|
|||||||
private synchronized void processExitingVehicle(Vehicle vehicle) {
|
private synchronized void processExitingVehicle(Vehicle vehicle) {
|
||||||
totalVehiclesReceived++;
|
totalVehiclesReceived++;
|
||||||
|
|
||||||
// Calculate relative simulation time (seconds since simulation start)
|
double systemTime = vehicle.getTotalTravelTime(getCurrentTime());
|
||||||
double currentSimTime = (System.currentTimeMillis() - simulationStartMillis) / 1000.0;
|
|
||||||
// System time = time vehicle spent in system (current time - entry time)
|
|
||||||
double systemTime = currentSimTime - vehicle.getEntryTime();
|
|
||||||
double waitTime = vehicle.getTotalWaitingTime();
|
double waitTime = vehicle.getTotalWaitingTime();
|
||||||
double crossingTime = vehicle.getTotalCrossingTime();
|
double crossingTime = vehicle.getTotalCrossingTime();
|
||||||
|
|
||||||
// Store times in seconds, will be converted to ms when sending to dashboard
|
|
||||||
totalSystemTime += systemTime;
|
totalSystemTime += systemTime;
|
||||||
totalWaitingTime += waitTime;
|
totalWaitingTime += waitTime;
|
||||||
totalCrossingTime += crossingTime;
|
totalCrossingTime += crossingTime;
|
||||||
@@ -281,12 +238,25 @@ public class ExitNodeProcess {
|
|||||||
vehicleTypeCount.put(type, vehicleTypeCount.get(type) + 1);
|
vehicleTypeCount.put(type, vehicleTypeCount.get(type) + 1);
|
||||||
vehicleTypeWaitTime.put(type, vehicleTypeWaitTime.get(type) + waitTime);
|
vehicleTypeWaitTime.put(type, vehicleTypeWaitTime.get(type) + waitTime);
|
||||||
|
|
||||||
System.out.printf("[Exit] Vehicle %s completed (type=%s, system_time=%.2fs, wait=%.2fs, crossing=%.2fs)%n",
|
System.out.printf("[Exit] Vehicle %s completed (type=%s, system_time=%.2fs, wait=%.2fs)%n",
|
||||||
vehicle.getId(), vehicle.getType(), systemTime, waitTime, crossingTime);
|
vehicle.getId(), vehicle.getType(), systemTime, waitTime);
|
||||||
|
|
||||||
// Send stats after every vehicle to ensure dashboard updates quickly
|
if (totalVehiclesReceived % 10 == 0) {
|
||||||
sendStatsToDashboard();
|
sendStatsToDashboard();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtém o tempo atual da simulação em segundos.
|
||||||
|
*
|
||||||
|
* @return Tempo atual em segundos desde "epoch"
|
||||||
|
*
|
||||||
|
* "Epoch" é um ponto de referência temporal Unix (1 de janeiro de 1970).
|
||||||
|
* Este método retorna os segundos decorridos desde esse momento.
|
||||||
|
*/
|
||||||
|
private double getCurrentTime() {
|
||||||
|
return System.currentTimeMillis() / 1000.0;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Envia as estatísticas para o dashboard.
|
* Envia as estatísticas para o dashboard.
|
||||||
@@ -303,46 +273,32 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Create stats payload
|
Map<String, Object> stats = new HashMap<>();
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload();
|
stats.put("totalVehicles", totalVehiclesReceived);
|
||||||
|
stats.put("avgSystemTime", totalVehiclesReceived > 0 ? totalSystemTime / totalVehiclesReceived : 0.0);
|
||||||
// Set global stats - convert seconds to milliseconds
|
stats.put("avgWaitingTime", totalVehiclesReceived > 0 ? totalWaitingTime / totalVehiclesReceived : 0.0);
|
||||||
payload.setTotalVehiclesCompleted(totalVehiclesReceived);
|
stats.put("avgCrossingTime", totalVehiclesReceived > 0 ? totalCrossingTime / totalVehiclesReceived : 0.0);
|
||||||
payload.setTotalSystemTime((long) (totalSystemTime * 1000.0)); // s -> ms
|
|
||||||
payload.setTotalWaitingTime((long) (totalWaitingTime * 1000.0)); // s -> ms
|
|
||||||
|
|
||||||
// Set intersection-like stats so it shows up correctly in the dashboard table
|
|
||||||
payload.setIntersectionArrivals(totalVehiclesReceived);
|
|
||||||
payload.setIntersectionDepartures(totalVehiclesReceived);
|
|
||||||
payload.setIntersectionQueueSize(0);
|
|
||||||
|
|
||||||
// Set vehicle type stats
|
|
||||||
Map<VehicleType, Integer> typeCounts = new HashMap<>();
|
|
||||||
Map<VehicleType, Long> typeWaitTimes = new HashMap<>();
|
|
||||||
|
|
||||||
|
Map<String, Integer> typeCounts = new HashMap<>();
|
||||||
|
Map<String, Double> typeAvgWait = new HashMap<>();
|
||||||
for (VehicleType type : VehicleType.values()) {
|
for (VehicleType type : VehicleType.values()) {
|
||||||
typeCounts.put(type, vehicleTypeCount.get(type));
|
int count = vehicleTypeCount.get(type);
|
||||||
typeWaitTimes.put(type, (long) (vehicleTypeWaitTime.get(type) * 1000.0)); // s -> ms
|
typeCounts.put(type.name(), count);
|
||||||
|
if (count > 0) {
|
||||||
|
typeAvgWait.put(type.name(), vehicleTypeWaitTime.get(type) / count);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
stats.put("vehicleTypeCounts", typeCounts);
|
||||||
|
stats.put("vehicleTypeAvgWait", typeAvgWait);
|
||||||
|
|
||||||
payload.setVehicleTypeCounts(typeCounts);
|
Message message = new Message(MessageType.STATS_UPDATE, "ExitNode", "Dashboard", stats);
|
||||||
payload.setVehicleTypeWaitTimes(typeWaitTimes);
|
|
||||||
|
|
||||||
// Send message
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.STATS_UPDATE,
|
|
||||||
"ExitNode",
|
|
||||||
"Dashboard",
|
|
||||||
payload);
|
|
||||||
|
|
||||||
dashboardClient.send(message);
|
dashboardClient.send(message);
|
||||||
|
|
||||||
double avgWait = totalVehiclesReceived > 0 ? totalWaitingTime / totalVehiclesReceived : 0.0;
|
|
||||||
System.out.printf("[Exit] Sent stats to dashboard (total=%d, avg_wait=%.2fs)%n",
|
System.out.printf("[Exit] Sent stats to dashboard (total=%d, avg_wait=%.2fs)%n",
|
||||||
totalVehiclesReceived, avgWait);
|
totalVehiclesReceived, totalWaitingTime / totalVehiclesReceived);
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (SerializationException | IOException e) {
|
||||||
System.err.println("[Exit] Failed to send stats to dashboard: " + e.getMessage());
|
System.err.println("Failed to send stats to dashboard: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,32 +4,25 @@ import java.io.IOException;
|
|||||||
import java.net.ServerSocket;
|
import java.net.ServerSocket;
|
||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
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;
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.coordinator.SocketClient;
|
|
||||||
import sd.dashboard.StatsUpdatePayload;
|
|
||||||
import sd.engine.TrafficLightThread;
|
import sd.engine.TrafficLightThread;
|
||||||
import sd.model.Intersection;
|
import sd.model.Intersection;
|
||||||
import sd.model.Message;
|
|
||||||
import sd.model.MessageType;
|
import sd.model.MessageType;
|
||||||
import sd.model.TrafficLight;
|
import sd.model.TrafficLight;
|
||||||
import sd.model.Vehicle;
|
import sd.model.Vehicle;
|
||||||
import sd.protocol.MessageProtocol;
|
import sd.protocol.MessageProtocol;
|
||||||
import sd.protocol.SocketConnection;
|
import sd.protocol.SocketConnection;
|
||||||
import sd.serialization.SerializationException;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Main class for an Intersection Process in the distributed traffic simulation.
|
* Main class for an Intersection Process in the distributed traffic simulation.
|
||||||
* * Each IntersectionProcess runs as an independent Java application (JVM
|
* * Each IntersectionProcess runs as an independent Java application (JVM instance)
|
||||||
* instance)
|
|
||||||
* representing one of the five intersections (Cr1-Cr5) in the network.
|
* representing one of the five intersections (Cr1-Cr5) in the network.
|
||||||
*/
|
*/
|
||||||
public class IntersectionProcess {
|
public class IntersectionProcess {
|
||||||
@@ -48,16 +41,13 @@ 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
|
||||||
|
//threads veem a mudança imediatamente.
|
||||||
private volatile boolean running; // Quando uma thread escreve um valor volatile, todas as outras
|
|
||||||
// threads veem a mudança imediatamente.
|
|
||||||
|
|
||||||
// Traffic Light Coordination
|
// Traffic Light Coordination
|
||||||
/**
|
/**
|
||||||
* Lock to ensure mutual exclusion between traffic lights.
|
* Lock to ensure mutual exclusion between traffic lights.
|
||||||
* Only one traffic light can be green at any given time within this
|
* Only one traffic light can be green at any given time within this intersection.
|
||||||
* intersection.
|
|
||||||
*/
|
*/
|
||||||
private final Lock trafficCoordinationLock;
|
private final Lock trafficCoordinationLock;
|
||||||
|
|
||||||
@@ -67,10 +57,6 @@ public class IntersectionProcess {
|
|||||||
*/
|
*/
|
||||||
private volatile String currentGreenDirection;
|
private volatile String currentGreenDirection;
|
||||||
|
|
||||||
private SocketClient dashboardClient;
|
|
||||||
private volatile int totalArrivals = 0;
|
|
||||||
private volatile int totalDepartures = 0;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new IntersectionProcess.
|
* Constructs a new IntersectionProcess.
|
||||||
*
|
*
|
||||||
@@ -85,9 +71,8 @@ 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(true); // Fair lock to prevent starvation
|
this.trafficCoordinationLock = new ReentrantLock();
|
||||||
this.currentGreenDirection = null;
|
this.currentGreenDirection = null;
|
||||||
|
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
@@ -95,35 +80,6 @@ public class IntersectionProcess {
|
|||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main entry point for running an intersection process
|
|
||||||
public static void main(String[] args) {
|
|
||||||
if (args.length < 1) {
|
|
||||||
System.err.println("Usage: java IntersectionProcess <intersectionId> [configFile]");
|
|
||||||
System.err.println("Example: java IntersectionProcess Cr1");
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
String intersectionId = args[0];
|
|
||||||
String configFile = args.length > 1 ? args[1] : "src/main/resources/simulation.properties";
|
|
||||||
|
|
||||||
try {
|
|
||||||
IntersectionProcess process = new IntersectionProcess(intersectionId, configFile);
|
|
||||||
process.initialize();
|
|
||||||
process.start();
|
|
||||||
|
|
||||||
// Add shutdown hook
|
|
||||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
|
||||||
System.out.println("\nShutdown signal received...");
|
|
||||||
process.shutdown();
|
|
||||||
}));
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Failed to start intersection process: " + e.getMessage());
|
|
||||||
e.printStackTrace();
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void initialize() {
|
public void initialize() {
|
||||||
System.out.println("\n[" + intersectionId + "] Initializing intersection...");
|
System.out.println("\n[" + intersectionId + "] Initializing intersection...");
|
||||||
|
|
||||||
@@ -131,50 +87,34 @@ public class IntersectionProcess {
|
|||||||
|
|
||||||
configureRouting();
|
configureRouting();
|
||||||
|
|
||||||
connectToDashboard();
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Initialization complete.");
|
System.out.println("[" + intersectionId + "] Initialization complete.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Establishes connection to the dashboard server for statistics reporting.
|
* Creates traffic lights for this intersection based on its physical connections.
|
||||||
*/
|
|
||||||
private void connectToDashboard() {
|
|
||||||
try {
|
|
||||||
String dashboardHost = config.getDashboardHost();
|
|
||||||
int dashboardPort = config.getDashboardPort();
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Connecting to dashboard at " +
|
|
||||||
dashboardHost + ":" + dashboardPort + "...");
|
|
||||||
|
|
||||||
dashboardClient = new SocketClient(intersectionId, dashboardHost, dashboardPort);
|
|
||||||
dashboardClient.connect();
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Connected to dashboard.");
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to connect to dashboard: " +
|
|
||||||
e.getMessage());
|
|
||||||
System.err.println("[" + intersectionId + "] Will continue without dashboard reporting.");
|
|
||||||
dashboardClient = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates traffic lights for this intersection based on its physical
|
|
||||||
* connections.
|
|
||||||
* Each intersection has different number and directions of traffic lights
|
* Each intersection has different number and directions of traffic lights
|
||||||
* according to the network topology.
|
* according to the network topology.
|
||||||
*/
|
*/
|
||||||
private void createTrafficLights() {
|
private void createTrafficLights() {
|
||||||
System.out.println("\n[" + intersectionId + "] Creating traffic lights...");
|
System.out.println("\n[" + intersectionId + "] Creating traffic lights...");
|
||||||
|
|
||||||
SimulationConfig.IntersectionConfig intersectionConfig = getIntersectionConfig();
|
String[] directions = new String[0];
|
||||||
List<String> directions = intersectionConfig.getLights();
|
switch (intersectionId) {
|
||||||
|
case "Cr1":
|
||||||
if (directions == null || directions.isEmpty()) {
|
directions = new String[]{"East", "South"};
|
||||||
System.err.println(" Warning: No traffic lights configured for " + intersectionId);
|
break;
|
||||||
return;
|
case "Cr2":
|
||||||
|
directions = new String[]{"West", "East", "South"};
|
||||||
|
break;
|
||||||
|
case "Cr3":
|
||||||
|
directions = new String[]{"West", "South"};
|
||||||
|
break;
|
||||||
|
case "Cr4":
|
||||||
|
directions = new String[]{"East"};
|
||||||
|
break;
|
||||||
|
case "Cr5":
|
||||||
|
directions = new String[]{"East"};
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (String direction : directions) {
|
for (String direction : directions) {
|
||||||
@@ -185,7 +125,8 @@ public class IntersectionProcess {
|
|||||||
intersectionId + "-" + direction,
|
intersectionId + "-" + direction,
|
||||||
direction,
|
direction,
|
||||||
greenTime,
|
greenTime,
|
||||||
redTime);
|
redTime
|
||||||
|
);
|
||||||
|
|
||||||
intersection.addTrafficLight(light);
|
intersection.addTrafficLight(light);
|
||||||
System.out.println(" Created traffic light: " + direction +
|
System.out.println(" Created traffic light: " + direction +
|
||||||
@@ -193,59 +134,41 @@ public class IntersectionProcess {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private SimulationConfig.IntersectionConfig getIntersectionConfig() {
|
|
||||||
if (config.getNetworkConfig() == null || config.getNetworkConfig().getIntersections() == null) {
|
|
||||||
throw new RuntimeException("Network configuration not loaded or empty.");
|
|
||||||
}
|
|
||||||
return config.getNetworkConfig().getIntersections().stream()
|
|
||||||
.filter(i -> i.getId().equals(intersectionId))
|
|
||||||
.findFirst()
|
|
||||||
.orElseThrow(() -> new RuntimeException("Intersection config not found for " + intersectionId));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void configureRouting() {
|
private void configureRouting() {
|
||||||
System.out.println("\n[" + intersectionId + "] Configuring routing...");
|
System.out.println("\n[" + intersectionId + "] Configuring routing...");
|
||||||
|
|
||||||
SimulationConfig.IntersectionConfig intersectionConfig = getIntersectionConfig();
|
switch (intersectionId) {
|
||||||
Map<String, String> routes = intersectionConfig.getRoutes();
|
case "Cr1":
|
||||||
|
intersection.configureRoute("Cr2", "East");
|
||||||
|
intersection.configureRoute("Cr4", "South");
|
||||||
|
break;
|
||||||
|
|
||||||
if (routes != null) {
|
case "Cr2":
|
||||||
for (Map.Entry<String, String> entry : routes.entrySet()) {
|
intersection.configureRoute("Cr1", "West");
|
||||||
String destination = entry.getKey();
|
intersection.configureRoute("Cr3", "East");
|
||||||
String direction = entry.getValue();
|
intersection.configureRoute("Cr5", "South");
|
||||||
intersection.configureRoute(destination, direction);
|
break;
|
||||||
System.out.println(" Route configured: To " + destination + " -> Use " + direction);
|
|
||||||
}
|
case "Cr3":
|
||||||
} else {
|
intersection.configureRoute("Cr2", "West");
|
||||||
System.out.println(" No routes configured.");
|
intersection.configureRoute("S", "South");
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "Cr4":
|
||||||
|
intersection.configureRoute("Cr5", "East");
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "Cr5":
|
||||||
|
intersection.configureRoute("S", "East");
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
System.err.println(" Error: unknown intersection ID: " + intersectionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println(" Routing configured.");
|
System.out.println(" Routing configured.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Requests permission for a traffic light to turn green.
|
|
||||||
* Blocks until permission is granted (no other light is green).
|
|
||||||
*
|
|
||||||
* @param direction The direction requesting green light
|
|
||||||
*/
|
|
||||||
public void requestGreenLight(String direction) {
|
|
||||||
trafficCoordinationLock.lock();
|
|
||||||
currentGreenDirection = direction;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Releases the green light permission, allowing another light to turn green.
|
|
||||||
*
|
|
||||||
* @param direction The direction releasing green light
|
|
||||||
*/
|
|
||||||
public void releaseGreenLight(String direction) {
|
|
||||||
if (direction.equals(currentGreenDirection)) {
|
|
||||||
currentGreenDirection = null;
|
|
||||||
trafficCoordinationLock.unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts all traffic light threads.
|
* Starts all traffic light threads.
|
||||||
*/
|
*/
|
||||||
@@ -256,12 +179,16 @@ public class IntersectionProcess {
|
|||||||
|
|
||||||
TrafficLightThread lightTask = new TrafficLightThread(light, this, config);
|
TrafficLightThread lightTask = new TrafficLightThread(light, this, config);
|
||||||
|
|
||||||
|
|
||||||
trafficLightPool.submit(lightTask);
|
trafficLightPool.submit(lightTask);
|
||||||
|
|
||||||
System.out.println(" Started thread for: " + light.getDirection());
|
System.out.println(" Started thread for: " + light.getDirection());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends a vehicle to its next destination via socket connection.
|
* Sends a vehicle to its next destination via socket connection.
|
||||||
*
|
*
|
||||||
@@ -274,22 +201,18 @@ public class IntersectionProcess {
|
|||||||
// Get or create connection to next destination
|
// Get or create connection to next destination
|
||||||
SocketConnection connection = getOrCreateConnection(nextDestination);
|
SocketConnection connection = getOrCreateConnection(nextDestination);
|
||||||
|
|
||||||
// Create and send message using Message class
|
// Create and send message
|
||||||
MessageProtocol message = new Message(
|
MessageProtocol message = new VehicleTransferMessage(
|
||||||
MessageType.VEHICLE_TRANSFER,
|
|
||||||
intersectionId,
|
intersectionId,
|
||||||
nextDestination,
|
nextDestination,
|
||||||
vehicle,
|
vehicle
|
||||||
System.currentTimeMillis());
|
);
|
||||||
|
|
||||||
connection.sendMessage(message);
|
connection.sendMessage(message);
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Sent vehicle " + vehicle.getId() +
|
System.out.println("[" + intersectionId + "] Sent vehicle " + vehicle.getId() +
|
||||||
" to " + nextDestination);
|
" to " + nextDestination);
|
||||||
|
|
||||||
// Record departure for statistics
|
|
||||||
recordVehicleDeparture();
|
|
||||||
|
|
||||||
// Note: vehicle route is advanced when it arrives at the next intersection
|
// Note: vehicle route is advanced when it arrives at the next intersection
|
||||||
|
|
||||||
} catch (IOException | InterruptedException e) {
|
} catch (IOException | InterruptedException e) {
|
||||||
@@ -367,9 +290,6 @@ 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
|
||||||
@@ -377,37 +297,17 @@ public class IntersectionProcess {
|
|||||||
try {
|
try {
|
||||||
Socket clientSocket = serverSocket.accept();
|
Socket clientSocket = serverSocket.accept();
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] New connection accepted from " +
|
|
||||||
clientSocket.getInetAddress().getHostAddress());
|
|
||||||
|
|
||||||
// Check running flag again before handling
|
|
||||||
if (!running) {
|
|
||||||
clientSocket.close();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// **Set timeout before submitting to handler**
|
|
||||||
try {
|
|
||||||
clientSocket.setSoTimeout(1000);
|
|
||||||
} catch (java.net.SocketException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to set timeout: " + e.getMessage());
|
|
||||||
clientSocket.close();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle each connection in a separate thread
|
// Handle each connection in a separate thread
|
||||||
connectionHandlerPool.submit(() -> handleIncomingConnection(clientSocket));
|
connectionHandlerPool.submit(() -> handleIncomingConnection(clientSocket));
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
// Expected when serverSocket.close() is called during shutdown
|
if (running) {
|
||||||
if (!running) {
|
|
||||||
break; // Normal shutdown
|
|
||||||
}
|
|
||||||
System.err.println("[" + intersectionId + "] Error accepting connection: " +
|
System.err.println("[" + intersectionId + "] Error accepting connection: " +
|
||||||
e.getMessage());
|
e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles an incoming connection from another process.
|
* Handles an incoming connection from another process.
|
||||||
@@ -416,14 +316,6 @@ public class IntersectionProcess {
|
|||||||
* @param clientSocket The accepted socket connection.
|
* @param clientSocket The accepted socket connection.
|
||||||
*/
|
*/
|
||||||
private void handleIncomingConnection(Socket clientSocket) {
|
private void handleIncomingConnection(Socket clientSocket) {
|
||||||
try {
|
|
||||||
clientSocket.setSoTimeout(1000); // 1 second timeout
|
|
||||||
|
|
||||||
} catch (java.net.SocketException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to set socket timeout: " + e.getMessage());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try (SocketConnection connection = new SocketConnection(clientSocket)) {
|
try (SocketConnection connection = new SocketConnection(clientSocket)) {
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] New connection accepted from " +
|
System.out.println("[" + intersectionId + "] New connection accepted from " +
|
||||||
@@ -434,66 +326,19 @@ public class IntersectionProcess {
|
|||||||
try {
|
try {
|
||||||
MessageProtocol message = connection.receiveMessage();
|
MessageProtocol message = connection.receiveMessage();
|
||||||
|
|
||||||
// Handle simulation start time synchronization
|
if (message.getType() == MessageType.VEHICLE_TRANSFER) {
|
||||||
if (message.getType() == MessageType.SIMULATION_START) {
|
Vehicle vehicle = (Vehicle) message.getPayload();
|
||||||
System.out.println("[" + intersectionId + "] Simulation start time synchronized");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Accept both VEHICLE_TRANSFER and VEHICLE_SPAWN (from coordinator)
|
|
||||||
if (message.getType() == MessageType.VEHICLE_TRANSFER ||
|
|
||||||
message.getType() == MessageType.VEHICLE_SPAWN) {
|
|
||||||
// Cast payload to Vehicle - handle Gson deserialization
|
|
||||||
Vehicle vehicle;
|
|
||||||
Object payload = message.getPayload();
|
|
||||||
if (payload instanceof Vehicle) {
|
|
||||||
vehicle = (Vehicle) payload;
|
|
||||||
} else if (payload instanceof java.util.Map) {
|
|
||||||
// Gson deserialized as LinkedHashMap - re-serialize and deserialize as Vehicle
|
|
||||||
com.google.gson.Gson gson = new com.google.gson.Gson();
|
|
||||||
String json = gson.toJson(payload);
|
|
||||||
vehicle = gson.fromJson(json, Vehicle.class);
|
|
||||||
} else {
|
|
||||||
System.err.println("[" + intersectionId + "] Unknown payload type: " + payload.getClass());
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Received vehicle: " +
|
System.out.println("[" + intersectionId + "] Received vehicle: " +
|
||||||
vehicle.getId() + " from " + message.getSourceNode());
|
vehicle.getId() + " from " + message.getSourceNode());
|
||||||
|
|
||||||
// Advance vehicle to next destination in its route
|
|
||||||
vehicle.advanceRoute();
|
|
||||||
|
|
||||||
// Add vehicle to appropriate queue
|
// Add vehicle to appropriate queue
|
||||||
intersection.receiveVehicle(vehicle);
|
intersection.receiveVehicle(vehicle);
|
||||||
|
|
||||||
// Record arrival for statistics
|
|
||||||
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) {
|
|
||||||
// Timeout - check running flag and continue
|
|
||||||
if (!running) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
// Continue waiting for next message
|
|
||||||
} catch (ClassNotFoundException e) {
|
} catch (ClassNotFoundException e) {
|
||||||
System.err.println("[" + intersectionId + "] Unknown message type received: " +
|
System.err.println("[" + intersectionId + "] Unknown message type received: " +
|
||||||
e.getMessage());
|
e.getMessage());
|
||||||
break; // Invalid message, close connection
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (running) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to deserialize message: " +
|
|
||||||
e.getMessage());
|
|
||||||
e.printStackTrace(); // For debugging - maybe change//remove later
|
|
||||||
}
|
|
||||||
break; // Connection error, close connection
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -501,7 +346,6 @@ public class IntersectionProcess {
|
|||||||
if (running) {
|
if (running) {
|
||||||
System.err.println("[" + intersectionId + "] Connection error: " + e.getMessage());
|
System.err.println("[" + intersectionId + "] Connection error: " + e.getMessage());
|
||||||
}
|
}
|
||||||
// Expected during shutdown
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -510,71 +354,47 @@ public class IntersectionProcess {
|
|||||||
* Shuts down all threads and closes all connections.
|
* Shuts down all threads and closes all connections.
|
||||||
*/
|
*/
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
// Check if already shutdown
|
|
||||||
if (!running) {
|
|
||||||
return; // Already shutdown, do nothing
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("\n[" + intersectionId + "] Shutting down...");
|
System.out.println("\n[" + intersectionId + "] Shutting down...");
|
||||||
running = false;
|
running = false;
|
||||||
|
|
||||||
// Send final stats before closing connections
|
// Close server socket
|
||||||
sendStatsToDashboard();
|
|
||||||
|
|
||||||
// 1. Close ServerSocket first
|
|
||||||
if (serverSocket != null && !serverSocket.isClosed()) {
|
|
||||||
try {
|
try {
|
||||||
|
if (serverSocket != null && !serverSocket.isClosed()) {
|
||||||
serverSocket.close();
|
serverSocket.close();
|
||||||
} catch (IOException e) {
|
|
||||||
// Expected
|
|
||||||
}
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("[" + intersectionId + "] Error closing server socket: " +
|
||||||
|
e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Shutdown thread pools with force
|
// Shutdown thread pools
|
||||||
if (trafficLightPool != null && !trafficLightPool.isShutdown()) {
|
trafficLightPool.shutdown();
|
||||||
|
connectionHandlerPool.shutdown();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!trafficLightPool.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||||
trafficLightPool.shutdownNow();
|
trafficLightPool.shutdownNow();
|
||||||
}
|
}
|
||||||
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
if (!connectionHandlerPool.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||||
connectionHandlerPool.shutdownNow();
|
connectionHandlerPool.shutdownNow();
|
||||||
}
|
}
|
||||||
if (statsExecutor != null && !statsExecutor.isShutdown()) {
|
|
||||||
statsExecutor.shutdownNow();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Wait briefly for termination (don't block forever)
|
|
||||||
try {
|
|
||||||
if (trafficLightPool != null) {
|
|
||||||
trafficLightPool.awaitTermination(1, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
if (connectionHandlerPool != null) {
|
|
||||||
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
if (statsExecutor != null) {
|
|
||||||
statsExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
trafficLightPool.shutdownNow();
|
||||||
|
connectionHandlerPool.shutdownNow();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Close outgoing connections
|
// Close all outgoing connections
|
||||||
synchronized (outgoingConnections) {
|
for (Map.Entry<String, SocketConnection> entry : outgoingConnections.entrySet()) {
|
||||||
for (SocketConnection conn : outgoingConnections.values()) {
|
|
||||||
try {
|
try {
|
||||||
conn.close();
|
entry.getValue().close();
|
||||||
} catch (Exception e) {
|
} catch (IOException e) {
|
||||||
// Ignore
|
System.err.println("[" + intersectionId + "] Error closing connection to " +
|
||||||
|
entry.getKey() + ": " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outgoingConnections.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. Close dashboard connection
|
|
||||||
if (dashboardClient != null) {
|
|
||||||
dashboardClient.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Shutdown complete.");
|
System.out.println("[" + intersectionId + "] Shutdown complete.");
|
||||||
System.out.println("============================================================\n");
|
System.out.println("=".repeat(60));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -587,53 +407,42 @@ public class IntersectionProcess {
|
|||||||
return intersection;
|
return intersection;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// --- Inner class for Vehicle Transfer Messages ---
|
||||||
* Records that a vehicle has arrived at this intersection.
|
|
||||||
*/
|
|
||||||
public void recordVehicleArrival() {
|
|
||||||
totalArrivals++;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Records that a vehicle has departed from this intersection.
|
* Implementation of MessageProtocol for vehicle transfers between processes.
|
||||||
*/
|
*/
|
||||||
public void recordVehicleDeparture() {
|
private static class VehicleTransferMessage implements MessageProtocol {
|
||||||
totalDepartures++;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
private final String sourceNode;
|
||||||
|
private final String destinationNode;
|
||||||
|
private final Vehicle payload;
|
||||||
|
|
||||||
|
public VehicleTransferMessage(String sourceNode, String destinationNode, Vehicle vehicle) {
|
||||||
|
this.sourceNode = sourceNode;
|
||||||
|
this.destinationNode = destinationNode;
|
||||||
|
this.payload = vehicle;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
@Override
|
||||||
* Sends current statistics to the dashboard server.
|
public MessageType getType() {
|
||||||
*/
|
return MessageType.VEHICLE_TRANSFER;
|
||||||
private void sendStatsToDashboard() {
|
|
||||||
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
@Override
|
||||||
// Calculate current queue size
|
public Object getPayload() {
|
||||||
int currentQueueSize = intersection.getTrafficLights().stream()
|
return payload;
|
||||||
.mapToInt(TrafficLight::getQueueSize)
|
}
|
||||||
.sum();
|
|
||||||
|
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload()
|
@Override
|
||||||
.setIntersectionArrivals(totalArrivals)
|
public String getSourceNode() {
|
||||||
.setIntersectionDepartures(totalDepartures)
|
return sourceNode;
|
||||||
.setIntersectionQueueSize(currentQueueSize);
|
}
|
||||||
|
|
||||||
// Send StatsUpdatePayload directly as the message payload
|
@Override
|
||||||
sd.model.Message message = new sd.model.Message(
|
public String getDestinationNode() {
|
||||||
MessageType.STATS_UPDATE,
|
return destinationNode;
|
||||||
intersectionId,
|
|
||||||
"Dashboard",
|
|
||||||
payload);
|
|
||||||
|
|
||||||
dashboardClient.send(message);
|
|
||||||
|
|
||||||
System.out.printf("[%s] Sent stats to dashboard (arrivals=%d, departures=%d, queue=%d)%n",
|
|
||||||
intersectionId, totalArrivals, totalDepartures, currentQueueSize);
|
|
||||||
|
|
||||||
} catch (SerializationException | IOException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Failed to send stats to dashboard: " + e.getMessage());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,16 +3,8 @@ package sd.config;
|
|||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.InputStreamReader;
|
|
||||||
import java.io.Reader;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class to load and manage simulation configurations.
|
* Class to load and manage simulation configurations.
|
||||||
* Configurations are read from a .properties file. This class provides
|
* Configurations are read from a .properties file. This class provides
|
||||||
@@ -25,144 +17,59 @@ public class SimulationConfig {
|
|||||||
* Holds all properties loaded from the file.
|
* Holds all properties loaded from the file.
|
||||||
*/
|
*/
|
||||||
private final Properties properties;
|
private final Properties properties;
|
||||||
private NetworkConfig networkConfig;
|
|
||||||
|
|
||||||
public static class NetworkConfig {
|
|
||||||
private List<IntersectionConfig> intersections;
|
|
||||||
|
|
||||||
public List<IntersectionConfig> getIntersections() {
|
|
||||||
return intersections;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class IntersectionConfig {
|
|
||||||
private String id;
|
|
||||||
private List<String> lights;
|
|
||||||
private Map<String, String> routes;
|
|
||||||
|
|
||||||
public String getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<String> getLights() {
|
|
||||||
return lights;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getRoutes() {
|
|
||||||
return routes;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new SimulationConfig object by loading properties
|
* Constructs a new SimulationConfig object by loading properties
|
||||||
* from the specified file path.
|
* from the specified file path.
|
||||||
*
|
*
|
||||||
* This constructor attempts to load the configuration file using multiple
|
* @param filePath The path to the .properties file (e.g., "src/main/resources/simulation.properties").
|
||||||
* strategies:
|
* @throws IOException If the file cannot be found or read.
|
||||||
* 1. Direct file system path
|
|
||||||
* 2. Classpath resource (with automatic path normalization)
|
|
||||||
* 3. Classpath resource with leading slash
|
|
||||||
*
|
|
||||||
* @param filePath The path to the .properties file (e.g.,
|
|
||||||
* "src/main/resources/simulation.properties").
|
|
||||||
* @throws IOException If the file cannot be found or read from any location.
|
|
||||||
*/
|
*/
|
||||||
public SimulationConfig(String filePath) throws IOException {
|
public SimulationConfig(String filePath) throws IOException {
|
||||||
properties = new Properties();
|
properties = new Properties();
|
||||||
|
/**Tenta carregar diretamente a partir do sistema de ficheiros, se o ficheiro não existir
|
||||||
|
* (por exemplo quando executado a partir do classpath/jar),
|
||||||
|
* faz fallback para carregar a partir do classpath usando o ClassLoader.
|
||||||
|
*/
|
||||||
|
IOException lastException = null; //FIXME: melhorar esta parte para reportar erros de forma mais clara
|
||||||
|
|
||||||
// List to track all attempted paths for better error reporting
|
try {
|
||||||
List<String> attemptedPaths = new ArrayList<>();
|
|
||||||
IOException fileSystemException = null;
|
|
||||||
|
|
||||||
// Strategy 1: Try to load directly from file system
|
|
||||||
try (InputStream input = new FileInputStream(filePath)) {
|
try (InputStream input = new FileInputStream(filePath)) {
|
||||||
properties.load(input);
|
properties.load(input);
|
||||||
loadNetworkConfig();
|
return; // carregado com sucesso a partir do caminho fornecido
|
||||||
return; // Successfully loaded from file system
|
|
||||||
} catch (IOException e) {
|
|
||||||
fileSystemException = e;
|
|
||||||
attemptedPaths.add("File system: " + filePath);
|
|
||||||
}
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
// Strategy 2: Try to load from classpath with path normalization
|
lastException = e;
|
||||||
|
//tenta carregar a partir do classpath sem prefixos comuns
|
||||||
String resourcePath = filePath;
|
String resourcePath = filePath;
|
||||||
|
//Remove prefixos que apontam para src/main/resources quando presentes
|
||||||
// Remove common src/main/resources prefixes
|
|
||||||
resourcePath = resourcePath.replace("src/main/resources/", "").replace("src\\main\\resources\\", "");
|
resourcePath = resourcePath.replace("src/main/resources/", "").replace("src\\main\\resources\\", "");
|
||||||
|
//Remove prefixo classpath: se fornecido
|
||||||
// Remove classpath: prefix if provided
|
|
||||||
if (resourcePath.startsWith("classpath:")) {
|
if (resourcePath.startsWith("classpath:")) {
|
||||||
resourcePath = resourcePath.substring("classpath:".length());
|
resourcePath = resourcePath.substring("classpath:".length());
|
||||||
if (resourcePath.startsWith("/")) {
|
if (resourcePath.startsWith("/")) resourcePath = resourcePath.substring(1);
|
||||||
resourcePath = resourcePath.substring(1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try loading from classpath using thread context class loader
|
|
||||||
InputStream resourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
|
InputStream resourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
|
||||||
attemptedPaths.add("Classpath (context): " + resourcePath);
|
|
||||||
|
|
||||||
if (resourceStream == null) {
|
if (resourceStream == null) {
|
||||||
// Strategy 3: Try with leading slash
|
//como último recurso, tentar com um leading slash
|
||||||
String slashPath = "/" + resourcePath;
|
resourceStream = SimulationConfig.class.getResourceAsStream('/' + resourcePath);
|
||||||
resourceStream = SimulationConfig.class.getResourceAsStream(slashPath);
|
|
||||||
attemptedPaths.add("Classpath (class): " + slashPath);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (resourceStream != null) {
|
if (resourceStream != null) {
|
||||||
try (InputStream input = resourceStream) {
|
try (InputStream input = resourceStream) {
|
||||||
properties.load(input);
|
properties.load(input);
|
||||||
loadNetworkConfig();
|
|
||||||
return; // Successfully loaded from classpath
|
|
||||||
} catch (IOException e) {
|
|
||||||
// Failed to read from classpath resource
|
|
||||||
throw new IOException(
|
|
||||||
String.format("Failed to read properties from classpath resource '%s': %s",
|
|
||||||
resourcePath, e.getMessage()),
|
|
||||||
e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// All strategies failed - provide comprehensive error message
|
|
||||||
StringBuilder errorMsg = new StringBuilder();
|
|
||||||
errorMsg.append("Configuration file '").append(filePath).append("' could not be found.\n");
|
|
||||||
errorMsg.append("Attempted locations:\n");
|
|
||||||
for (String path : attemptedPaths) {
|
|
||||||
errorMsg.append(" - ").append(path).append("\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fileSystemException != null) {
|
|
||||||
errorMsg.append("\nOriginal error: ").append(fileSystemException.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new IOException(errorMsg.toString(), fileSystemException);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void loadNetworkConfig() {
|
|
||||||
try (InputStream is = getClass().getClassLoader().getResourceAsStream("network_config.json")) {
|
|
||||||
if (is == null) {
|
|
||||||
System.err.println("Warning: network_config.json not found in classpath. Using defaults/empty.");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try (Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
|
|
||||||
Gson gson = new Gson();
|
|
||||||
this.networkConfig = gson.fromJson(reader, NetworkConfig.class);
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Failed to load network_config.json: " + e.getMessage());
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (lastException != null) throw lastException;
|
||||||
public NetworkConfig getNetworkConfig() {
|
|
||||||
return networkConfig;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Network configurations ---
|
// --- Network configurations ---
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the host address for a specific intersection.
|
* Gets the host address for a specific intersection.
|
||||||
*
|
|
||||||
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
||||||
* @return The host (e.g., "localhost").
|
* @return The host (e.g., "localhost").
|
||||||
*/
|
*/
|
||||||
@@ -172,7 +79,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the port number for a specific intersection.
|
* Gets the port number for a specific intersection.
|
||||||
*
|
|
||||||
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
||||||
* @return The port number.
|
* @return The port number.
|
||||||
*/
|
*/
|
||||||
@@ -182,7 +88,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the host address for the dashboard server.
|
* Gets the host address for the dashboard server.
|
||||||
*
|
|
||||||
* @return The dashboard host.
|
* @return The dashboard host.
|
||||||
*/
|
*/
|
||||||
public String getDashboardHost() {
|
public String getDashboardHost() {
|
||||||
@@ -191,7 +96,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the port number for the dashboard server.
|
* Gets the port number for the dashboard server.
|
||||||
*
|
|
||||||
* @return The dashboard port.
|
* @return The dashboard port.
|
||||||
*/
|
*/
|
||||||
public int getDashboardPort() {
|
public int getDashboardPort() {
|
||||||
@@ -200,7 +104,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the host address for the exit node.
|
* Gets the host address for the exit node.
|
||||||
*
|
|
||||||
* @return The exit node host.
|
* @return The exit node host.
|
||||||
*/
|
*/
|
||||||
public String getExitHost() {
|
public String getExitHost() {
|
||||||
@@ -209,7 +112,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the port number for the exit node.
|
* Gets the port number for the exit node.
|
||||||
*
|
|
||||||
* @return The exit node port.
|
* @return The exit node port.
|
||||||
*/
|
*/
|
||||||
public int getExitPort() {
|
public int getExitPort() {
|
||||||
@@ -220,26 +122,14 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the total duration of the simulation in virtual seconds.
|
* Gets the total duration of the simulation in virtual seconds.
|
||||||
*
|
|
||||||
* @return The simulation duration.
|
* @return The simulation duration.
|
||||||
*/
|
*/
|
||||||
public double getSimulationDuration() {
|
public double getSimulationDuration() {
|
||||||
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").
|
||||||
*
|
|
||||||
* @return The arrival model as a string.
|
* @return The arrival model as a string.
|
||||||
*/
|
*/
|
||||||
public String getArrivalModel() {
|
public String getArrivalModel() {
|
||||||
@@ -249,7 +139,6 @@ public class SimulationConfig {
|
|||||||
/**
|
/**
|
||||||
* Gets the average arrival rate (lambda) for the POISSON model.
|
* Gets the average arrival rate (lambda) for the POISSON model.
|
||||||
* This represents the average number of vehicles arriving per second.
|
* This represents the average number of vehicles arriving per second.
|
||||||
*
|
|
||||||
* @return The arrival rate.
|
* @return The arrival rate.
|
||||||
*/
|
*/
|
||||||
public double getArrivalRate() {
|
public double getArrivalRate() {
|
||||||
@@ -258,7 +147,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the fixed time interval between vehicle arrivals for the FIXED model.
|
* Gets the fixed time interval between vehicle arrivals for the FIXED model.
|
||||||
*
|
|
||||||
* @return The fixed interval in seconds.
|
* @return The fixed interval in seconds.
|
||||||
*/
|
*/
|
||||||
public double getFixedArrivalInterval() {
|
public double getFixedArrivalInterval() {
|
||||||
@@ -269,7 +157,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the duration of the GREEN light state for a specific traffic light.
|
* Gets the duration of the GREEN light state for a specific traffic light.
|
||||||
*
|
|
||||||
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
||||||
* @param direction The direction of the light (e.g., "North").
|
* @param direction The direction of the light (e.g., "North").
|
||||||
* @return The green light time in seconds.
|
* @return The green light time in seconds.
|
||||||
@@ -281,7 +168,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the duration of the RED light state for a specific traffic light.
|
* Gets the duration of the RED light state for a specific traffic light.
|
||||||
*
|
|
||||||
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
||||||
* @param direction The direction of the light (e.g., "North").
|
* @param direction The direction of the light (e.g., "North").
|
||||||
* @return The red light time in seconds.
|
* @return The red light time in seconds.
|
||||||
@@ -295,7 +181,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type LIGHT.
|
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type LIGHT.
|
||||||
*
|
|
||||||
* @return The probability for LIGHT vehicles.
|
* @return The probability for LIGHT vehicles.
|
||||||
*/
|
*/
|
||||||
public double getLightVehicleProbability() {
|
public double getLightVehicleProbability() {
|
||||||
@@ -304,7 +189,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the average time it takes a LIGHT vehicle to cross an intersection.
|
* Gets the average time it takes a LIGHT vehicle to cross an intersection.
|
||||||
*
|
|
||||||
* @return The crossing time in seconds.
|
* @return The crossing time in seconds.
|
||||||
*/
|
*/
|
||||||
public double getLightVehicleCrossingTime() {
|
public double getLightVehicleCrossingTime() {
|
||||||
@@ -313,7 +197,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type BIKE.
|
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type BIKE.
|
||||||
*
|
|
||||||
* @return The probability for BIKE vehicles.
|
* @return The probability for BIKE vehicles.
|
||||||
*/
|
*/
|
||||||
public double getBikeVehicleProbability() {
|
public double getBikeVehicleProbability() {
|
||||||
@@ -322,7 +205,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the average time it takes a BIKE vehicle to cross an intersection.
|
* Gets the average time it takes a BIKE vehicle to cross an intersection.
|
||||||
*
|
|
||||||
* @return The crossing time in seconds.
|
* @return The crossing time in seconds.
|
||||||
*/
|
*/
|
||||||
public double getBikeVehicleCrossingTime() {
|
public double getBikeVehicleCrossingTime() {
|
||||||
@@ -331,7 +213,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type HEAVY.
|
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type HEAVY.
|
||||||
*
|
|
||||||
* @return The probability for HEAVY vehicles.
|
* @return The probability for HEAVY vehicles.
|
||||||
*/
|
*/
|
||||||
public double getHeavyVehicleProbability() {
|
public double getHeavyVehicleProbability() {
|
||||||
@@ -340,58 +221,26 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the average time it takes a HEAVY vehicle to cross an intersection.
|
* Gets the average time it takes a HEAVY vehicle to cross an intersection.
|
||||||
*
|
|
||||||
* @return The crossing time in seconds.
|
* @return The crossing time in seconds.
|
||||||
*/
|
*/
|
||||||
public double getHeavyVehicleCrossingTime() {
|
public double getHeavyVehicleCrossingTime() {
|
||||||
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.heavy", "4.0"));
|
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.heavy", "4.0"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the base travel time between intersections for light vehicles.
|
|
||||||
*
|
|
||||||
* @return The base travel time in seconds.
|
|
||||||
*/
|
|
||||||
public double getBaseTravelTime() {
|
|
||||||
return Double.parseDouble(properties.getProperty("vehicle.travel.time.base", "8.0"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the travel time multiplier for bike vehicles.
|
|
||||||
* Bike travel time = base time × this multiplier.
|
|
||||||
*
|
|
||||||
* @return The multiplier for bike travel time.
|
|
||||||
*/
|
|
||||||
public double getBikeTravelTimeMultiplier() {
|
|
||||||
return Double.parseDouble(properties.getProperty("vehicle.travel.time.bike.multiplier", "0.5"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the travel time multiplier for heavy vehicles.
|
|
||||||
* Heavy vehicle travel time = base time × this multiplier.
|
|
||||||
*
|
|
||||||
* @return The multiplier for heavy vehicle travel time.
|
|
||||||
*/
|
|
||||||
public double getHeavyTravelTimeMultiplier() {
|
|
||||||
return Double.parseDouble(properties.getProperty("vehicle.travel.time.heavy.multiplier", "2.0"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Statistics ---
|
// --- Statistics ---
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the interval (in virtual seconds) between periodic statistics updates.
|
* Gets the interval (in virtual seconds) between periodic statistics updates.
|
||||||
*
|
|
||||||
* @return The statistics update interval.
|
* @return The statistics update interval.
|
||||||
*/
|
*/
|
||||||
public double getStatisticsUpdateInterval() {
|
public double getStatisticsUpdateInterval() {
|
||||||
return Double.parseDouble(properties.getProperty("statistics.update.interval", "1.0"));
|
return Double.parseDouble(properties.getProperty("statistics.update.interval", "10.0"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Generic getters ---
|
// --- Generic getters ---
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generic method to get any property as a string, with a default value.
|
* Generic method to get any property as a string, with a default value.
|
||||||
*
|
|
||||||
* @param key The property key.
|
* @param key The property key.
|
||||||
* @param defaultValue The value to return if the key is not found.
|
* @param defaultValue The value to return if the key is not found.
|
||||||
* @return The property value or the default.
|
* @return The property value or the default.
|
||||||
@@ -402,7 +251,6 @@ public class SimulationConfig {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Generic method to get any property as a string.
|
* Generic method to get any property as a string.
|
||||||
*
|
|
||||||
* @param key The property key.
|
* @param key The property key.
|
||||||
* @return The property value, or null if not found.
|
* @return The property value, or null if not found.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import java.util.HashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.dashboard.StatsUpdatePayload;
|
|
||||||
import sd.model.Message;
|
import sd.model.Message;
|
||||||
import sd.model.MessageType;
|
import sd.model.MessageType;
|
||||||
import sd.model.Vehicle;
|
import sd.model.Vehicle;
|
||||||
@@ -25,7 +24,6 @@ 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;
|
||||||
private SocketClient dashboardClient;
|
|
||||||
private double currentTime;
|
private double currentTime;
|
||||||
private int vehicleCounter;
|
private int vehicleCounter;
|
||||||
private boolean running;
|
private boolean running;
|
||||||
@@ -77,12 +75,9 @@ public class CoordinatorProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void initialize() {
|
public void initialize() {
|
||||||
// Connect to dashboard first
|
|
||||||
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 {
|
||||||
@@ -113,36 +108,14 @@ public class CoordinatorProcess {
|
|||||||
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
|
|
||||||
sendSimulationStartTime();
|
|
||||||
|
|
||||||
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
||||||
final double TIME_STEP = 0.1;
|
final double TIME_STEP = 0.1;
|
||||||
|
|
||||||
double drainTime = config.getDrainTime();
|
while (running && currentTime < duration) {
|
||||||
double totalDuration = duration + drainTime;
|
|
||||||
boolean draining = false;
|
|
||||||
|
|
||||||
while (running && currentTime < totalDuration) {
|
|
||||||
// Only generate vehicles during the main duration
|
|
||||||
if (currentTime < duration) {
|
|
||||||
if (currentTime >= nextGenerationTime) {
|
if (currentTime >= nextGenerationTime) {
|
||||||
generateAndSendVehicle();
|
generateAndSendVehicle();
|
||||||
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,9 +132,6 @@ public class CoordinatorProcess {
|
|||||||
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
|
|
||||||
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;
|
||||||
@@ -184,7 +154,8 @@ public class CoordinatorProcess {
|
|||||||
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);
|
||||||
@@ -210,7 +181,8 @@ public class CoordinatorProcess {
|
|||||||
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);
|
||||||
}
|
}
|
||||||
@@ -229,74 +201,4 @@ public class CoordinatorProcess {
|
|||||||
System.out.println("\nStop signal received...");
|
System.out.println("\nStop signal received...");
|
||||||
running = false;
|
running = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void connectToDashboard() {
|
|
||||||
try {
|
|
||||||
String host = config.getDashboardHost();
|
|
||||||
int port = config.getDashboardPort();
|
|
||||||
|
|
||||||
System.out.println("Connecting to dashboard at " + host + ":" + port);
|
|
||||||
dashboardClient = new SocketClient("Dashboard", host, port);
|
|
||||||
dashboardClient.connect();
|
|
||||||
System.out.println("Successfully connected to dashboard\n");
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("WARNING: Failed to connect to dashboard: " + e.getMessage());
|
|
||||||
System.err.println("Coordinator will continue without dashboard connection\n");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendGenerationStatsToDashboard() {
|
|
||||||
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Create stats payload with vehicle generation count
|
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload();
|
|
||||||
payload.setTotalVehiclesGenerated(vehicleCounter);
|
|
||||||
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.STATS_UPDATE,
|
|
||||||
"COORDINATOR",
|
|
||||||
"Dashboard",
|
|
||||||
payload);
|
|
||||||
|
|
||||||
dashboardClient.send(message);
|
|
||||||
} catch (Exception e) { // This is fine - can add IOException if need be
|
|
||||||
// Don't crash if dashboard update fails
|
|
||||||
System.err.println("Failed to send stats to dashboard: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sendSimulationStartTime() {
|
|
||||||
long startTimeMillis = System.currentTimeMillis();
|
|
||||||
|
|
||||||
// Send to all intersections
|
|
||||||
for (Map.Entry<String, SocketClient> entry : intersectionClients.entrySet()) {
|
|
||||||
try {
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.SIMULATION_START,
|
|
||||||
"COORDINATOR",
|
|
||||||
entry.getKey(),
|
|
||||||
startTimeMillis);
|
|
||||||
entry.getValue().send(message);
|
|
||||||
} catch (Exception e) { // Same thing here
|
|
||||||
System.err.println("Failed to send start time to " + entry.getKey() + ": " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send to dashboard
|
|
||||||
if (dashboardClient != null && dashboardClient.isConnected()) {
|
|
||||||
try {
|
|
||||||
Message message = new Message(
|
|
||||||
MessageType.SIMULATION_START,
|
|
||||||
"COORDINATOR",
|
|
||||||
"Dashboard",
|
|
||||||
startTimeMillis);
|
|
||||||
dashboardClient.send(message);
|
|
||||||
} catch (Exception e) { // And here
|
|
||||||
// Don't crash
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,137 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import sd.model.MessageType;
|
|
||||||
import sd.protocol.MessageProtocol;
|
|
||||||
import sd.protocol.SocketConnection;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Processes statistics messages from a single client connection.
|
|
||||||
* Runs in a separate thread per client.
|
|
||||||
*/
|
|
||||||
public class DashboardClientHandler implements Runnable {
|
|
||||||
|
|
||||||
private final Socket clientSocket;
|
|
||||||
private final DashboardStatistics statistics;
|
|
||||||
|
|
||||||
public DashboardClientHandler(Socket clientSocket, DashboardStatistics statistics) {
|
|
||||||
this.clientSocket = clientSocket;
|
|
||||||
this.statistics = statistics;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
String clientInfo = clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort();
|
|
||||||
|
|
||||||
try (SocketConnection connection = new SocketConnection(clientSocket)) {
|
|
||||||
System.out.println("[Handler] Started handling client: " + clientInfo);
|
|
||||||
|
|
||||||
while (!Thread.currentThread().isInterrupted()) {
|
|
||||||
try {
|
|
||||||
MessageProtocol message = connection.receiveMessage();
|
|
||||||
|
|
||||||
if (message == null) {
|
|
||||||
System.out.println("[Handler] Client disconnected: " + clientInfo);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
processMessage(message);
|
|
||||||
|
|
||||||
} catch (ClassNotFoundException e) {
|
|
||||||
System.err.println("[Handler] Unknown message class from " + clientInfo + ": " + e.getMessage());
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.out.println("[Handler] Connection error with " + clientInfo + ": " + e.getMessage());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("[Handler] Error initializing connection with " + clientInfo + ": " + e.getMessage());
|
|
||||||
} finally {
|
|
||||||
try {
|
|
||||||
if (!clientSocket.isClosed()) {
|
|
||||||
clientSocket.close();
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("[Handler] Error closing socket for " + clientInfo + ": " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void processMessage(MessageProtocol message) {
|
|
||||||
if (message.getType() != MessageType.STATS_UPDATE) {
|
|
||||||
System.out.println("[Handler] Ignoring non-statistics message type: " + message.getType());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String senderId = message.getSourceNode();
|
|
||||||
Object payload = message.getPayload();
|
|
||||||
|
|
||||||
System.out.println("[Handler] Received STATS_UPDATE from: " + senderId);
|
|
||||||
|
|
||||||
// Handle both direct StatsUpdatePayload and Gson-deserialized Map
|
|
||||||
StatsUpdatePayload stats;
|
|
||||||
if (payload instanceof StatsUpdatePayload) {
|
|
||||||
stats = (StatsUpdatePayload) payload;
|
|
||||||
} else if (payload instanceof java.util.Map) {
|
|
||||||
// Gson deserialized as LinkedHashMap - re-serialize and deserialize properly
|
|
||||||
com.google.gson.Gson gson = new com.google.gson.Gson();
|
|
||||||
String json = gson.toJson(payload);
|
|
||||||
stats = gson.fromJson(json, StatsUpdatePayload.class);
|
|
||||||
} else {
|
|
||||||
System.err.println("[Handler] Unknown payload type: " +
|
|
||||||
(payload != null ? payload.getClass().getName() : "null"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
updateStatistics(senderId, stats);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateStatistics(String senderId, StatsUpdatePayload stats) {
|
|
||||||
if (stats.getTotalVehiclesGenerated() >= 0) {
|
|
||||||
statistics.updateVehiclesGenerated(stats.getTotalVehiclesGenerated());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (stats.getTotalVehiclesCompleted() >= 0) {
|
|
||||||
statistics.updateVehiclesCompleted(stats.getTotalVehiclesCompleted());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exit Node sends cumulative totals, so we SET rather than ADD
|
|
||||||
if (stats.getTotalSystemTime() >= 0) {
|
|
||||||
statistics.setTotalSystemTime(stats.getTotalSystemTime());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (stats.getTotalWaitingTime() >= 0) {
|
|
||||||
statistics.setTotalWaitingTime(stats.getTotalWaitingTime());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process vehicle type statistics (from Exit Node)
|
|
||||||
if (stats.getVehicleTypeCounts() != null && !stats.getVehicleTypeCounts().isEmpty()) {
|
|
||||||
Map<sd.model.VehicleType, Integer> counts = stats.getVehicleTypeCounts();
|
|
||||||
Map<sd.model.VehicleType, Long> waitTimes = stats.getVehicleTypeWaitTimes();
|
|
||||||
|
|
||||||
for (var entry : counts.entrySet()) {
|
|
||||||
sd.model.VehicleType type = entry.getKey();
|
|
||||||
int count = entry.getValue();
|
|
||||||
long waitTime = (waitTimes != null && waitTimes.containsKey(type))
|
|
||||||
? waitTimes.get(type) : 0L;
|
|
||||||
statistics.updateVehicleTypeStats(type, count, waitTime);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process intersection statistics (from Intersection processes)
|
|
||||||
if (senderId.startsWith("Cr") || senderId.startsWith("E")) {
|
|
||||||
statistics.updateIntersectionStats(
|
|
||||||
senderId,
|
|
||||||
stats.getIntersectionArrivals(),
|
|
||||||
stats.getIntersectionDepartures(),
|
|
||||||
stats.getIntersectionQueueSize()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("[Handler] Successfully updated statistics from: " + senderId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,165 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.ServerSocket;
|
|
||||||
import java.net.Socket;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Aggregates and displays real-time statistics from all simulation processes.
|
|
||||||
* Uses a thread pool to handle concurrent client connections.
|
|
||||||
*/
|
|
||||||
public class DashboardServer {
|
|
||||||
|
|
||||||
private final int port;
|
|
||||||
private final DashboardStatistics statistics;
|
|
||||||
private final ExecutorService clientHandlerPool;
|
|
||||||
private final AtomicBoolean running;
|
|
||||||
private ServerSocket serverSocket;
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
// Check if GUI mode is requested
|
|
||||||
boolean useGUI = false;
|
|
||||||
String configFile = "src/main/resources/simulation.properties";
|
|
||||||
|
|
||||||
for (int i = 0; i < args.length; i++) {
|
|
||||||
if (args[i].equals("--gui") || args[i].equals("-g")) {
|
|
||||||
useGUI = true;
|
|
||||||
} else {
|
|
||||||
configFile = args[i];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (useGUI) {
|
|
||||||
// Launch JavaFX UI
|
|
||||||
System.out.println("Launching Dashboard with JavaFX GUI...");
|
|
||||||
DashboardUI.main(args);
|
|
||||||
} else {
|
|
||||||
// Traditional terminal mode
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
System.out.println("DASHBOARD SERVER - DISTRIBUTED TRAFFIC SIMULATION");
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
|
|
||||||
try {
|
|
||||||
System.out.println("Loading configuration from: " + configFile);
|
|
||||||
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile);
|
|
||||||
DashboardServer server = new DashboardServer(config);
|
|
||||||
|
|
||||||
// Start the server
|
|
||||||
System.out.println("\n" + "=".repeat(60));
|
|
||||||
server.start();
|
|
||||||
|
|
||||||
// Keep running until interrupted
|
|
||||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
|
||||||
System.out.println("\n\nShutdown signal received...");
|
|
||||||
server.stop();
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Display statistics periodically
|
|
||||||
server.displayLoop();
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Failed to start Dashboard Server: " + e.getMessage());
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public DashboardServer(SimulationConfig config) {
|
|
||||||
this.port = config.getDashboardPort();
|
|
||||||
this.statistics = new DashboardStatistics();
|
|
||||||
this.clientHandlerPool = Executors.newFixedThreadPool(10);
|
|
||||||
this.running = new AtomicBoolean(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void start() throws IOException {
|
|
||||||
if (running.get()) {
|
|
||||||
System.out.println("Dashboard Server is already running.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
serverSocket = new ServerSocket(port);
|
|
||||||
running.set(true);
|
|
||||||
|
|
||||||
System.out.println("Dashboard Server started on port " + port);
|
|
||||||
System.out.println("Waiting for statistics updates from simulation processes...");
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
|
|
||||||
Thread acceptThread = new Thread(this::acceptConnections, "DashboardServer-Accept");
|
|
||||||
acceptThread.setDaemon(false);
|
|
||||||
acceptThread.start();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void acceptConnections() {
|
|
||||||
while (running.get()) {
|
|
||||||
try {
|
|
||||||
Socket clientSocket = serverSocket.accept();
|
|
||||||
System.out.println("[Connection] New client connected: " +
|
|
||||||
clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort());
|
|
||||||
|
|
||||||
clientHandlerPool.execute(new DashboardClientHandler(clientSocket, statistics));
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (running.get()) {
|
|
||||||
System.err.println("[Error] Failed to accept client connection: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("BusyWait")
|
|
||||||
private void displayLoop() {
|
|
||||||
final long DISPLAY_INTERVAL_MS = 5000;
|
|
||||||
|
|
||||||
while (running.get()) {
|
|
||||||
try {
|
|
||||||
Thread.sleep(DISPLAY_INTERVAL_MS);
|
|
||||||
displayStatistics();
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void displayStatistics() {
|
|
||||||
System.out.println("\n" + "=".repeat(60));
|
|
||||||
System.out.println("REAL-TIME SIMULATION STATISTICS");
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
statistics.display();
|
|
||||||
System.out.println("=".repeat(60));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stop() {
|
|
||||||
if (!running.get()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("\nStopping Dashboard Server...");
|
|
||||||
running.set(false);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (serverSocket != null && !serverSocket.isClosed()) {
|
|
||||||
serverSocket.close();
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Error closing server socket: " + e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
clientHandlerPool.shutdownNow();
|
|
||||||
System.out.println("Dashboard Server stopped.");
|
|
||||||
}
|
|
||||||
|
|
||||||
public DashboardStatistics getStatistics() {
|
|
||||||
return statistics;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isRunning() {
|
|
||||||
return running.get();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,224 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
|
||||||
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Thread-safe storage for aggregated simulation statistics.
|
|
||||||
* Uses atomic types and concurrent collections for lock-free updates.
|
|
||||||
*/
|
|
||||||
public class DashboardStatistics {
|
|
||||||
|
|
||||||
private final AtomicInteger totalVehiclesGenerated;
|
|
||||||
private final AtomicInteger totalVehiclesCompleted;
|
|
||||||
private final AtomicLong totalSystemTime;
|
|
||||||
private final AtomicLong totalWaitingTime;
|
|
||||||
|
|
||||||
private final Map<String, IntersectionStats> intersectionStats;
|
|
||||||
private final Map<VehicleType, AtomicInteger> vehicleTypeCount;
|
|
||||||
private final Map<VehicleType, AtomicLong> vehicleTypeWaitTime;
|
|
||||||
|
|
||||||
private volatile long lastUpdateTime;
|
|
||||||
|
|
||||||
public DashboardStatistics() {
|
|
||||||
this.totalVehiclesGenerated = new AtomicInteger(0);
|
|
||||||
this.totalVehiclesCompleted = new AtomicInteger(0);
|
|
||||||
this.totalSystemTime = new AtomicLong(0);
|
|
||||||
this.totalWaitingTime = new AtomicLong(0);
|
|
||||||
|
|
||||||
this.intersectionStats = new ConcurrentHashMap<>();
|
|
||||||
this.vehicleTypeCount = new ConcurrentHashMap<>();
|
|
||||||
this.vehicleTypeWaitTime = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
vehicleTypeCount.put(type, new AtomicInteger(0));
|
|
||||||
vehicleTypeWaitTime.put(type, new AtomicLong(0));
|
|
||||||
}
|
|
||||||
|
|
||||||
this.lastUpdateTime = System.currentTimeMillis();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateVehiclesGenerated(int count) {
|
|
||||||
totalVehiclesGenerated.set(count);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void incrementVehiclesGenerated() {
|
|
||||||
totalVehiclesGenerated.incrementAndGet();
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateVehiclesCompleted(int count) {
|
|
||||||
totalVehiclesCompleted.set(count);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void incrementVehiclesCompleted() {
|
|
||||||
totalVehiclesCompleted.incrementAndGet();
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addSystemTime(long timeMs) {
|
|
||||||
totalSystemTime.addAndGet(timeMs);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTotalSystemTime(long timeMs) {
|
|
||||||
totalSystemTime.set(timeMs);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addWaitingTime(long timeMs) {
|
|
||||||
totalWaitingTime.addAndGet(timeMs);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTotalWaitingTime(long timeMs) {
|
|
||||||
totalWaitingTime.set(timeMs);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateVehicleTypeStats(VehicleType type, int count, long waitTimeMs) {
|
|
||||||
vehicleTypeCount.get(type).set(count);
|
|
||||||
vehicleTypeWaitTime.get(type).set(waitTimeMs);
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void incrementVehicleType(VehicleType type) {
|
|
||||||
vehicleTypeCount.get(type).incrementAndGet();
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateIntersectionStats(String intersectionId, int arrivals,
|
|
||||||
int departures, int currentQueueSize) {
|
|
||||||
intersectionStats.compute(intersectionId, (id, stats) -> {
|
|
||||||
if (stats == null) {
|
|
||||||
stats = new IntersectionStats(intersectionId);
|
|
||||||
}
|
|
||||||
stats.updateStats(arrivals, departures, currentQueueSize);
|
|
||||||
return stats;
|
|
||||||
});
|
|
||||||
updateTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateTimestamp() {
|
|
||||||
lastUpdateTime = System.currentTimeMillis();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalVehiclesGenerated() {
|
|
||||||
return totalVehiclesGenerated.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalVehiclesCompleted() {
|
|
||||||
return totalVehiclesCompleted.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public double getAverageSystemTime() {
|
|
||||||
int completed = totalVehiclesCompleted.get();
|
|
||||||
if (completed == 0) return 0.0;
|
|
||||||
return (double) totalSystemTime.get() / completed;
|
|
||||||
}
|
|
||||||
|
|
||||||
public double getAverageWaitingTime() {
|
|
||||||
int completed = totalVehiclesCompleted.get();
|
|
||||||
if (completed == 0) return 0.0;
|
|
||||||
return (double) totalWaitingTime.get() / completed;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getVehicleTypeCount(VehicleType type) {
|
|
||||||
return vehicleTypeCount.get(type).get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public double getAverageWaitingTimeByType(VehicleType type) {
|
|
||||||
int count = vehicleTypeCount.get(type).get();
|
|
||||||
if (count == 0) return 0.0;
|
|
||||||
return (double) vehicleTypeWaitTime.get(type).get() / count;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IntersectionStats getIntersectionStats(String intersectionId) {
|
|
||||||
return intersectionStats.get(intersectionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, IntersectionStats> getAllIntersectionStats() {
|
|
||||||
return new HashMap<>(intersectionStats);
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getLastUpdateTime() {
|
|
||||||
return lastUpdateTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void display() {
|
|
||||||
System.out.println("\n--- GLOBAL STATISTICS ---");
|
|
||||||
System.out.printf("Total Vehicles Generated: %d%n", getTotalVehiclesGenerated());
|
|
||||||
System.out.printf("Total Vehicles Completed: %d%n", getTotalVehiclesCompleted());
|
|
||||||
System.out.printf("Vehicles In Transit: %d%n",
|
|
||||||
getTotalVehiclesGenerated() - getTotalVehiclesCompleted());
|
|
||||||
System.out.printf("Average System Time: %.2f ms%n", getAverageSystemTime());
|
|
||||||
System.out.printf("Average Waiting Time: %.2f ms%n", getAverageWaitingTime());
|
|
||||||
|
|
||||||
System.out.println("\n--- VEHICLE TYPE STATISTICS ---");
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
int count = getVehicleTypeCount(type);
|
|
||||||
double avgWait = getAverageWaitingTimeByType(type);
|
|
||||||
System.out.printf("%s: %d vehicles, avg wait: %.2f ms%n",
|
|
||||||
type, count, avgWait);
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("\n--- INTERSECTION STATISTICS ---");
|
|
||||||
if (intersectionStats.isEmpty()) {
|
|
||||||
System.out.println("(No data received yet)");
|
|
||||||
} else {
|
|
||||||
for (IntersectionStats stats : intersectionStats.values()) {
|
|
||||||
stats.display();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.printf("%nLast Update: %tT%n", lastUpdateTime);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class IntersectionStats {
|
|
||||||
private final String intersectionId;
|
|
||||||
private final AtomicInteger totalArrivals;
|
|
||||||
private final AtomicInteger totalDepartures;
|
|
||||||
private final AtomicInteger currentQueueSize;
|
|
||||||
|
|
||||||
public IntersectionStats(String intersectionId) {
|
|
||||||
this.intersectionId = intersectionId;
|
|
||||||
this.totalArrivals = new AtomicInteger(0);
|
|
||||||
this.totalDepartures = new AtomicInteger(0);
|
|
||||||
this.currentQueueSize = new AtomicInteger(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateStats(int arrivals, int departures, int queueSize) {
|
|
||||||
this.totalArrivals.set(arrivals);
|
|
||||||
this.totalDepartures.set(departures);
|
|
||||||
this.currentQueueSize.set(queueSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getIntersectionId() {
|
|
||||||
return intersectionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalArrivals() {
|
|
||||||
return totalArrivals.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalDepartures() {
|
|
||||||
return totalDepartures.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getCurrentQueueSize() {
|
|
||||||
return currentQueueSize.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void display() {
|
|
||||||
System.out.printf("%s: Arrivals=%d, Departures=%d, Queue=%d%n",
|
|
||||||
intersectionId, getTotalArrivals(), getTotalDepartures(), getCurrentQueueSize());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,450 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import javafx.application.Application;
|
|
||||||
import javafx.application.Platform;
|
|
||||||
import javafx.geometry.Insets;
|
|
||||||
import javafx.geometry.Pos;
|
|
||||||
import javafx.scene.Scene;
|
|
||||||
import javafx.scene.control.Alert;
|
|
||||||
import javafx.scene.control.Button;
|
|
||||||
import javafx.scene.control.Label;
|
|
||||||
import javafx.scene.control.TableColumn;
|
|
||||||
import javafx.scene.control.TableView;
|
|
||||||
import javafx.scene.control.cell.PropertyValueFactory;
|
|
||||||
import javafx.scene.layout.BorderPane;
|
|
||||||
import javafx.scene.layout.GridPane;
|
|
||||||
import javafx.scene.layout.HBox;
|
|
||||||
import javafx.scene.layout.Priority;
|
|
||||||
import javafx.scene.layout.Region;
|
|
||||||
import javafx.scene.layout.VBox;
|
|
||||||
import javafx.scene.shape.Circle;
|
|
||||||
import javafx.stage.Stage;
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* JavaFX-based Dashboard UI for displaying real-time simulation statistics.
|
|
||||||
* Provides a graphical interface with auto-updating statistics panels.
|
|
||||||
*/
|
|
||||||
public class DashboardUI extends Application {
|
|
||||||
|
|
||||||
private DashboardServer server;
|
|
||||||
private DashboardStatistics statistics;
|
|
||||||
|
|
||||||
// Global Statistics Labels
|
|
||||||
private Label lblVehiclesGenerated;
|
|
||||||
private Label lblVehiclesCompleted;
|
|
||||||
private Label lblVehiclesInTransit;
|
|
||||||
private Label lblAvgSystemTime;
|
|
||||||
private Label lblAvgWaitingTime;
|
|
||||||
private Label lblLastUpdate;
|
|
||||||
|
|
||||||
// Vehicle Type Table
|
|
||||||
private TableView<VehicleTypeRow> vehicleTypeTable;
|
|
||||||
|
|
||||||
// Intersection Table
|
|
||||||
private TableView<IntersectionRow> intersectionTable;
|
|
||||||
|
|
||||||
// Update scheduler
|
|
||||||
private ScheduledExecutorService updateScheduler;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void start(Stage primaryStage) {
|
|
||||||
try {
|
|
||||||
// Initialize server
|
|
||||||
String configFile = getParameters().getRaw().isEmpty()
|
|
||||||
? "src/main/resources/simulation.properties"
|
|
||||||
: getParameters().getRaw().get(0);
|
|
||||||
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile);
|
|
||||||
server = new DashboardServer(config);
|
|
||||||
statistics = server.getStatistics();
|
|
||||||
|
|
||||||
// Start the dashboard server
|
|
||||||
server.start();
|
|
||||||
|
|
||||||
// Build UI
|
|
||||||
BorderPane root = new BorderPane();
|
|
||||||
root.getStyleClass().add("root");
|
|
||||||
|
|
||||||
// Header
|
|
||||||
VBox header = createHeader();
|
|
||||||
root.setTop(header);
|
|
||||||
|
|
||||||
// Main content
|
|
||||||
VBox mainContent = createMainContent();
|
|
||||||
root.setCenter(mainContent);
|
|
||||||
|
|
||||||
// Footer
|
|
||||||
HBox footer = createFooter();
|
|
||||||
root.setBottom(footer);
|
|
||||||
|
|
||||||
// Create scene
|
|
||||||
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.setScene(scene);
|
|
||||||
primaryStage.show();
|
|
||||||
|
|
||||||
// Start periodic updates
|
|
||||||
startPeriodicUpdates();
|
|
||||||
|
|
||||||
// Handle window close
|
|
||||||
primaryStage.setOnCloseRequest(event -> {
|
|
||||||
shutdown();
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
showErrorAlert("Failed to start Dashboard Server", e.getMessage());
|
|
||||||
e.printStackTrace();
|
|
||||||
Platform.exit();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private VBox createHeader() {
|
|
||||||
VBox header = new VBox(10);
|
|
||||||
header.getStyleClass().add("header");
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
private VBox createMainContent() {
|
|
||||||
VBox mainContent = new VBox(20);
|
|
||||||
mainContent.setPadding(new Insets(20));
|
|
||||||
|
|
||||||
// Global Statistics Panel
|
|
||||||
VBox globalStatsCard = createGlobalStatisticsPanel();
|
|
||||||
|
|
||||||
// Tables Container
|
|
||||||
HBox tablesContainer = new HBox(20);
|
|
||||||
tablesContainer.setAlignment(Pos.TOP_CENTER);
|
|
||||||
|
|
||||||
// Vehicle Type Statistics Panel
|
|
||||||
VBox vehicleTypeCard = createVehicleTypePanel();
|
|
||||||
HBox.setHgrow(vehicleTypeCard, Priority.ALWAYS);
|
|
||||||
|
|
||||||
// Intersection Statistics Panel
|
|
||||||
VBox intersectionCard = createIntersectionPanel();
|
|
||||||
HBox.setHgrow(intersectionCard, Priority.ALWAYS);
|
|
||||||
|
|
||||||
tablesContainer.getChildren().addAll(vehicleTypeCard, intersectionCard);
|
|
||||||
|
|
||||||
mainContent.getChildren().addAll(globalStatsCard, tablesContainer);
|
|
||||||
|
|
||||||
return mainContent;
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
grid.getStyleClass().add("card-content");
|
|
||||||
grid.setHgap(40);
|
|
||||||
grid.setVgap(15);
|
|
||||||
grid.setAlignment(Pos.CENTER);
|
|
||||||
|
|
||||||
// Initialize labels
|
|
||||||
lblVehiclesGenerated = createStatValueLabel("0");
|
|
||||||
lblVehiclesCompleted = createStatValueLabel("0");
|
|
||||||
lblVehiclesInTransit = createStatValueLabel("0");
|
|
||||||
lblAvgSystemTime = createStatValueLabel("0.00 s");
|
|
||||||
lblAvgWaitingTime = createStatValueLabel("0.00 s");
|
|
||||||
|
|
||||||
// Add labels with descriptions
|
|
||||||
addStatRow(grid, 0, 0, "Total Vehicles Generated", lblVehiclesGenerated);
|
|
||||||
addStatRow(grid, 1, 0, "Total Vehicles Completed", lblVehiclesCompleted);
|
|
||||||
addStatRow(grid, 2, 0, "Vehicles In Transit", lblVehiclesInTransit);
|
|
||||||
addStatRow(grid, 0, 1, "Average System Time", lblAvgSystemTime);
|
|
||||||
addStatRow(grid, 1, 1, "Average Waiting Time", lblAvgWaitingTime);
|
|
||||||
|
|
||||||
card.getChildren().addAll(cardHeader, grid);
|
|
||||||
return card;
|
|
||||||
}
|
|
||||||
|
|
||||||
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.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
|
||||||
vehicleTypeTable.setPrefHeight(300);
|
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, String> typeCol = new TableColumn<>("Vehicle Type");
|
|
||||||
typeCol.setCellValueFactory(new PropertyValueFactory<>("vehicleType"));
|
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, Integer> countCol = new TableColumn<>("Count");
|
|
||||||
countCol.setCellValueFactory(new PropertyValueFactory<>("count"));
|
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, String> avgWaitCol = new TableColumn<>("Avg Wait Time");
|
|
||||||
avgWaitCol.setCellValueFactory(new PropertyValueFactory<>("avgWaitTime"));
|
|
||||||
|
|
||||||
vehicleTypeTable.getColumns().addAll(typeCol, countCol, avgWaitCol);
|
|
||||||
|
|
||||||
card.getChildren().addAll(cardHeader, vehicleTypeTable);
|
|
||||||
return card;
|
|
||||||
}
|
|
||||||
|
|
||||||
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.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
|
||||||
intersectionTable.setPrefHeight(300);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, String> idCol = new TableColumn<>("Intersection ID");
|
|
||||||
idCol.setCellValueFactory(new PropertyValueFactory<>("intersectionId"));
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> arrivalsCol = new TableColumn<>("Total Arrivals");
|
|
||||||
arrivalsCol.setCellValueFactory(new PropertyValueFactory<>("arrivals"));
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> departuresCol = new TableColumn<>("Total Departures");
|
|
||||||
departuresCol.setCellValueFactory(new PropertyValueFactory<>("departures"));
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> queueCol = new TableColumn<>("Current Queue");
|
|
||||||
queueCol.setCellValueFactory(new PropertyValueFactory<>("queueSize"));
|
|
||||||
|
|
||||||
intersectionTable.getColumns().addAll(idCol, arrivalsCol, departuresCol, queueCol);
|
|
||||||
|
|
||||||
card.getChildren().addAll(cardHeader, intersectionTable);
|
|
||||||
return card;
|
|
||||||
}
|
|
||||||
|
|
||||||
private HBox createFooter() {
|
|
||||||
HBox footer = new HBox(10);
|
|
||||||
footer.getStyleClass().add("footer");
|
|
||||||
footer.setAlignment(Pos.CENTER_LEFT);
|
|
||||||
|
|
||||||
Label statusLabel = new Label("Status:");
|
|
||||||
statusLabel.getStyleClass().add("footer-text");
|
|
||||||
statusLabel.setStyle("-fx-font-weight: bold;");
|
|
||||||
|
|
||||||
Circle statusIndicator = new Circle(6);
|
|
||||||
statusIndicator.setFill(javafx.scene.paint.Color.LIME);
|
|
||||||
|
|
||||||
Label statusText = new Label("Connected and Receiving Data");
|
|
||||||
statusText.getStyleClass().add("footer-text");
|
|
||||||
|
|
||||||
lblLastUpdate = new Label("Last Update: --:--:--");
|
|
||||||
lblLastUpdate.getStyleClass().add("footer-text");
|
|
||||||
|
|
||||||
Region spacer = new Region();
|
|
||||||
HBox.setHgrow(spacer, Priority.ALWAYS);
|
|
||||||
|
|
||||||
footer.getChildren().addAll(statusLabel, statusIndicator, statusText, spacer, lblLastUpdate);
|
|
||||||
|
|
||||||
return footer;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Label createStatValueLabel(String initialValue) {
|
|
||||||
Label label = new Label(initialValue);
|
|
||||||
label.getStyleClass().add("stat-value");
|
|
||||||
return label;
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
descLabel.getStyleClass().add("stat-label");
|
|
||||||
|
|
||||||
container.getChildren().addAll(descLabel, valueLabel);
|
|
||||||
|
|
||||||
grid.add(container, colGroup, row);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void startPeriodicUpdates() {
|
|
||||||
updateScheduler = Executors.newSingleThreadScheduledExecutor();
|
|
||||||
updateScheduler.scheduleAtFixedRate(() -> {
|
|
||||||
Platform.runLater(this::updateUI);
|
|
||||||
}, 0, 5, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateUI() {
|
|
||||||
// Update global statistics
|
|
||||||
lblVehiclesGenerated.setText(String.valueOf(statistics.getTotalVehiclesGenerated()));
|
|
||||||
lblVehiclesCompleted.setText(String.valueOf(statistics.getTotalVehiclesCompleted()));
|
|
||||||
lblVehiclesInTransit.setText(String.valueOf(
|
|
||||||
statistics.getTotalVehiclesGenerated() - statistics.getTotalVehiclesCompleted()));
|
|
||||||
lblAvgSystemTime.setText(String.format("%.2f s", statistics.getAverageSystemTime() / 1000.0));
|
|
||||||
lblAvgWaitingTime.setText(String.format("%.2f s", statistics.getAverageWaitingTime() / 1000.0));
|
|
||||||
lblLastUpdate.setText(String.format("Last Update: %tT", statistics.getLastUpdateTime()));
|
|
||||||
|
|
||||||
// Update vehicle type table
|
|
||||||
vehicleTypeTable.getItems().clear();
|
|
||||||
for (VehicleType type : VehicleType.values()) {
|
|
||||||
int count = statistics.getVehicleTypeCount(type);
|
|
||||||
double avgWait = statistics.getAverageWaitingTimeByType(type);
|
|
||||||
vehicleTypeTable.getItems().add(new VehicleTypeRow(
|
|
||||||
type.toString(), count, String.format("%.2f s", avgWait / 1000.0)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update intersection table
|
|
||||||
intersectionTable.getItems().clear();
|
|
||||||
Map<String, DashboardStatistics.IntersectionStats> intersectionStats = statistics.getAllIntersectionStats();
|
|
||||||
for (DashboardStatistics.IntersectionStats stats : intersectionStats.values()) {
|
|
||||||
intersectionTable.getItems().add(new IntersectionRow(
|
|
||||||
stats.getIntersectionId(),
|
|
||||||
stats.getTotalArrivals(),
|
|
||||||
stats.getTotalDepartures(),
|
|
||||||
stats.getCurrentQueueSize()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void shutdown() {
|
|
||||||
System.out.println("Shutting down Dashboard UI...");
|
|
||||||
|
|
||||||
if (updateScheduler != null && !updateScheduler.isShutdown()) {
|
|
||||||
updateScheduler.shutdownNow();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (server != null) {
|
|
||||||
server.stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
Platform.exit();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void showErrorAlert(String title, String message) {
|
|
||||||
Alert alert = new Alert(Alert.AlertType.ERROR);
|
|
||||||
alert.setTitle(title);
|
|
||||||
alert.setHeaderText(null);
|
|
||||||
alert.setContentText(message);
|
|
||||||
alert.showAndWait();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
launch(args);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inner classes for TableView data models
|
|
||||||
public static class VehicleTypeRow {
|
|
||||||
private final String vehicleType;
|
|
||||||
private final int count;
|
|
||||||
private final String avgWaitTime;
|
|
||||||
|
|
||||||
public VehicleTypeRow(String vehicleType, int count, String avgWaitTime) {
|
|
||||||
this.vehicleType = vehicleType;
|
|
||||||
this.count = count;
|
|
||||||
this.avgWaitTime = avgWaitTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getVehicleType() {
|
|
||||||
return vehicleType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getCount() {
|
|
||||||
return count;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAvgWaitTime() {
|
|
||||||
return avgWaitTime;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class IntersectionRow {
|
|
||||||
private final String intersectionId;
|
|
||||||
private final int arrivals;
|
|
||||||
private final int departures;
|
|
||||||
private final int queueSize;
|
|
||||||
|
|
||||||
public IntersectionRow(String intersectionId, int arrivals, int departures, int queueSize) {
|
|
||||||
this.intersectionId = intersectionId;
|
|
||||||
this.arrivals = arrivals;
|
|
||||||
this.departures = departures;
|
|
||||||
this.queueSize = queueSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getIntersectionId() {
|
|
||||||
return intersectionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getArrivals() {
|
|
||||||
return arrivals;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getDepartures() {
|
|
||||||
return departures;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getQueueSize() {
|
|
||||||
return queueSize;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import sd.model.MessageType;
|
|
||||||
import sd.protocol.MessageProtocol;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Message wrapper for sending statistics to the dashboard.
|
|
||||||
*/
|
|
||||||
public class StatsMessage implements MessageProtocol {
|
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
private final String sourceNode;
|
|
||||||
private final String destinationNode;
|
|
||||||
private final StatsUpdatePayload payload;
|
|
||||||
|
|
||||||
public StatsMessage(String sourceNode, StatsUpdatePayload payload) {
|
|
||||||
this.sourceNode = sourceNode;
|
|
||||||
this.destinationNode = "DashboardServer";
|
|
||||||
this.payload = payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public MessageType getType() {
|
|
||||||
return MessageType.STATS_UPDATE;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object getPayload() {
|
|
||||||
return payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getSourceNode() {
|
|
||||||
return sourceNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getDestinationNode() {
|
|
||||||
return destinationNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return String.format("StatsMessage[from=%s, to=%s, payload=%s]",
|
|
||||||
sourceNode, destinationNode, payload);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import java.io.Serializable;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Data transfer object for statistics updates to the dashboard.
|
|
||||||
* Use -1 for fields not being updated in this message.
|
|
||||||
*/
|
|
||||||
public class StatsUpdatePayload implements Serializable {
|
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
private int totalVehiclesGenerated = -1;
|
|
||||||
private int totalVehiclesCompleted = -1;
|
|
||||||
private long totalSystemTime = -1;
|
|
||||||
private long totalWaitingTime = -1;
|
|
||||||
|
|
||||||
private int intersectionArrivals = 0;
|
|
||||||
private int intersectionDepartures = 0;
|
|
||||||
private int intersectionQueueSize = 0;
|
|
||||||
|
|
||||||
private Map<VehicleType, Integer> vehicleTypeCounts;
|
|
||||||
private Map<VehicleType, Long> vehicleTypeWaitTimes;
|
|
||||||
|
|
||||||
public StatsUpdatePayload() {
|
|
||||||
this.vehicleTypeCounts = new HashMap<>();
|
|
||||||
this.vehicleTypeWaitTimes = new HashMap<>();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalVehiclesGenerated() {
|
|
||||||
return totalVehiclesGenerated;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTotalVehiclesCompleted() {
|
|
||||||
return totalVehiclesCompleted;
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getTotalSystemTime() {
|
|
||||||
return totalSystemTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getTotalWaitingTime() {
|
|
||||||
return totalWaitingTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIntersectionArrivals() {
|
|
||||||
return intersectionArrivals;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIntersectionDepartures() {
|
|
||||||
return intersectionDepartures;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIntersectionQueueSize() {
|
|
||||||
return intersectionQueueSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<VehicleType, Integer> getVehicleTypeCounts() {
|
|
||||||
return vehicleTypeCounts;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<VehicleType, Long> getVehicleTypeWaitTimes() {
|
|
||||||
return vehicleTypeWaitTimes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setTotalVehiclesGenerated(int totalVehiclesGenerated) {
|
|
||||||
this.totalVehiclesGenerated = totalVehiclesGenerated;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setTotalVehiclesCompleted(int totalVehiclesCompleted) {
|
|
||||||
this.totalVehiclesCompleted = totalVehiclesCompleted;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setTotalSystemTime(long totalSystemTime) {
|
|
||||||
this.totalSystemTime = totalSystemTime;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setTotalWaitingTime(long totalWaitingTime) {
|
|
||||||
this.totalWaitingTime = totalWaitingTime;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setIntersectionArrivals(int intersectionArrivals) {
|
|
||||||
this.intersectionArrivals = intersectionArrivals;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setIntersectionDepartures(int intersectionDepartures) {
|
|
||||||
this.intersectionDepartures = intersectionDepartures;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setIntersectionQueueSize(int intersectionQueueSize) {
|
|
||||||
this.intersectionQueueSize = intersectionQueueSize;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setVehicleTypeCounts(Map<VehicleType, Integer> vehicleTypeCounts) {
|
|
||||||
this.vehicleTypeCounts = vehicleTypeCounts;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public StatsUpdatePayload setVehicleTypeWaitTimes(Map<VehicleType, Long> vehicleTypeWaitTimes) {
|
|
||||||
this.vehicleTypeWaitTimes = vehicleTypeWaitTimes;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return String.format("StatsUpdatePayload[generated=%d, completed=%d, arrivals=%d, departures=%d, queueSize=%d]",
|
|
||||||
totalVehiclesGenerated, totalVehiclesCompleted, intersectionArrivals,
|
|
||||||
intersectionDepartures, intersectionQueueSize);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
628
main/src/main/java/sd/engine/SimulationEngine.java
Normal file
628
main/src/main/java/sd/engine/SimulationEngine.java
Normal file
@@ -0,0 +1,628 @@
|
|||||||
|
package sd.engine;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.PriorityQueue;
|
||||||
|
|
||||||
|
import sd.config.SimulationConfig;
|
||||||
|
import sd.model.Event;
|
||||||
|
import sd.model.EventType;
|
||||||
|
import sd.model.Intersection;
|
||||||
|
import sd.model.TrafficLight;
|
||||||
|
import sd.model.TrafficLightState;
|
||||||
|
import sd.model.Vehicle;
|
||||||
|
import sd.model.VehicleType;
|
||||||
|
import sd.util.StatisticsCollector;
|
||||||
|
import sd.util.VehicleGenerator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Core simulation engine using discrete event simulation (DES).
|
||||||
|
* * This class orchestrates the entire simulation. It maintains a
|
||||||
|
* {@link PriorityQueue} of {@link Event} objects, representing all
|
||||||
|
* scheduled future actions. The engine processes events in strict
|
||||||
|
* chronological order (based on their timestamp).
|
||||||
|
* * It manages the simulation's state, including:
|
||||||
|
* - The current simulation time ({@code currentTime}).
|
||||||
|
* - The collection of all {@link Intersection} objects.
|
||||||
|
* - The {@link VehicleGenerator} for creating new vehicles.
|
||||||
|
* - The {@link StatisticsCollector} for tracking metrics.
|
||||||
|
*/
|
||||||
|
public class SimulationEngine {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holds all simulation parameters loaded from the properties file.
|
||||||
|
*/
|
||||||
|
private final SimulationConfig config;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The core of the discrete event simulation. Events are pulled from this
|
||||||
|
* queue in order of their timestamp.
|
||||||
|
*/
|
||||||
|
private final PriorityQueue<Event> eventQueue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A map storing all intersections in the simulation, keyed by their ID (e.g., "Cr1").
|
||||||
|
*/
|
||||||
|
private final Map<String, Intersection> intersections;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Responsible for creating new vehicles according to the configured arrival model.
|
||||||
|
*/
|
||||||
|
private final VehicleGenerator vehicleGenerator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collects and calculates statistics throughout the simulation.
|
||||||
|
*/
|
||||||
|
private final StatisticsCollector statisticsCollector;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The current time in the simulation (in virtual seconds).
|
||||||
|
* This time advances based on the timestamp of the event being processed.
|
||||||
|
*/
|
||||||
|
private double currentTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A simple counter to generate unique IDs for vehicles.
|
||||||
|
*/
|
||||||
|
private int vehicleCounter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs a new SimulationEngine.
|
||||||
|
*
|
||||||
|
* @param config The {@link SimulationConfig} object containing all
|
||||||
|
* simulation parameters.
|
||||||
|
*/
|
||||||
|
public SimulationEngine(SimulationConfig config) {
|
||||||
|
this.config = config;
|
||||||
|
this.eventQueue = new PriorityQueue<>();
|
||||||
|
this.intersections = new HashMap<>();
|
||||||
|
this.vehicleGenerator = new VehicleGenerator(config);
|
||||||
|
this.statisticsCollector = new StatisticsCollector(config);
|
||||||
|
this.currentTime = 0.0;
|
||||||
|
this.vehicleCounter = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the simulation. This involves:
|
||||||
|
* 1. Creating all {@link Intersection} and {@link TrafficLight} objects.
|
||||||
|
* 2. Configuring the routing logic between intersections.
|
||||||
|
* 3. Scheduling the initial events (first traffic light changes,
|
||||||
|
* first vehicle generation, and periodic statistics updates).
|
||||||
|
*/
|
||||||
|
public void initialize() {
|
||||||
|
System.out.println("Initializing simulation...");
|
||||||
|
|
||||||
|
setupIntersections();
|
||||||
|
setupRouting();
|
||||||
|
|
||||||
|
// Schedule initial events to "bootstrap" the simulation
|
||||||
|
scheduleTrafficLightEvents();
|
||||||
|
scheduleNextVehicleGeneration(0.0);
|
||||||
|
scheduleStatisticsUpdates();
|
||||||
|
|
||||||
|
System.out.println("Simulation initialized with " + intersections.size() + " intersections");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates all intersections defined in the configuration
|
||||||
|
* and adds their corresponding traffic lights.
|
||||||
|
*/
|
||||||
|
private void setupIntersections() {
|
||||||
|
String[] intersectionIds = {"Cr1", "Cr2", "Cr3", "Cr4", "Cr5"};
|
||||||
|
// Note: "North" is commented out, so it won't be created.
|
||||||
|
String[] directions = {/*"North",*/ "South", "East", "West"};
|
||||||
|
|
||||||
|
for (String id : intersectionIds) {
|
||||||
|
Intersection intersection = new Intersection(id);
|
||||||
|
|
||||||
|
// Add traffic lights for each configured direction
|
||||||
|
for (String direction : directions) {
|
||||||
|
double greenTime = config.getTrafficLightGreenTime(id, direction);
|
||||||
|
double redTime = config.getTrafficLightRedTime(id, direction);
|
||||||
|
|
||||||
|
TrafficLight light = new TrafficLight(
|
||||||
|
id + "-" + direction,
|
||||||
|
direction,
|
||||||
|
greenTime,
|
||||||
|
redTime
|
||||||
|
);
|
||||||
|
|
||||||
|
intersection.addTrafficLight(light);
|
||||||
|
}
|
||||||
|
|
||||||
|
intersections.put(id, intersection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configures how vehicles should be routed between intersections.
|
||||||
|
* This hardcoded logic defines the "map" of the city.
|
||||||
|
* * For example, `intersections.get("Cr1").configureRoute("Cr2", "East");` means
|
||||||
|
* "at intersection Cr1, any vehicle whose *next* destination is Cr2
|
||||||
|
* should be sent to the 'East' traffic light queue."
|
||||||
|
*/
|
||||||
|
private void setupRouting() {
|
||||||
|
// Cr1 routing
|
||||||
|
intersections.get("Cr1").configureRoute("Cr2", "East");
|
||||||
|
intersections.get("Cr1").configureRoute("Cr4", "South");
|
||||||
|
|
||||||
|
// Cr2 routing
|
||||||
|
intersections.get("Cr2").configureRoute("Cr1", "West");
|
||||||
|
intersections.get("Cr2").configureRoute("Cr3", "East");
|
||||||
|
intersections.get("Cr2").configureRoute("Cr5", "South");
|
||||||
|
|
||||||
|
// Cr3 routing
|
||||||
|
intersections.get("Cr3").configureRoute("Cr2", "West");
|
||||||
|
intersections.get("Cr3").configureRoute("S", "South"); // "S" is the exit
|
||||||
|
|
||||||
|
// Cr4 routing
|
||||||
|
//intersections.get("Cr4").configureRoute("Cr1", "North");
|
||||||
|
intersections.get("Cr4").configureRoute("Cr5", "East");
|
||||||
|
|
||||||
|
// Cr5 routing
|
||||||
|
//intersections.get("Cr5").configureRoute("Cr2", "North");
|
||||||
|
//intersections.get("Cr5").configureRoute("Cr4", "West");
|
||||||
|
intersections.get("Cr5").configureRoute("S", "East"); // "S" is the exit
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedules the initial {@link EventType#TRAFFIC_LIGHT_CHANGE} event
|
||||||
|
* for every traffic light in the simulation.
|
||||||
|
* A small random delay is added to "stagger" the lights, preventing
|
||||||
|
* all of them from changing at the exact same time at t=0.
|
||||||
|
*/
|
||||||
|
private void scheduleTrafficLightEvents() {
|
||||||
|
for (Intersection intersection : intersections.values()) {
|
||||||
|
for (TrafficLight light : intersection.getTrafficLights()) {
|
||||||
|
// Start with lights in RED state, schedule first GREEN change
|
||||||
|
// Stagger the start times slightly to avoid all lights changing at once
|
||||||
|
double staggerDelay = Math.random() * 1.5;
|
||||||
|
scheduleTrafficLightChange(light, intersection.getId(), staggerDelay);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates and schedules a new {@link EventType#TRAFFIC_LIGHT_CHANGE} event.
|
||||||
|
* The event is scheduled to occur at {@code currentTime + delay}.
|
||||||
|
*
|
||||||
|
* @param light The {@link TrafficLight} that will change state.
|
||||||
|
* @param intersectionId The ID of the intersection where the light is located.
|
||||||
|
* @param delay The time (in seconds) from {@code currentTime} when the change should occur.
|
||||||
|
*/
|
||||||
|
private void scheduleTrafficLightChange(TrafficLight light, String intersectionId, double delay) {
|
||||||
|
double changeTime = currentTime + delay;
|
||||||
|
Event event = new Event(changeTime, EventType.TRAFFIC_LIGHT_CHANGE, light, intersectionId);
|
||||||
|
eventQueue.offer(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedules the next {@link EventType#VEHICLE_GENERATION} event.
|
||||||
|
* The time of the next arrival is determined by the {@link VehicleGenerator}.
|
||||||
|
*
|
||||||
|
* @param baseTime The time from which to calculate the next arrival (usually {@code currentTime}).
|
||||||
|
*/
|
||||||
|
private void scheduleNextVehicleGeneration(double baseTime) {
|
||||||
|
// Get the absolute time for the next arrival.
|
||||||
|
double nextArrivalTime = vehicleGenerator.getNextArrivalTime(baseTime);
|
||||||
|
|
||||||
|
// Only schedule the event if it's within the simulation's total duration.
|
||||||
|
if (nextArrivalTime < config.getSimulationDuration()) {
|
||||||
|
Event event = new Event(nextArrivalTime, EventType.VEHICLE_GENERATION, null, null);
|
||||||
|
eventQueue.offer(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedules all periodic {@link EventType#STATISTICS_UPDATE} events
|
||||||
|
* for the entire duration of the simulation.
|
||||||
|
*/
|
||||||
|
private void scheduleStatisticsUpdates() {
|
||||||
|
double interval = config.getStatisticsUpdateInterval();
|
||||||
|
double duration = config.getSimulationDuration();
|
||||||
|
|
||||||
|
for (double time = interval; time < duration; time += interval) {
|
||||||
|
Event event = new Event(time, EventType.STATISTICS_UPDATE, null, null);
|
||||||
|
eventQueue.offer(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs the main simulation loop.
|
||||||
|
* The loop continues as long as there are events in the queue and
|
||||||
|
* the {@code currentTime} is less than the total simulation duration.
|
||||||
|
* * In each iteration, it:
|
||||||
|
* 1. Polls the next event from the {@link #eventQueue}.
|
||||||
|
* 2. Advances {@link #currentTime} to the event's timestamp.
|
||||||
|
* 3. Calls {@link #processEvent(Event)} to handle the event.
|
||||||
|
* * After the loop, it prints the final statistics.
|
||||||
|
*/
|
||||||
|
public void run() {
|
||||||
|
System.out.println("Starting simulation...");
|
||||||
|
double duration = config.getSimulationDuration();
|
||||||
|
|
||||||
|
while (!eventQueue.isEmpty() && currentTime < duration) {
|
||||||
|
// Get the next event in chronological order
|
||||||
|
Event event = eventQueue.poll();
|
||||||
|
|
||||||
|
// Advance simulation time to this event's time
|
||||||
|
currentTime = event.getTimestamp();
|
||||||
|
|
||||||
|
// Process the event
|
||||||
|
processEvent(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("\nSimulation completed at t=" + String.format("%.2f", currentTime) + "s");
|
||||||
|
printFinalStatistics();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main event processing logic.
|
||||||
|
* Delegates the event to the appropriate handler method based on its {@link EventType}.
|
||||||
|
*
|
||||||
|
* @param event The {@link Event} to be processed.
|
||||||
|
*/
|
||||||
|
private void processEvent(Event event) {
|
||||||
|
switch (event.getType()) {
|
||||||
|
case VEHICLE_GENERATION -> handleVehicleGeneration();
|
||||||
|
|
||||||
|
case VEHICLE_ARRIVAL -> handleVehicleArrival(event);
|
||||||
|
|
||||||
|
case TRAFFIC_LIGHT_CHANGE -> handleTrafficLightChange(event);
|
||||||
|
|
||||||
|
case CROSSING_START -> handleCrossingStart(event);
|
||||||
|
|
||||||
|
case CROSSING_END -> handleCrossingEnd(event);
|
||||||
|
|
||||||
|
case STATISTICS_UPDATE -> handleStatisticsUpdate();
|
||||||
|
|
||||||
|
default -> System.err.println("Unknown event type: " + event.getType());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles {@link EventType#VEHICLE_GENERATION}.
|
||||||
|
* 1. Creates a new {@link Vehicle} using the {@link #vehicleGenerator}.
|
||||||
|
* 2. Records the generation event with the {@link #statisticsCollector}.
|
||||||
|
* 3. Schedules a {@link EventType#VEHICLE_ARRIVAL} event for the vehicle
|
||||||
|
* at its first destination intersection.
|
||||||
|
* 4. Schedules the *next* {@link EventType#VEHICLE_GENERATION} event.
|
||||||
|
* (Note: This line is commented out in the original, which might be a bug,
|
||||||
|
* as it implies only one vehicle is ever generated. It should likely be active.)
|
||||||
|
*/
|
||||||
|
private void handleVehicleGeneration() {
|
||||||
|
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
|
||||||
|
|
||||||
|
System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n",
|
||||||
|
currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute());
|
||||||
|
|
||||||
|
// Register with statistics collector
|
||||||
|
statisticsCollector.recordVehicleGeneration(vehicle, currentTime);
|
||||||
|
|
||||||
|
// Schedule arrival at first intersection
|
||||||
|
String firstIntersection = vehicle.getCurrentDestination();
|
||||||
|
if (firstIntersection != null && !firstIntersection.equals("S")) {
|
||||||
|
// Assume minimal travel time to first intersection (e.g., 1-3 seconds)
|
||||||
|
double arrivalTime = currentTime + 1.0 + Math.random() * 2.0;
|
||||||
|
Event arrivalEvent = new Event(arrivalTime, EventType.VEHICLE_ARRIVAL, vehicle, firstIntersection);
|
||||||
|
eventQueue.offer(arrivalEvent);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedule next vehicle generation
|
||||||
|
// This was commented out in the original file.
|
||||||
|
// For a continuous simulation, it should be enabled:
|
||||||
|
scheduleNextVehicleGeneration(currentTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles {@link EventType#VEHICLE_ARRIVAL} at an intersection.
|
||||||
|
* 1. Records the arrival for statistics.
|
||||||
|
* 2. Advances the vehicle's internal route planner to its *next* destination.
|
||||||
|
* 3. If the next destination is the exit ("S") or null,
|
||||||
|
* the vehicle exits the system via {@link #handleVehicleExit(Vehicle)}.
|
||||||
|
* 4. Otherwise, the vehicle is placed in the correct queue at the
|
||||||
|
* current intersection using {@link Intersection#receiveVehicle(Vehicle)}.
|
||||||
|
* 5. Attempts to process the vehicle immediately if its light is green.
|
||||||
|
*
|
||||||
|
* @param event The arrival event, containing the {@link Vehicle} and intersection ID.
|
||||||
|
*/
|
||||||
|
private void handleVehicleArrival(Event event) {
|
||||||
|
Vehicle vehicle = (Vehicle) event.getData();
|
||||||
|
String intersectionId = event.getLocation();
|
||||||
|
|
||||||
|
Intersection intersection = intersections.get(intersectionId);
|
||||||
|
if (intersection == null) {
|
||||||
|
System.err.println("Unknown intersection: " + intersectionId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.printf("[t=%.2f] Vehicle %s arrived at %s%n",
|
||||||
|
currentTime, vehicle.getId(), intersectionId);
|
||||||
|
|
||||||
|
// Record arrival time (used to calculate waiting time later)
|
||||||
|
statisticsCollector.recordVehicleArrival(vehicle, intersectionId, currentTime);
|
||||||
|
|
||||||
|
// Advance the vehicle's route to the *next* stop
|
||||||
|
// (it has now arrived at its *current* destination)
|
||||||
|
boolean hasNext = vehicle.advanceRoute();
|
||||||
|
|
||||||
|
if (!hasNext) {
|
||||||
|
// This was the last stop
|
||||||
|
handleVehicleExit(vehicle);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String nextDestination = vehicle.getCurrentDestination();
|
||||||
|
if (nextDestination == null || "S".equals(nextDestination)) {
|
||||||
|
// Next stop is the exit
|
||||||
|
handleVehicleExit(vehicle);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add vehicle to the appropriate traffic light queue based on its next destination
|
||||||
|
intersection.receiveVehicle(vehicle);
|
||||||
|
|
||||||
|
// Try to process the vehicle immediately if its light is already green
|
||||||
|
tryProcessVehicle(vehicle, intersection);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if a newly arrived vehicle (or a vehicle in a queue
|
||||||
|
* that just turned green) can start crossing.
|
||||||
|
*
|
||||||
|
* @param vehicle The vehicle to process.
|
||||||
|
* @param intersection The intersection where the vehicle is.
|
||||||
|
*/
|
||||||
|
private void tryProcessVehicle(Vehicle vehicle, Intersection intersection) { //FIXME
|
||||||
|
// Find the direction (and light) this vehicle is queued at
|
||||||
|
// This logic is a bit flawed: it just finds the *first* non-empty queue
|
||||||
|
// A better approach would be to get the light from the vehicle's route
|
||||||
|
String direction = intersection.getTrafficLights().stream()
|
||||||
|
.filter(tl -> tl.getQueueSize() > 0)
|
||||||
|
.map(TrafficLight::getDirection)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (direction != null) {
|
||||||
|
TrafficLight light = intersection.getTrafficLight(direction);
|
||||||
|
// If the light is green and it's the correct one...
|
||||||
|
if (light != null && light.getState() == TrafficLightState.GREEN) {
|
||||||
|
// ...remove the vehicle from the queue (if it's at the front)
|
||||||
|
Vehicle v = light.removeVehicle();
|
||||||
|
if (v != null) {
|
||||||
|
// ...and schedule its crossing.
|
||||||
|
scheduleCrossing(v, intersection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedules the crossing for a vehicle that has just been dequeued
|
||||||
|
* from a green light.
|
||||||
|
* 1. Calculates and records the vehicle's waiting time.
|
||||||
|
* 2. Schedules an immediate {@link EventType#CROSSING_START} event.
|
||||||
|
*
|
||||||
|
* @param vehicle The {@link Vehicle} that is crossing.
|
||||||
|
* @param intersection The {@link Intersection} it is crossing.
|
||||||
|
*/
|
||||||
|
private void scheduleCrossing(Vehicle vehicle, Intersection intersection) {
|
||||||
|
// Calculate time spent waiting at the red light
|
||||||
|
double waitTime = currentTime - statisticsCollector.getArrivalTime(vehicle);
|
||||||
|
vehicle.addWaitingTime(waitTime);
|
||||||
|
|
||||||
|
// Schedule crossing start event *now*
|
||||||
|
Event crossingStart = new Event(currentTime, EventType.CROSSING_START, vehicle, intersection.getId());
|
||||||
|
processEvent(crossingStart); // Process immediately
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles {@link EventType#CROSSING_START}.
|
||||||
|
* 1. Determines the crossing time based on vehicle type.
|
||||||
|
* 2. Schedules a {@link EventType#CROSSING_END} event to occur
|
||||||
|
* at {@code currentTime + crossingTime}.
|
||||||
|
*
|
||||||
|
* @param event The crossing start event.
|
||||||
|
*/
|
||||||
|
private void handleCrossingStart(Event event) {
|
||||||
|
Vehicle vehicle = (Vehicle) event.getData();
|
||||||
|
String intersectionId = event.getLocation();
|
||||||
|
|
||||||
|
double crossingTime = getCrossingTime(vehicle.getType());
|
||||||
|
|
||||||
|
System.out.printf("[t=%.2f] Vehicle %s started crossing at %s (duration=%.2fs)%n",
|
||||||
|
currentTime, vehicle.getId(), intersectionId, crossingTime);
|
||||||
|
|
||||||
|
// Schedule the *end* of the crossing
|
||||||
|
double endTime = currentTime + crossingTime;
|
||||||
|
Event crossingEnd = new Event(endTime, EventType.CROSSING_END, vehicle, intersectionId);
|
||||||
|
eventQueue.offer(crossingEnd);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles {@link EventType#CROSSING_END}.
|
||||||
|
* 1. Updates intersection and vehicle statistics.
|
||||||
|
* 2. Checks the vehicle's *next* destination.
|
||||||
|
* 3. If the next destination is the exit ("S"), call {@link #handleVehicleExit(Vehicle)}.
|
||||||
|
* 4. Otherwise, schedule a {@link EventType#VEHICLE_ARRIVAL} event at the
|
||||||
|
* *next* intersection, after some travel time.
|
||||||
|
*
|
||||||
|
* @param event The crossing end event.
|
||||||
|
*/
|
||||||
|
private void handleCrossingEnd(Event event) {
|
||||||
|
Vehicle vehicle = (Vehicle) event.getData();
|
||||||
|
String intersectionId = event.getLocation();
|
||||||
|
|
||||||
|
// Update stats
|
||||||
|
Intersection intersection = intersections.get(intersectionId);
|
||||||
|
if (intersection != null) {
|
||||||
|
intersection.incrementVehiclesSent();
|
||||||
|
}
|
||||||
|
|
||||||
|
double crossingTime = getCrossingTime(vehicle.getType());
|
||||||
|
vehicle.addCrossingTime(crossingTime);
|
||||||
|
|
||||||
|
System.out.printf("[t=%.2f] Vehicle %s finished crossing at %s%n",
|
||||||
|
currentTime, vehicle.getId(), intersectionId);
|
||||||
|
|
||||||
|
// Decide what to do next
|
||||||
|
String nextDest = vehicle.getCurrentDestination();
|
||||||
|
if (nextDest != null && !nextDest.equals("S")) {
|
||||||
|
// Route to the *next* intersection
|
||||||
|
// Assume 5-10 seconds travel time between intersections
|
||||||
|
double travelTime = 5.0 + Math.random() * 5.0;
|
||||||
|
double arrivalTime = currentTime + travelTime;
|
||||||
|
Event arrivalEvent = new Event(arrivalTime, EventType.VEHICLE_ARRIVAL, vehicle, nextDest);
|
||||||
|
eventQueue.offer(arrivalEvent);
|
||||||
|
} else {
|
||||||
|
// Reached the exit
|
||||||
|
handleVehicleExit(vehicle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles a vehicle exiting the simulation.
|
||||||
|
* Records final statistics for the vehicle.
|
||||||
|
*
|
||||||
|
* @param vehicle The {@link Vehicle} that has completed its route.
|
||||||
|
*/
|
||||||
|
private void handleVehicleExit(Vehicle vehicle) {
|
||||||
|
System.out.printf("[t=%.2f] Vehicle %s exited the system (wait=%.2fs, travel=%.2fs)%n",
|
||||||
|
currentTime, vehicle.getId(),
|
||||||
|
vehicle.getTotalWaitingTime(),
|
||||||
|
vehicle.getTotalTravelTime(currentTime));
|
||||||
|
|
||||||
|
// Record the exit for final statistics calculation
|
||||||
|
statisticsCollector.recordVehicleExit(vehicle, currentTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles {@link EventType#TRAFFIC_LIGHT_CHANGE}.
|
||||||
|
* 1. Toggles the light's state (RED to GREEN or GREEN to RED).
|
||||||
|
* 2. If the light just turned GREEN, call {@link #processGreenLight(TrafficLight, Intersection)}
|
||||||
|
* to process any waiting vehicles.
|
||||||
|
* 3. Schedules the *next* state change for this light based on its
|
||||||
|
* green/red time duration.
|
||||||
|
*
|
||||||
|
* @param event The light change event.
|
||||||
|
*/
|
||||||
|
private void handleTrafficLightChange(Event event) {
|
||||||
|
TrafficLight light = (TrafficLight) event.getData();
|
||||||
|
String intersectionId = event.getLocation();
|
||||||
|
|
||||||
|
// Toggle state
|
||||||
|
TrafficLightState newState = (light.getState() == TrafficLightState.RED)
|
||||||
|
? TrafficLightState.GREEN
|
||||||
|
: TrafficLightState.RED;
|
||||||
|
|
||||||
|
light.changeState(newState);
|
||||||
|
|
||||||
|
System.out.printf("[t=%.2f] Traffic light %s changed to %s%n",
|
||||||
|
currentTime, light.getId(), newState);
|
||||||
|
|
||||||
|
// If changed to GREEN, process waiting vehicles
|
||||||
|
if (newState == TrafficLightState.GREEN) {
|
||||||
|
Intersection intersection = intersections.get(intersectionId);
|
||||||
|
if (intersection != null) {
|
||||||
|
processGreenLight(light, intersection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedule the *next* state change for this same light
|
||||||
|
double nextChangeDelay = (newState == TrafficLightState.GREEN)
|
||||||
|
? light.getGreenTime()
|
||||||
|
: light.getRedTime();
|
||||||
|
|
||||||
|
scheduleTrafficLightChange(light, intersectionId, nextChangeDelay);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processes vehicles when a light turns green.
|
||||||
|
* It loops as long as the light is green and there are vehicles in the queue,
|
||||||
|
* dequeuing one vehicle at a time and scheduling its crossing.
|
||||||
|
* * *Note*: This is a simplified model. A real simulation would
|
||||||
|
* account for the *time* it takes each vehicle to cross, processing
|
||||||
|
* one vehicle every {@code crossingTime} seconds. This implementation
|
||||||
|
* processes the entire queue "instantaneously" at the moment
|
||||||
|
* the light turns green.
|
||||||
|
*
|
||||||
|
* @param light The {@link TrafficLight} that just turned green.
|
||||||
|
* @param intersection The {@link Intersection} where the light is.
|
||||||
|
*/
|
||||||
|
private void processGreenLight(TrafficLight light, Intersection intersection) {
|
||||||
|
// While the light is green and vehicles are waiting...
|
||||||
|
while (light.getState() == TrafficLightState.GREEN && light.getQueueSize() > 0) {
|
||||||
|
Vehicle vehicle = light.removeVehicle();
|
||||||
|
if (vehicle != null) {
|
||||||
|
// Dequeue one vehicle and schedule its crossing
|
||||||
|
scheduleCrossing(vehicle, intersection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles {@link EventType#STATISTICS_UPDATE}.
|
||||||
|
* Calls the {@link StatisticsCollector} to print the current
|
||||||
|
* state of the simulation (queue sizes, averages, etc.).
|
||||||
|
*/
|
||||||
|
private void handleStatisticsUpdate() {
|
||||||
|
System.out.printf("\n=== Statistics at t=%.2f ===%n", currentTime);
|
||||||
|
statisticsCollector.printCurrentStatistics(intersections, currentTime);
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utility method to get the configured crossing time for a given {@link VehicleType}.
|
||||||
|
*
|
||||||
|
* @param type The type of vehicle.
|
||||||
|
* @return The crossing time in seconds.
|
||||||
|
*/
|
||||||
|
private double getCrossingTime(VehicleType type) {
|
||||||
|
return switch (type) {
|
||||||
|
case BIKE -> config.getBikeVehicleCrossingTime();
|
||||||
|
case LIGHT -> config.getLightVehicleCrossingTime();
|
||||||
|
case HEAVY -> config.getHeavyVehicleCrossingTime();
|
||||||
|
default -> 2.0;
|
||||||
|
}; // Default fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prints the final summary of statistics at the end of the simulation.
|
||||||
|
*/
|
||||||
|
private void printFinalStatistics() {
|
||||||
|
System.out.println("\n" + "=".repeat(60));
|
||||||
|
System.out.println("FINAL SIMULATION STATISTICS");
|
||||||
|
System.out.println("=".repeat(60));
|
||||||
|
|
||||||
|
statisticsCollector.printFinalStatistics(intersections, currentTime);
|
||||||
|
|
||||||
|
System.out.println("=".repeat(60));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Public Getters ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the current simulation time.
|
||||||
|
* @return The time in virtual seconds.
|
||||||
|
*/
|
||||||
|
public double getCurrentTime() {
|
||||||
|
return currentTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets a map of all intersections in the simulation.
|
||||||
|
* Returns a copy to prevent external modification.
|
||||||
|
* @return A {@link Map} of intersection IDs to {@link Intersection} objects.
|
||||||
|
*/
|
||||||
|
public Map<String, Intersection> getIntersections() {
|
||||||
|
return new HashMap<>(intersections);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the statistics collector instance.
|
||||||
|
* @return The {@link StatisticsCollector}.
|
||||||
|
*/
|
||||||
|
public StatisticsCollector getStatisticsCollector() {
|
||||||
|
return statisticsCollector;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,118 +9,150 @@ import sd.model.Vehicle;
|
|||||||
/**
|
/**
|
||||||
* Implements the control logic for a single TrafficLight
|
* Implements the control logic for a single TrafficLight
|
||||||
* as a Runnable task that runs in its own Thread.
|
* as a Runnable task that runs in its own Thread.
|
||||||
|
*
|
||||||
*/
|
*/
|
||||||
public class TrafficLightThread implements Runnable {
|
public class TrafficLightThread implements Runnable {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The TrafficLight object (the *model*) that this thread controls.
|
||||||
|
* Contains the queue and the state.
|
||||||
|
*/
|
||||||
private final TrafficLight light;
|
private final TrafficLight light;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The IntersectionProcess (the Process) that "owns" this thread.
|
||||||
|
* Used to call methods on the process, such as sendVehicleToNextDestination().
|
||||||
|
*/
|
||||||
private final IntersectionProcess process;
|
private final IntersectionProcess process;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The simulation configuration, used to get timings (e.g., crossing time).
|
||||||
|
*/
|
||||||
private final SimulationConfig config;
|
private final SimulationConfig config;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Volatile flag to control the graceful shutdown mechanism.
|
||||||
|
* When set to 'false', the 'run()' loop terminates.
|
||||||
|
*/
|
||||||
private volatile boolean running;
|
private volatile boolean running;
|
||||||
|
|
||||||
// Store the thread reference for proper interruption
|
/**
|
||||||
private Thread currentThread;
|
* Constructor for the Traffic Light Thread.
|
||||||
|
*
|
||||||
|
* @param light The TrafficLight object (model) to be controlled.
|
||||||
|
* @param process The parent IntersectionProcess (for callbacks).
|
||||||
|
* @param config The simulation configuration (to get timings).
|
||||||
|
*/
|
||||||
public TrafficLightThread(TrafficLight light, IntersectionProcess process, SimulationConfig config) {
|
public TrafficLightThread(TrafficLight light, IntersectionProcess process, SimulationConfig config) {
|
||||||
this.light = light;
|
this.light = light;
|
||||||
this.process = process;
|
this.process = process;
|
||||||
this.config = config;
|
this.config = config;
|
||||||
this.running = false;
|
this.running = false; // Starts as 'stopped'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The main entry point for the thread.
|
||||||
|
* Implements the GREEN/RED cycle logic extracted from IntersectionProcess.
|
||||||
|
*
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
this.currentThread = Thread.currentThread();
|
|
||||||
this.running = true;
|
this.running = true;
|
||||||
System.out.println("[" + light.getId() + "] Traffic light thread started.");
|
System.out.println("[" + light.getId() + "] Traffic light thread started.");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
while (running && !Thread.currentThread().isInterrupted()) {
|
// Main thread loop, continues while 'running' is true
|
||||||
|
// This 'running' flag is controlled by the parent IntersectionProcess
|
||||||
|
while (running) {
|
||||||
|
|
||||||
// Request permission to turn green (blocks until granted)
|
|
||||||
process.requestGreenLight(light.getDirection());
|
|
||||||
|
|
||||||
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");
|
||||||
|
|
||||||
// Process queue for the duration of the green light
|
// Process vehicles in the queue
|
||||||
long greenDurationMs = (long) (light.getGreenTime() * 1000);
|
processGreenLightQueue();
|
||||||
processGreenLightQueue(greenDurationMs);
|
|
||||||
|
|
||||||
if (!running || Thread.currentThread().isInterrupted())
|
// Wait for green duration
|
||||||
break;
|
Thread.sleep((long) (light.getGreenTime() * 1000)); //
|
||||||
|
|
||||||
|
if (!running) break; // Check flag after sleep
|
||||||
|
|
||||||
// --- 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 {
|
|
||||||
// Always release the green light permission
|
|
||||||
process.releaseGreenLight(light.getDirection());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for red duration
|
// Wait for red duration
|
||||||
Thread.sleep((long) (light.getRedTime() * 1000));
|
Thread.sleep((long) (light.getRedTime() * 1000)); //
|
||||||
|
|
||||||
}
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
|
// Apanha a InterruptedException (outra forma de parar a thread)
|
||||||
System.out.println("[" + light.getId() + "] Traffic light thread interrupted.");
|
System.out.println("[" + light.getId() + "] Traffic light thread interrupted.");
|
||||||
Thread.currentThread().interrupt();
|
this.running = false; // Garante que o loop termina
|
||||||
} finally {
|
}
|
||||||
this.running = false;
|
|
||||||
System.out.println("[" + light.getId() + "] Traffic light thread stopped.");
|
System.out.println("[" + light.getId() + "] Traffic light thread stopped.");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private void processGreenLightQueue(long greenDurationMs) throws InterruptedException {
|
|
||||||
long startTime = System.currentTimeMillis();
|
|
||||||
|
|
||||||
while (running && !Thread.currentThread().isInterrupted()
|
|
||||||
&& light.getState() == TrafficLightState.GREEN) {
|
|
||||||
|
|
||||||
// Check if green time has expired
|
|
||||||
long elapsed = System.currentTimeMillis() - startTime;
|
|
||||||
if (elapsed >= greenDurationMs) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (light.getQueueSize() > 0) {
|
|
||||||
Vehicle vehicle = light.removeVehicle();
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private double getCrossingTimeForVehicle(Vehicle vehicle) {
|
|
||||||
return switch (vehicle.getType()) {
|
|
||||||
case BIKE -> config.getBikeVehicleCrossingTime();
|
|
||||||
case LIGHT -> config.getLightVehicleCrossingTime();
|
|
||||||
case HEAVY -> config.getHeavyVehicleCrossingTime();
|
|
||||||
default -> config.getLightVehicleCrossingTime();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Requests the thread to stop gracefully.
|
* Processes vehicles in the queue while the traffic light is GREEN.
|
||||||
* Sets the running flag and interrupts the thread to unblock any sleep() calls.
|
* Logic extracted from IntersectionProcess.processGreenLight()
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
private void processGreenLightQueue() throws InterruptedException {
|
||||||
|
//
|
||||||
|
while (running && light.getState() == TrafficLightState.GREEN && light.getQueueSize() > 0) {
|
||||||
|
|
||||||
|
Vehicle vehicle = light.removeVehicle(); //
|
||||||
|
|
||||||
|
if (vehicle != null) {
|
||||||
|
// 1. Get the crossing time (t_sem)
|
||||||
|
double crossingTime = getCrossingTimeForVehicle(vehicle); //
|
||||||
|
|
||||||
|
// 2. Simulate the time the vehicle takes to cross
|
||||||
|
Thread.sleep((long) (crossingTime * 1000)); //
|
||||||
|
|
||||||
|
// 3. Update vehicle statistics
|
||||||
|
vehicle.addCrossingTime(crossingTime); //
|
||||||
|
|
||||||
|
// 4. Update intersection statistics
|
||||||
|
|
||||||
|
process.getIntersection().incrementVehiclesSent(); //
|
||||||
|
|
||||||
|
// 5. Call the parent Process to send the vehicle
|
||||||
|
|
||||||
|
process.sendVehicleToNextDestination(vehicle); //
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the crossing time for a vehicle based on its type.
|
||||||
|
* Logic extracted from IntersectionProcess.getCrossingTimeForVehicle()
|
||||||
|
*
|
||||||
|
*
|
||||||
|
* @param vehicle The vehicle.
|
||||||
|
* @return The crossing time in seconds.
|
||||||
|
*/
|
||||||
|
private double getCrossingTimeForVehicle(Vehicle vehicle) {
|
||||||
|
switch (vehicle.getType()) { //
|
||||||
|
case BIKE:
|
||||||
|
return config.getBikeVehicleCrossingTime(); //
|
||||||
|
case LIGHT:
|
||||||
|
return config.getLightVehicleCrossingTime(); //
|
||||||
|
case HEAVY:
|
||||||
|
return config.getHeavyVehicleCrossingTime(); //
|
||||||
|
default:
|
||||||
|
return config.getLightVehicleCrossingTime(); //
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Requests the thread to stop gracefully (graceful shutdown).
|
||||||
|
* Sets the 'running' flag to false. The thread will finish
|
||||||
|
* its current sleep cycle and exit the 'run()' loop.
|
||||||
*/
|
*/
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
this.running = false;
|
this.running = false;
|
||||||
if (currentThread != null && currentThread.isAlive()) {
|
|
||||||
currentThread.interrupt();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
131
main/src/main/java/sd/model/Event.java
Normal file
131
main/src/main/java/sd/model/Event.java
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
45
main/src/main/java/sd/model/EventType.java
Normal file
45
main/src/main/java/sd/model/EventType.java
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -140,16 +140,6 @@ public class Intersection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the direction a vehicle should take to reach a given destination.
|
|
||||||
*
|
|
||||||
* @param destination The next destination (e.g., "Cr3", "S").
|
|
||||||
* @return The direction (e.g., "East"), or null if no route is configured.
|
|
||||||
*/
|
|
||||||
public String getDirectionForDestination(String destination) {
|
|
||||||
return routing.get(destination);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the traffic light controlling the given direction.
|
* Returns the traffic light controlling the given direction.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
package sd.model;
|
package sd.model;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import sd.protocol.MessageProtocol;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a message exchanged between processes in the distributed simulation.
|
* Represents a message exchanged between processes in the distributed simulation.
|
||||||
* Each message has a unique ID, a type, a sender, a destination, and a payload.
|
* Each message has a unique ID, a type, a sender, a destination, and a payload.
|
||||||
* This class implements {@link MessageProtocol} which extends Serializable for network transmission.
|
* This class implements {@link Serializable} to allow transmission over the network.
|
||||||
*/
|
*/
|
||||||
public class Message implements MessageProtocol {
|
public class Message implements Serializable {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
@@ -133,17 +132,6 @@ public class Message implements MessageProtocol {
|
|||||||
return (T) payload;
|
return (T) payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Impl MessageProtocol interface
|
|
||||||
@Override
|
|
||||||
public String getSourceNode() {
|
|
||||||
return senderId;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getDestinationNode() {
|
|
||||||
return destinationId;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return String.format("Message[id=%s, type=%s, from=%s, to=%s, timestamp=%d]",
|
return String.format("Message[id=%s, type=%s, from=%s, to=%s, timestamp=%d]",
|
||||||
|
|||||||
@@ -19,12 +19,6 @@ public enum MessageType {
|
|||||||
*/
|
*/
|
||||||
STATS_UPDATE,
|
STATS_UPDATE,
|
||||||
|
|
||||||
/**
|
|
||||||
* Message to synchronize simulation start time across all processes.
|
|
||||||
* Payload: Start timestamp (long milliseconds)
|
|
||||||
*/
|
|
||||||
SIMULATION_START,
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Message to synchronize traffic light states between processes.
|
* Message to synchronize traffic light states between processes.
|
||||||
* Payload: TrafficLight state and timing information
|
* Payload: TrafficLight state and timing information
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
package sd.model;
|
package sd.model;
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Queue;
|
import java.util.Queue;
|
||||||
import java.util.concurrent.locks.Condition;
|
import java.util.concurrent.locks.Condition;
|
||||||
import java.util.concurrent.locks.Lock;
|
import java.util.concurrent.locks.Lock;
|
||||||
@@ -96,12 +94,6 @@ public class TrafficLight {
|
|||||||
*/
|
*/
|
||||||
private int totalVehiclesProcessed;
|
private int totalVehiclesProcessed;
|
||||||
|
|
||||||
/**
|
|
||||||
* Track when vehicles arrive at this light for wait time calculation.
|
|
||||||
* Maps vehicle ID to arrival timestamp (milliseconds).
|
|
||||||
*/
|
|
||||||
private final Map<String, Long> vehicleArrivalTimes;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new TrafficLight.
|
* Constructs a new TrafficLight.
|
||||||
*
|
*
|
||||||
@@ -123,7 +115,6 @@ public class TrafficLight {
|
|||||||
|
|
||||||
this.greenTime = greenTime;
|
this.greenTime = greenTime;
|
||||||
this.redTime = redTime;
|
this.redTime = redTime;
|
||||||
this.vehicleArrivalTimes = new HashMap<>();
|
|
||||||
this.totalVehiclesProcessed = 0;
|
this.totalVehiclesProcessed = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,7 +128,6 @@ public class TrafficLight {
|
|||||||
lock.lock(); // Acquire the lock
|
lock.lock(); // Acquire the lock
|
||||||
try {
|
try {
|
||||||
queue.offer(vehicle); // Add vehicle to queue
|
queue.offer(vehicle); // Add vehicle to queue
|
||||||
vehicleArrivalTimes.put(vehicle.getId(), System.currentTimeMillis());
|
|
||||||
vehicleAdded.signalAll(); // Signal (for concurrent models)
|
vehicleAdded.signalAll(); // Signal (for concurrent models)
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock(); // Always release the lock
|
lock.unlock(); // Always release the lock
|
||||||
@@ -162,13 +152,6 @@ public class TrafficLight {
|
|||||||
Vehicle vehicle = queue.poll(); // Remove vehicle from queue
|
Vehicle vehicle = queue.poll(); // Remove vehicle from queue
|
||||||
if (vehicle != null) {
|
if (vehicle != null) {
|
||||||
totalVehiclesProcessed++;
|
totalVehiclesProcessed++;
|
||||||
|
|
||||||
// Calculate wait time (time spent in queue)
|
|
||||||
Long arrivalTime = vehicleArrivalTimes.remove(vehicle.getId());
|
|
||||||
if (arrivalTime != null) {
|
|
||||||
double waitTimeSeconds = (System.currentTimeMillis() - arrivalTime) / 1000.0;
|
|
||||||
vehicle.addWaitingTime(waitTimeSeconds);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return vehicle;
|
return vehicle;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 message
|
* * This object is passed around the simulation, primarily inside {@link Event}
|
||||||
* 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).
|
||||||
@@ -70,8 +70,7 @@ public class Vehicle implements Serializable {
|
|||||||
* @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",
|
* @param route The complete list of destination IDs (e.t., ["Cr1", "Cr2", "S"]).
|
||||||
* "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;
|
||||||
@@ -152,8 +151,7 @@ public class Vehicle implements Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The current index pointing to the vehicle's destination in its route
|
* @return The current index pointing to the vehicle's destination in its route list.
|
||||||
* list.
|
|
||||||
*/
|
*/
|
||||||
public int getCurrentRouteIndex() {
|
public int getCurrentRouteIndex() {
|
||||||
return currentRouteIndex;
|
return currentRouteIndex;
|
||||||
@@ -214,6 +212,7 @@ public class Vehicle implements Serializable {
|
|||||||
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,6 +4,7 @@ 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;
|
||||||
@@ -126,7 +127,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 synchronized void sendMessage(MessageProtocol message) throws IOException {
|
public 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");
|
||||||
}
|
}
|
||||||
@@ -171,8 +172,8 @@ public class SocketConnection implements Closeable {
|
|||||||
byte[] data = new byte[length];
|
byte[] data = new byte[length];
|
||||||
dataIn.readFully(data);
|
dataIn.readFully(data);
|
||||||
|
|
||||||
// Deserialize do JSON - use concrete Message class, not interface
|
// Deserialize do JSON
|
||||||
return serializer.deserialize(data, sd.model.Message.class);
|
return serializer.deserialize(data, MessageProtocol.class);
|
||||||
|
|
||||||
} catch (SerializationException e) {
|
} catch (SerializationException e) {
|
||||||
throw new IOException("Failed to deserialize message", e);
|
throw new IOException("Failed to deserialize message", e);
|
||||||
|
|||||||
134
main/src/main/java/sd/serialization/SerializationExample.java
Normal file
134
main/src/main/java/sd/serialization/SerializationExample.java
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
379
main/src/main/java/sd/util/StatisticsCollector.java
Normal file
379
main/src/main/java/sd/util/StatisticsCollector.java
Normal file
@@ -0,0 +1,379 @@
|
|||||||
|
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 {@link sd.engine.SimulationEngine}
|
||||||
|
* 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 {@link sd.engine.SimulationEngine}
|
||||||
|
* 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 {@link sd.engine.SimulationEngine}
|
||||||
|
* 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 {@link sd.engine.SimulationEngine} 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 {@link sd.engine.SimulationEngine}
|
||||||
|
* 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 void recordDeparture() {
|
||||||
|
totalDepartures++;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
/* 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;
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
{
|
|
||||||
"intersections": [
|
|
||||||
{
|
|
||||||
"id": "Cr1",
|
|
||||||
"lights": ["East", "South"],
|
|
||||||
"routes": {
|
|
||||||
"Cr2": "East",
|
|
||||||
"Cr4": "South"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "Cr2",
|
|
||||||
"lights": ["West", "East", "South"],
|
|
||||||
"routes": {
|
|
||||||
"Cr1": "West",
|
|
||||||
"Cr3": "East",
|
|
||||||
"Cr5": "South"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "Cr3",
|
|
||||||
"lights": ["West", "South"],
|
|
||||||
"routes": {
|
|
||||||
"Cr2": "West",
|
|
||||||
"S": "South"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "Cr4",
|
|
||||||
"lights": ["East"],
|
|
||||||
"routes": {
|
|
||||||
"Cr5": "East"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "Cr5",
|
|
||||||
"lights": ["East"],
|
|
||||||
"routes": {
|
|
||||||
"S": "East"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -46,44 +46,54 @@ simulation.arrival.fixed.interval=2.0
|
|||||||
# === TRAFFIC LIGHT TIMINGS ===
|
# === TRAFFIC LIGHT TIMINGS ===
|
||||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
||||||
|
|
||||||
# Intersection 1 (Entry point - balanced)
|
# Intersection 1
|
||||||
trafficlight.Cr1.South.green=20.0
|
trafficlight.Cr1.North.green=30.0
|
||||||
trafficlight.Cr1.South.red=40.0
|
trafficlight.Cr1.North.red=30.0
|
||||||
trafficlight.Cr1.East.green=20.0
|
trafficlight.Cr1.South.green=30.0
|
||||||
trafficlight.Cr1.East.red=40.0
|
trafficlight.Cr1.South.red=30.0
|
||||||
trafficlight.Cr1.West.green=20.0
|
trafficlight.Cr1.East.green=30.0
|
||||||
trafficlight.Cr1.West.red=40.0
|
trafficlight.Cr1.East.red=30.0
|
||||||
|
trafficlight.Cr1.West.green=30.0
|
||||||
|
trafficlight.Cr1.West.red=30.0
|
||||||
|
|
||||||
# Intersection 2 (Main hub - shorter cycles, favor East-West)
|
# Intersection 2
|
||||||
trafficlight.Cr2.South.green=12.0
|
trafficlight.Cr2.North.green=25.0
|
||||||
trafficlight.Cr2.South.red=36.0
|
trafficlight.Cr2.North.red=35.0
|
||||||
trafficlight.Cr2.East.green=18.0
|
trafficlight.Cr2.South.green=25.0
|
||||||
trafficlight.Cr2.East.red=30.0
|
trafficlight.Cr2.South.red=35.0
|
||||||
trafficlight.Cr2.West.green=18.0
|
trafficlight.Cr2.East.green=35.0
|
||||||
trafficlight.Cr2.West.red=30.0
|
trafficlight.Cr2.East.red=25.0
|
||||||
|
trafficlight.Cr2.West.green=35.0
|
||||||
|
trafficlight.Cr2.West.red=25.0
|
||||||
|
|
||||||
# Intersection 3 (Path to exit - favor East)
|
# Intersection 3
|
||||||
trafficlight.Cr3.South.green=15.0
|
trafficlight.Cr3.North.green=30.0
|
||||||
|
trafficlight.Cr3.North.red=30.0
|
||||||
|
trafficlight.Cr3.South.green=30.0
|
||||||
trafficlight.Cr3.South.red=30.0
|
trafficlight.Cr3.South.red=30.0
|
||||||
trafficlight.Cr3.East.green=20.0
|
trafficlight.Cr3.East.green=30.0
|
||||||
trafficlight.Cr3.East.red=25.0
|
trafficlight.Cr3.East.red=30.0
|
||||||
trafficlight.Cr3.West.green=15.0
|
trafficlight.Cr3.West.green=30.0
|
||||||
trafficlight.Cr3.West.red=30.0
|
trafficlight.Cr3.West.red=30.0
|
||||||
|
|
||||||
# Intersection 4 (Favor East toward Cr5)
|
# Intersection 4
|
||||||
trafficlight.Cr4.South.green=15.0
|
trafficlight.Cr4.North.green=30.0
|
||||||
|
trafficlight.Cr4.North.red=30.0
|
||||||
|
trafficlight.Cr4.South.green=30.0
|
||||||
trafficlight.Cr4.South.red=30.0
|
trafficlight.Cr4.South.red=30.0
|
||||||
trafficlight.Cr4.East.green=20.0
|
trafficlight.Cr4.East.green=30.0
|
||||||
trafficlight.Cr4.East.red=25.0
|
trafficlight.Cr4.East.red=30.0
|
||||||
trafficlight.Cr4.West.green=15.0
|
trafficlight.Cr4.West.green=30.0
|
||||||
trafficlight.Cr4.West.red=30.0
|
trafficlight.Cr4.West.red=30.0
|
||||||
|
|
||||||
# Intersection 5 (Near exit - favor East)
|
# Intersection 5
|
||||||
trafficlight.Cr5.South.green=15.0
|
trafficlight.Cr5.North.green=30.0
|
||||||
|
trafficlight.Cr5.North.red=30.0
|
||||||
|
trafficlight.Cr5.South.green=30.0
|
||||||
trafficlight.Cr5.South.red=30.0
|
trafficlight.Cr5.South.red=30.0
|
||||||
trafficlight.Cr5.East.green=22.0
|
trafficlight.Cr5.East.green=30.0
|
||||||
trafficlight.Cr5.East.red=23.0
|
trafficlight.Cr5.East.red=30.0
|
||||||
trafficlight.Cr5.West.green=15.0
|
trafficlight.Cr5.West.green=30.0
|
||||||
trafficlight.Cr5.West.red=30.0
|
trafficlight.Cr5.West.red=30.0
|
||||||
|
|
||||||
# === VEHICLE CONFIGURATION ===
|
# === VEHICLE CONFIGURATION ===
|
||||||
@@ -93,19 +103,11 @@ vehicle.probability.light=0.6
|
|||||||
vehicle.probability.heavy=0.2
|
vehicle.probability.heavy=0.2
|
||||||
|
|
||||||
# Average crossing times (in seconds)
|
# Average crossing times (in seconds)
|
||||||
vehicle.crossing.time.bike=1.0
|
vehicle.crossing.time.bike=1.5
|
||||||
vehicle.crossing.time.light=2.0
|
vehicle.crossing.time.light=2.0
|
||||||
vehicle.crossing.time.heavy=4.0
|
vehicle.crossing.time.heavy=4.0
|
||||||
|
|
||||||
# Travel times between intersections (in seconds)
|
|
||||||
# Base time for light vehicles (cars)
|
|
||||||
vehicle.travel.time.base=8.0
|
|
||||||
# Bike travel time = 0.5 × car travel time
|
|
||||||
vehicle.travel.time.bike.multiplier=0.5
|
|
||||||
# Heavy vehicle travel time = 4 × bike travel time
|
|
||||||
vehicle.travel.time.heavy.multiplier=2.0
|
|
||||||
|
|
||||||
# === STATISTICS ===
|
# === STATISTICS ===
|
||||||
|
|
||||||
# Interval between dashboard updates (seconds)
|
# Interval between dashboard updates (seconds)
|
||||||
statistics.update.interval=1.0
|
statistics.update.interval=10.0
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.InetSocketAddress;
|
import java.io.ObjectOutputStream;
|
||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
@@ -19,7 +19,6 @@ import sd.IntersectionProcess;
|
|||||||
import sd.model.MessageType;
|
import sd.model.MessageType;
|
||||||
import sd.model.Vehicle;
|
import sd.model.Vehicle;
|
||||||
import sd.model.VehicleType;
|
import sd.model.VehicleType;
|
||||||
import sd.protocol.SocketConnection;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for IntersectionProcess - covers initialization, traffic lights,
|
* Tests for IntersectionProcess - covers initialization, traffic lights,
|
||||||
@@ -97,17 +96,11 @@ public class IntersectionProcessTest {
|
|||||||
Files.writeString(configFile, configContent);
|
Files.writeString(configFile, configContent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cleanup after tests
|
||||||
@AfterEach
|
@AfterEach
|
||||||
public void tearDown() {
|
public void tearDown() {
|
||||||
if (intersectionProcess != null) {
|
if (intersectionProcess != null) {
|
||||||
try {
|
|
||||||
// Only shutdown if still running
|
|
||||||
intersectionProcess.shutdown();
|
intersectionProcess.shutdown();
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("Error in tearDown: " + e.getMessage());
|
|
||||||
} finally {
|
|
||||||
intersectionProcess = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,7 +187,7 @@ public class IntersectionProcessTest {
|
|||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
// start server in separate thread
|
// start server in seperate thread
|
||||||
Thread serverThread = new Thread(() -> {
|
Thread serverThread = new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
intersectionProcess.start();
|
intersectionProcess.start();
|
||||||
@@ -204,22 +197,13 @@ public class IntersectionProcessTest {
|
|||||||
});
|
});
|
||||||
serverThread.start();
|
serverThread.start();
|
||||||
|
|
||||||
// Wait for server to actually start with retries
|
Thread.sleep(500); // wait for server to start
|
||||||
boolean serverReady = false;
|
|
||||||
for (int i = 0; i < 20; i++) {
|
// try connecting to check if its running
|
||||||
Thread.sleep(100);
|
try (Socket clientSocket = new Socket("localhost", 18001)) {
|
||||||
try (Socket testSocket = new Socket()) {
|
assertTrue(clientSocket.isConnected());
|
||||||
testSocket.connect(new java.net.InetSocketAddress("localhost", 18001), 500);
|
|
||||||
serverReady = true;
|
|
||||||
break;
|
|
||||||
} catch (IOException e) {
|
|
||||||
// Server not ready yet, continue waiting
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
assertTrue(serverReady, "Server should start and bind to port 18001");
|
|
||||||
|
|
||||||
// Shutdown immediately after confirming server is running
|
|
||||||
intersectionProcess.shutdown();
|
intersectionProcess.shutdown();
|
||||||
serverThread.join(2000);
|
serverThread.join(2000);
|
||||||
}
|
}
|
||||||
@@ -235,17 +219,11 @@ public class IntersectionProcessTest {
|
|||||||
cr2.initialize();
|
cr2.initialize();
|
||||||
|
|
||||||
Thread thread1 = new Thread(() -> {
|
Thread thread1 = new Thread(() -> {
|
||||||
try {
|
try { cr1.start(); } catch (IOException e) { }
|
||||||
cr1.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Thread thread2 = new Thread(() -> {
|
Thread thread2 = new Thread(() -> {
|
||||||
try {
|
try { cr2.start(); } catch (IOException e) { }
|
||||||
cr2.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
thread1.start();
|
thread1.start();
|
||||||
@@ -278,32 +256,30 @@ public class IntersectionProcessTest {
|
|||||||
Thread serverThread = new Thread(() -> {
|
Thread serverThread = new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
intersectionProcess.start();
|
intersectionProcess.start();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) { }
|
||||||
}
|
|
||||||
});
|
});
|
||||||
serverThread.start();
|
serverThread.start();
|
||||||
|
|
||||||
Thread.sleep(500);
|
Thread.sleep(500);
|
||||||
|
|
||||||
try {
|
// create test vehicle
|
||||||
// create test vehicle - FIXED: use 4-parameter constructor
|
|
||||||
java.util.List<String> route = Arrays.asList("Cr2", "Cr3", "S");
|
java.util.List<String> route = Arrays.asList("Cr2", "Cr3", "S");
|
||||||
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 0.0, route);
|
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 0.0, route);
|
||||||
|
|
||||||
// send vehicle from Cr1 to Cr2 - FIXED: use SocketConnection
|
// send vehicle from Cr1 to Cr2
|
||||||
try (Socket socket = new Socket("localhost", 18002);
|
try (Socket socket = new Socket("localhost", 18002)) {
|
||||||
SocketConnection conn = new SocketConnection(socket)) {
|
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
|
|
||||||
TestVehicleMessage message = new TestVehicleMessage("Cr1", "Cr2", vehicle);
|
TestVehicleMessage message = new TestVehicleMessage("Cr1", "Cr2", vehicle);
|
||||||
conn.sendMessage(message);
|
out.writeObject(message);
|
||||||
|
out.flush();
|
||||||
|
|
||||||
Thread.sleep(1000); // wait for processing
|
Thread.sleep(1000); // wait for procesing
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
intersectionProcess.shutdown();
|
intersectionProcess.shutdown();
|
||||||
serverThread.join(2000);
|
serverThread.join(2000);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// routing config tests
|
// routing config tests
|
||||||
|
|
||||||
@@ -336,8 +312,7 @@ public class IntersectionProcessTest {
|
|||||||
Thread serverThread = new Thread(() -> {
|
Thread serverThread = new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
intersectionProcess.start();
|
intersectionProcess.start();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) { }
|
||||||
}
|
|
||||||
});
|
});
|
||||||
serverThread.start();
|
serverThread.start();
|
||||||
|
|
||||||
@@ -355,35 +330,30 @@ public class IntersectionProcessTest {
|
|||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
// Start server in separate thread
|
|
||||||
Thread serverThread = new Thread(() -> {
|
Thread serverThread = new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
intersectionProcess.start();
|
intersectionProcess.start();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) { }
|
||||||
// Expected on shutdown
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
serverThread.start();
|
serverThread.start();
|
||||||
|
|
||||||
// Wait for server to start
|
|
||||||
Thread.sleep(500);
|
Thread.sleep(500);
|
||||||
|
|
||||||
// Shutdown
|
// verify server running
|
||||||
|
try (Socket socket = new Socket("localhost", 18001)) {
|
||||||
|
assertTrue(socket.isConnected());
|
||||||
|
}
|
||||||
|
|
||||||
intersectionProcess.shutdown();
|
intersectionProcess.shutdown();
|
||||||
serverThread.join(2000);
|
serverThread.join(2000);
|
||||||
|
|
||||||
// Give shutdown time to complete
|
// after shutdown conection should fail
|
||||||
Thread.sleep(200);
|
Thread.sleep(500);
|
||||||
|
Exception exception = assertThrows(IOException.class, () -> {
|
||||||
// Verify we cannot connect (server socket is closed)
|
Socket socket = new Socket("localhost", 18001);
|
||||||
boolean connectionFailed = false;
|
socket.close();
|
||||||
try (Socket testSocket = new Socket()) {
|
});
|
||||||
testSocket.connect(new InetSocketAddress("localhost", 18001), 500);
|
assertNotNull(exception);
|
||||||
} catch (IOException e) {
|
|
||||||
connectionFailed = true; // Expected - server should be closed
|
|
||||||
}
|
|
||||||
|
|
||||||
assertTrue(connectionFailed, "Server socket should be closed after shutdown");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -395,8 +365,7 @@ public class IntersectionProcessTest {
|
|||||||
Thread serverThread = new Thread(() -> {
|
Thread serverThread = new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
intersectionProcess.start();
|
intersectionProcess.start();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) { }
|
||||||
}
|
|
||||||
});
|
});
|
||||||
serverThread.start();
|
serverThread.start();
|
||||||
|
|
||||||
@@ -419,34 +388,20 @@ public class IntersectionProcessTest {
|
|||||||
@Test
|
@Test
|
||||||
@Timeout(15)
|
@Timeout(15)
|
||||||
public void testIntegration_TwoIntersectionsVehicleTransfer() throws IOException, InterruptedException {
|
public void testIntegration_TwoIntersectionsVehicleTransfer() throws IOException, InterruptedException {
|
||||||
IntersectionProcess cr1 = null;
|
|
||||||
IntersectionProcess cr2 = null;
|
|
||||||
Thread thread1 = null;
|
|
||||||
Thread thread2 = null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// setup 2 intersections
|
// setup 2 intersections
|
||||||
cr1 = new IntersectionProcess("Cr1", configFile.toString());
|
IntersectionProcess cr1 = new IntersectionProcess("Cr1", configFile.toString());
|
||||||
cr2 = new IntersectionProcess("Cr2", configFile.toString());
|
IntersectionProcess cr2 = new IntersectionProcess("Cr2", configFile.toString());
|
||||||
|
|
||||||
cr1.initialize();
|
cr1.initialize();
|
||||||
cr2.initialize();
|
cr2.initialize();
|
||||||
|
|
||||||
// start both
|
// start both
|
||||||
final IntersectionProcess cr1Final = cr1;
|
Thread thread1 = new Thread(() -> {
|
||||||
thread1 = new Thread(() -> {
|
try { cr1.start(); } catch (IOException e) { }
|
||||||
try {
|
|
||||||
cr1Final.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final IntersectionProcess cr2Final = cr2;
|
Thread thread2 = new Thread(() -> {
|
||||||
thread2 = new Thread(() -> {
|
try { cr2.start(); } catch (IOException e) { }
|
||||||
try {
|
|
||||||
cr2Final.start();
|
|
||||||
} catch (IOException e) {
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
thread1.start();
|
thread1.start();
|
||||||
@@ -454,34 +409,25 @@ public class IntersectionProcessTest {
|
|||||||
|
|
||||||
Thread.sleep(1000); // wait for servers
|
Thread.sleep(1000); // wait for servers
|
||||||
|
|
||||||
// send vehicle to Cr1 that goes to Cr2 - FIXED: use 4-parameter constructor
|
// send vehicle to Cr1 that goes to Cr2
|
||||||
java.util.List<String> route = Arrays.asList("Cr1", "Cr2", "S");
|
java.util.List<String> route = Arrays.asList("Cr1", "Cr2", "S");
|
||||||
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 0.0, route);
|
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 0.0, route);
|
||||||
|
|
||||||
// FIXED: use SocketConnection
|
try (Socket socket = new Socket("localhost", 18001)) {
|
||||||
try (Socket socket = new Socket("localhost", 18001);
|
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
SocketConnection conn = new SocketConnection(socket)) {
|
|
||||||
|
|
||||||
TestVehicleMessage message = new TestVehicleMessage("Entry", "Cr1", vehicle);
|
TestVehicleMessage message = new TestVehicleMessage("Entry", "Cr1", vehicle);
|
||||||
conn.sendMessage(message);
|
out.writeObject(message);
|
||||||
|
out.flush();
|
||||||
|
|
||||||
Thread.sleep(2000); // time for processing
|
Thread.sleep(2000); // time for processing
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
if (cr1 != null) {
|
|
||||||
cr1.shutdown();
|
cr1.shutdown();
|
||||||
}
|
|
||||||
if (cr2 != null) {
|
|
||||||
cr2.shutdown();
|
cr2.shutdown();
|
||||||
}
|
|
||||||
if (thread1 != null) {
|
|
||||||
thread1.join(2000);
|
thread1.join(2000);
|
||||||
}
|
|
||||||
if (thread2 != null) {
|
|
||||||
thread2.join(2000);
|
thread2.join(2000);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testMain_MissingArguments() {
|
public void testMain_MissingArguments() {
|
||||||
|
|||||||
@@ -6,11 +6,15 @@ 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.engine.SimulationEngine;
|
||||||
|
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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -25,7 +29,7 @@ class SimulationTest {
|
|||||||
assertEquals(60.0, config.getSimulationDuration());
|
assertEquals(60.0, config.getSimulationDuration());
|
||||||
assertEquals("POISSON", config.getArrivalModel());
|
assertEquals("POISSON", config.getArrivalModel());
|
||||||
assertEquals(0.5, config.getArrivalRate());
|
assertEquals(0.5, config.getArrivalRate());
|
||||||
assertEquals(1.0, config.getStatisticsUpdateInterval());
|
assertEquals(10.0, config.getStatisticsUpdateInterval());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -42,6 +46,16 @@ 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");
|
||||||
@@ -76,7 +90,36 @@ class SimulationTest {
|
|||||||
assertEquals(TrafficLightState.RED, light.getState());
|
assertEquals(TrafficLightState.RED, light.getState());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Removed testSimulationEngineInitialization as SimulationEngine has been
|
@Test
|
||||||
// removed.
|
void testSimulationEngineInitialization() throws IOException {
|
||||||
|
SimulationConfig config = new SimulationConfig("src/main/resources/simulation.properties");
|
||||||
|
SimulationEngine engine = new SimulationEngine(config);
|
||||||
|
|
||||||
|
engine.initialize();
|
||||||
|
|
||||||
|
assertNotNull(engine.getIntersections());
|
||||||
|
assertEquals(5, engine.getIntersections().size());
|
||||||
|
|
||||||
|
// Check that intersections have traffic lights
|
||||||
|
for (Intersection intersection : engine.getIntersections().values()) {
|
||||||
|
assertEquals(3, intersection.getTrafficLights().size()); // North, South, East, West
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
package sd;
|
package sd;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
|
||||||
|
import sd.model.TrafficLight;
|
||||||
|
import sd.model.TrafficLightState;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import sd.model.TrafficLight;
|
|
||||||
import sd.model.TrafficLightState;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test class to verify traffic light coordination within an intersection.
|
* Test class to verify traffic light coordination within an intersection.
|
||||||
@@ -108,7 +108,7 @@ public class TrafficLightCoordinationTest {
|
|||||||
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("\n✅ Traffic light coordination working correctly!");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -133,8 +133,8 @@ public class TrafficLightCoordinationTest {
|
|||||||
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 60 seconds (enough time for all lights to cycle: 18+18+12 = 48s)
|
// Monitor for 15 seconds (enough time for all lights to cycle)
|
||||||
long endTime = System.currentTimeMillis() + 60000;
|
long endTime = System.currentTimeMillis() + 15000;
|
||||||
|
|
||||||
while (System.currentTimeMillis() < endTime) {
|
while (System.currentTimeMillis() < endTime) {
|
||||||
for (int i = 0; i < lights.size(); i++) {
|
for (int i = 0; i < lights.size(); i++) {
|
||||||
@@ -152,8 +152,7 @@ public class TrafficLightCoordinationTest {
|
|||||||
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])
|
if (hasBeenGreen[i]) greenCount++;
|
||||||
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");
|
||||||
|
|||||||
@@ -1,164 +0,0 @@
|
|||||||
package sd.dashboard;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import sd.config.SimulationConfig;
|
|
||||||
import sd.model.VehicleType;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Unit tests for Dashboard Server components.
|
|
||||||
*/
|
|
||||||
class DashboardTest {
|
|
||||||
|
|
||||||
private DashboardStatistics statistics;
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() {
|
|
||||||
statistics = new DashboardStatistics();
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterEach
|
|
||||||
void tearDown() {
|
|
||||||
statistics = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testInitialStatistics() {
|
|
||||||
assertEquals(0, statistics.getTotalVehiclesGenerated(),
|
|
||||||
"Initial vehicles generated should be 0");
|
|
||||||
assertEquals(0, statistics.getTotalVehiclesCompleted(),
|
|
||||||
"Initial vehicles completed should be 0");
|
|
||||||
assertEquals(0.0, statistics.getAverageSystemTime(),
|
|
||||||
"Initial average system time should be 0.0");
|
|
||||||
assertEquals(0.0, statistics.getAverageWaitingTime(),
|
|
||||||
"Initial average waiting time should be 0.0");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testVehicleCounters() {
|
|
||||||
statistics.incrementVehiclesGenerated();
|
|
||||||
assertEquals(1, statistics.getTotalVehiclesGenerated());
|
|
||||||
|
|
||||||
statistics.updateVehiclesGenerated(10);
|
|
||||||
assertEquals(10, statistics.getTotalVehiclesGenerated());
|
|
||||||
|
|
||||||
statistics.incrementVehiclesCompleted();
|
|
||||||
assertEquals(1, statistics.getTotalVehiclesCompleted());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testAverageCalculations() {
|
|
||||||
// Add 3 completed vehicles with known times
|
|
||||||
statistics.updateVehiclesCompleted(3);
|
|
||||||
statistics.addSystemTime(3000); // 3000ms total
|
|
||||||
statistics.addWaitingTime(1500); // 1500ms total
|
|
||||||
|
|
||||||
assertEquals(1000.0, statistics.getAverageSystemTime(), 0.01,
|
|
||||||
"Average system time should be 1000ms");
|
|
||||||
assertEquals(500.0, statistics.getAverageWaitingTime(), 0.01,
|
|
||||||
"Average waiting time should be 500ms");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testVehicleTypeStatistics() {
|
|
||||||
statistics.incrementVehicleType(VehicleType.LIGHT);
|
|
||||||
statistics.incrementVehicleType(VehicleType.LIGHT);
|
|
||||||
statistics.incrementVehicleType(VehicleType.HEAVY);
|
|
||||||
|
|
||||||
assertEquals(2, statistics.getVehicleTypeCount(VehicleType.LIGHT));
|
|
||||||
assertEquals(1, statistics.getVehicleTypeCount(VehicleType.HEAVY));
|
|
||||||
assertEquals(0, statistics.getVehicleTypeCount(VehicleType.BIKE));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testIntersectionStatistics() {
|
|
||||||
statistics.updateIntersectionStats("Cr1", 10, 8, 2);
|
|
||||||
|
|
||||||
DashboardStatistics.IntersectionStats stats =
|
|
||||||
statistics.getIntersectionStats("Cr1");
|
|
||||||
|
|
||||||
assertNotNull(stats, "Intersection stats should not be null");
|
|
||||||
assertEquals("Cr1", stats.getIntersectionId());
|
|
||||||
assertEquals(10, stats.getTotalArrivals());
|
|
||||||
assertEquals(8, stats.getTotalDepartures());
|
|
||||||
assertEquals(2, stats.getCurrentQueueSize());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testMultipleIntersections() {
|
|
||||||
statistics.updateIntersectionStats("Cr1", 10, 8, 2);
|
|
||||||
statistics.updateIntersectionStats("Cr2", 15, 12, 3);
|
|
||||||
statistics.updateIntersectionStats("Cr3", 5, 5, 0);
|
|
||||||
|
|
||||||
assertEquals(3, statistics.getAllIntersectionStats().size(),
|
|
||||||
"Should have 3 intersections");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testStatsUpdatePayload() {
|
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload()
|
|
||||||
.setTotalVehiclesGenerated(50)
|
|
||||||
.setTotalVehiclesCompleted(20)
|
|
||||||
.setIntersectionArrivals(30)
|
|
||||||
.setIntersectionDepartures(25)
|
|
||||||
.setIntersectionQueueSize(5);
|
|
||||||
|
|
||||||
assertEquals(50, payload.getTotalVehiclesGenerated());
|
|
||||||
assertEquals(20, payload.getTotalVehiclesCompleted());
|
|
||||||
assertEquals(30, payload.getIntersectionArrivals());
|
|
||||||
assertEquals(25, payload.getIntersectionDepartures());
|
|
||||||
assertEquals(5, payload.getIntersectionQueueSize());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testStatsMessage() {
|
|
||||||
StatsUpdatePayload payload = new StatsUpdatePayload()
|
|
||||||
.setIntersectionArrivals(10);
|
|
||||||
|
|
||||||
StatsMessage message = new StatsMessage("Cr1", payload);
|
|
||||||
|
|
||||||
assertEquals("Cr1", message.getSourceNode());
|
|
||||||
assertEquals("DashboardServer", message.getDestinationNode());
|
|
||||||
assertEquals(sd.model.MessageType.STATS_UPDATE, message.getType());
|
|
||||||
assertNotNull(message.getPayload());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testThreadSafety() throws InterruptedException {
|
|
||||||
// Test concurrent updates
|
|
||||||
Thread t1 = new Thread(() -> {
|
|
||||||
for (int i = 0; i < 100; i++) {
|
|
||||||
statistics.incrementVehiclesGenerated();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Thread t2 = new Thread(() -> {
|
|
||||||
for (int i = 0; i < 100; i++) {
|
|
||||||
statistics.incrementVehiclesGenerated();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
t1.start();
|
|
||||||
t2.start();
|
|
||||||
t1.join();
|
|
||||||
t2.join();
|
|
||||||
|
|
||||||
assertEquals(200, statistics.getTotalVehiclesGenerated(),
|
|
||||||
"Concurrent increments should total 200");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testDashboardServerCreation() throws Exception {
|
|
||||||
SimulationConfig config = new SimulationConfig("simulation.properties");
|
|
||||||
DashboardServer server = new DashboardServer(config);
|
|
||||||
|
|
||||||
assertNotNull(server, "Server should be created successfully");
|
|
||||||
assertNotNull(server.getStatistics(), "Statistics should be initialized");
|
|
||||||
assertFalse(server.isRunning(), "Server should not be running initially");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# Distributed Traffic Simulation Startup Script
|
|
||||||
|
|
||||||
# kill java
|
|
||||||
echo "-> Cleaning up existing processes..."
|
|
||||||
pkill -9 java 2>/dev/null
|
|
||||||
sleep 2
|
|
||||||
|
|
||||||
# build
|
|
||||||
echo "-> Building project..."
|
|
||||||
cd "$(dirname "$0")"
|
|
||||||
mvn package -DskipTests -q
|
|
||||||
if [ $? -ne 0 ]; then
|
|
||||||
echo "XXX Build failed! XXX"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "-> Build complete"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# start gui
|
|
||||||
echo "-> Starting JavaFX Dashboard..."
|
|
||||||
mvn javafx:run &
|
|
||||||
DASHBOARD_PID=$!
|
|
||||||
sleep 3
|
|
||||||
|
|
||||||
# acho que é assim idk
|
|
||||||
echo "-> Starting 5 Intersection processes..."
|
|
||||||
for id in Cr1 Cr2 Cr3 Cr4 Cr5; do
|
|
||||||
java -cp target/classes:target/main-1.0-SNAPSHOT.jar sd.IntersectionProcess $id > /tmp/$(echo $id | tr '[:upper:]' '[:lower:]').log 2>&1 &
|
|
||||||
echo "[SUCCESS] Started $id"
|
|
||||||
done
|
|
||||||
sleep 2
|
|
||||||
|
|
||||||
# exit
|
|
||||||
echo "-> Starting Exit Node..."
|
|
||||||
java -cp target/classes:target/main-1.0-SNAPSHOT.jar sd.ExitNodeProcess > /tmp/exit.log 2>&1 &
|
|
||||||
sleep 1
|
|
||||||
|
|
||||||
# coordinator
|
|
||||||
echo "-> Starting Coordinator..."
|
|
||||||
java -cp target/classes:target/main-1.0-SNAPSHOT.jar sd.coordinator.CoordinatorProcess > /tmp/coordinator.log 2>&1 &
|
|
||||||
sleep 1
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "-> All processes started!"
|
|
||||||
echo ""
|
|
||||||
echo "-> System Status:"
|
|
||||||
ps aux | grep "java.*sd\." | grep -v grep | wc -l | xargs -I {} echo " {} Java processes running"
|
|
||||||
echo ""
|
|
||||||
echo " IMPORTANT: Keep the JavaFX Dashboard window OPEN for 60+ seconds"
|
|
||||||
echo " to see live updates! The simulation runs for 60 seconds."
|
|
||||||
echo ""
|
|
||||||
echo "-> Logs available at:"
|
|
||||||
echo " Dashboard: Check JavaFX window (live updates)"
|
|
||||||
echo " Intersections: /tmp/cr*.log"
|
|
||||||
echo " Exit Node: /tmp/exit.log"
|
|
||||||
echo " Coordinator: /tmp/coordinator.log"
|
|
||||||
echo ""
|
|
||||||
echo "-> To stop all processes: pkill -9 java"
|
|
||||||
echo ""
|
|
||||||
1055
main/testing.txt
1055
main/testing.txt
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user