mirror of
https://github.com/davidalves04/Trabalho-Pratico-SD.git
synced 2025-12-08 20:43:32 +00:00
Compare commits
6 Commits
16-integra
...
18-design-
| Author | SHA1 | Date | |
|---|---|---|---|
| 6fdcf376b2 | |||
|
|
ecb70fa6a2 | ||
| 06f079ce5b | |||
| 72893f87ae | |||
| 6b94d727e2 | |||
| 84cba39597 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -48,3 +48,6 @@ build/
|
|||||||
# Other
|
# Other
|
||||||
*.swp
|
*.swp
|
||||||
*.pdf
|
*.pdf
|
||||||
|
|
||||||
|
# JAR built pom file
|
||||||
|
dependency-reduced-pom.xml
|
||||||
21
main/pom.xml
21
main/pom.xml
@@ -29,6 +29,18 @@
|
|||||||
<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>
|
||||||
@@ -42,6 +54,15 @@
|
|||||||
<mainClass>sd.Entry</mainClass>
|
<mainClass>sd.Entry</mainClass>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</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>
|
||||||
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-shade-plugin</artifactId>
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ 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;
|
||||||
@@ -38,6 +39,9 @@ public class ExitNodeProcess {
|
|||||||
/** 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;
|
||||||
|
|
||||||
@@ -161,9 +165,10 @@ public class ExitNodeProcess {
|
|||||||
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 {
|
||||||
@@ -186,28 +191,54 @@ public class ExitNodeProcess {
|
|||||||
* @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.VEHICLE_TRANSFER) {
|
if (message.getType() == MessageType.SIMULATION_START) {
|
||||||
Vehicle vehicle = (Vehicle) message.getPayload();
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
processExitingVehicle(vehicle);
|
processExitingVehicle(vehicle);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (ClassNotFoundException e) {
|
} catch (ClassNotFoundException e) {
|
||||||
System.err.println("Unknown message type received: " + e.getMessage());
|
System.err.println("[Exit] Unknown message type: " + 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("Connection error: " + e.getMessage());
|
System.err.println("[Exit] Connection error from " + clientAddress + ": " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -226,10 +257,14 @@ public class ExitNodeProcess {
|
|||||||
private synchronized void processExitingVehicle(Vehicle vehicle) {
|
private synchronized void processExitingVehicle(Vehicle vehicle) {
|
||||||
totalVehiclesReceived++;
|
totalVehiclesReceived++;
|
||||||
|
|
||||||
double systemTime = vehicle.getTotalTravelTime(getCurrentTime());
|
// Calculate relative simulation time (seconds since simulation start)
|
||||||
|
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;
|
||||||
@@ -238,12 +273,11 @@ 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)%n",
|
System.out.printf("[Exit] Vehicle %s completed (type=%s, system_time=%.2fs, wait=%.2fs, crossing=%.2fs)%n",
|
||||||
vehicle.getId(), vehicle.getType(), systemTime, waitTime);
|
vehicle.getId(), vehicle.getType(), systemTime, waitTime, crossingTime);
|
||||||
|
|
||||||
if (totalVehiclesReceived % 10 == 0) {
|
// Send stats after every vehicle to ensure dashboard updates quickly
|
||||||
sendStatsToDashboard();
|
sendStatsToDashboard();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -273,32 +307,42 @@ public class ExitNodeProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Map<String, Object> stats = new HashMap<>();
|
// Create stats payload
|
||||||
stats.put("totalVehicles", totalVehiclesReceived);
|
StatsUpdatePayload payload = new StatsUpdatePayload();
|
||||||
stats.put("avgSystemTime", totalVehiclesReceived > 0 ? totalSystemTime / totalVehiclesReceived : 0.0);
|
|
||||||
stats.put("avgWaitingTime", totalVehiclesReceived > 0 ? totalWaitingTime / totalVehiclesReceived : 0.0);
|
// Set global stats - convert seconds to milliseconds
|
||||||
stats.put("avgCrossingTime", totalVehiclesReceived > 0 ? totalCrossingTime / totalVehiclesReceived : 0.0);
|
payload.setTotalVehiclesCompleted(totalVehiclesReceived);
|
||||||
|
payload.setTotalSystemTime((long)(totalSystemTime * 1000.0)); // s -> ms
|
||||||
|
payload.setTotalWaitingTime((long)(totalWaitingTime * 1000.0)); // s -> ms
|
||||||
|
|
||||||
|
// 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()) {
|
||||||
int count = vehicleTypeCount.get(type);
|
typeCounts.put(type, vehicleTypeCount.get(type));
|
||||||
typeCounts.put(type.name(), count);
|
typeWaitTimes.put(type, (long)(vehicleTypeWaitTime.get(type) * 1000.0)); // s -> ms
|
||||||
if (count > 0) {
|
|
||||||
typeAvgWait.put(type.name(), vehicleTypeWaitTime.get(type) / count);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
stats.put("vehicleTypeCounts", typeCounts);
|
|
||||||
stats.put("vehicleTypeAvgWait", typeAvgWait);
|
|
||||||
|
|
||||||
Message message = new Message(MessageType.STATS_UPDATE, "ExitNode", "Dashboard", stats);
|
payload.setVehicleTypeCounts(typeCounts);
|
||||||
|
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, totalWaitingTime / totalVehiclesReceived);
|
totalVehiclesReceived, avgWait);
|
||||||
|
|
||||||
} catch (SerializationException | IOException e) {
|
} catch (Exception e) {
|
||||||
System.err.println("Failed to send stats to dashboard: " + e.getMessage());
|
System.err.println("[Exit] Failed to send stats to dashboard: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,51 +12,63 @@ 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.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.TrafficLightState;
|
|
||||||
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 instance)
|
* * Each IntersectionProcess runs as an independent Java application (JVM
|
||||||
|
* 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 {
|
||||||
|
|
||||||
private final String intersectionId;
|
private final String intersectionId;
|
||||||
|
|
||||||
private final SimulationConfig config;
|
private final SimulationConfig config;
|
||||||
|
|
||||||
private final Intersection intersection;
|
private final Intersection intersection;
|
||||||
|
|
||||||
private ServerSocket serverSocket;
|
private ServerSocket serverSocket;
|
||||||
|
|
||||||
private final Map<String, SocketConnection> outgoingConnections;
|
private final Map<String, SocketConnection> outgoingConnections;
|
||||||
|
|
||||||
private final ExecutorService connectionHandlerPool;
|
private final ExecutorService connectionHandlerPool;
|
||||||
|
|
||||||
private final ExecutorService trafficLightPool;
|
private final ExecutorService trafficLightPool;
|
||||||
|
|
||||||
private volatile boolean running; //Quando uma thread escreve um valor volatile, todas as outras
|
private volatile boolean running; // Quando uma thread escreve um valor volatile, todas as outras
|
||||||
//threads veem a mudança imediatamente.
|
// threads veem a mudança imediatamente.
|
||||||
|
|
||||||
// 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 intersection.
|
* Only one traffic light can be green at any given time within this
|
||||||
|
* intersection.
|
||||||
*/
|
*/
|
||||||
private final Lock trafficCoordinationLock;
|
private final Lock trafficCoordinationLock;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tracks which direction currently has the green light.
|
* Tracks which direction currently has the green light.
|
||||||
* null means no direction is currently green (all are red).
|
* null means no direction is currently green (all are red).
|
||||||
*/
|
*/
|
||||||
private volatile String currentGreenDirection;
|
private volatile String currentGreenDirection;
|
||||||
|
|
||||||
|
private SocketClient dashboardClient;
|
||||||
|
private long simulationStartMillis;
|
||||||
|
private volatile int totalArrivals = 0;
|
||||||
|
private volatile int totalDepartures = 0;
|
||||||
|
private long lastStatsUpdateTime;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new IntersectionProcess.
|
* Constructs a new IntersectionProcess.
|
||||||
*
|
*
|
||||||
@@ -74,230 +86,196 @@ public class IntersectionProcess {
|
|||||||
this.running = false;
|
this.running = false;
|
||||||
this.trafficCoordinationLock = new ReentrantLock();
|
this.trafficCoordinationLock = new ReentrantLock();
|
||||||
this.currentGreenDirection = null;
|
this.currentGreenDirection = null;
|
||||||
|
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
System.out.println("INTERSECTION PROCESS: " + intersectionId);
|
System.out.println("INTERSECTION PROCESS: " + intersectionId);
|
||||||
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...");
|
||||||
|
|
||||||
createTrafficLights();
|
createTrafficLights();
|
||||||
|
|
||||||
configureRouting();
|
configureRouting();
|
||||||
|
|
||||||
|
connectToDashboard();
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Initialization complete.");
|
System.out.println("[" + intersectionId + "] Initialization complete.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates traffic lights for this intersection based on its physical connections.
|
* Establishes connection to the dashboard server for statistics reporting.
|
||||||
|
*/
|
||||||
|
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.");
|
||||||
|
lastStatsUpdateTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
} 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...");
|
||||||
|
|
||||||
String[] directions = new String[0];
|
String[] directions = new String[0];
|
||||||
switch (intersectionId) {
|
switch (intersectionId) {
|
||||||
case "Cr1":
|
case "Cr1":
|
||||||
directions = new String[]{"East", "South"};
|
directions = new String[] { "East", "South" };
|
||||||
break;
|
break;
|
||||||
case "Cr2":
|
case "Cr2":
|
||||||
directions = new String[]{"West", "East", "South"};
|
directions = new String[] { "West", "East", "South" };
|
||||||
break;
|
break;
|
||||||
case "Cr3":
|
case "Cr3":
|
||||||
directions = new String[]{"West", "South"};
|
directions = new String[] { "West", "South" };
|
||||||
break;
|
break;
|
||||||
case "Cr4":
|
case "Cr4":
|
||||||
directions = new String[]{"East"};
|
directions = new String[] { "East" };
|
||||||
break;
|
break;
|
||||||
case "Cr5":
|
case "Cr5":
|
||||||
directions = new String[]{"East"};
|
directions = new String[] { "East" };
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (String direction : directions) {
|
for (String direction : directions) {
|
||||||
double greenTime = config.getTrafficLightGreenTime(intersectionId, direction);
|
double greenTime = config.getTrafficLightGreenTime(intersectionId, direction);
|
||||||
double redTime = config.getTrafficLightRedTime(intersectionId, direction);
|
double redTime = config.getTrafficLightRedTime(intersectionId, direction);
|
||||||
|
|
||||||
TrafficLight light = new TrafficLight(
|
TrafficLight light = new TrafficLight(
|
||||||
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 +
|
||||||
" (Green: " + greenTime + "s, Red: " + redTime + "s)");
|
" (Green: " + greenTime + "s, Red: " + redTime + "s)");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void configureRouting() {
|
private void configureRouting() {
|
||||||
System.out.println("\n[" + intersectionId + "] Configuring routing...");
|
System.out.println("\n[" + intersectionId + "] Configuring routing...");
|
||||||
|
|
||||||
switch (intersectionId) {
|
switch (intersectionId) {
|
||||||
case "Cr1":
|
case "Cr1":
|
||||||
intersection.configureRoute("Cr2", "East");
|
intersection.configureRoute("Cr2", "East");
|
||||||
intersection.configureRoute("Cr4", "South");
|
intersection.configureRoute("Cr4", "South");
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "Cr2":
|
case "Cr2":
|
||||||
intersection.configureRoute("Cr1", "West");
|
intersection.configureRoute("Cr1", "West");
|
||||||
intersection.configureRoute("Cr3", "East");
|
intersection.configureRoute("Cr3", "East");
|
||||||
intersection.configureRoute("Cr5", "South");
|
intersection.configureRoute("Cr5", "South");
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "Cr3":
|
case "Cr3":
|
||||||
intersection.configureRoute("Cr2", "West");
|
intersection.configureRoute("Cr2", "West");
|
||||||
intersection.configureRoute("S", "South");
|
intersection.configureRoute("S", "South");
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "Cr4":
|
case "Cr4":
|
||||||
intersection.configureRoute("Cr5", "East");
|
intersection.configureRoute("Cr5", "East");
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "Cr5":
|
case "Cr5":
|
||||||
intersection.configureRoute("S", "East");
|
intersection.configureRoute("S", "East");
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
System.err.println(" Error: unknown intersection ID: " + intersectionId);
|
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.
|
||||||
*/
|
*/
|
||||||
private void startTrafficLights() {
|
private void startTrafficLights() {
|
||||||
System.out.println("\n[" + intersectionId + "] Starting traffic light threads...");
|
System.out.println("\n[" + intersectionId + "] Starting traffic light threads...");
|
||||||
|
|
||||||
for (TrafficLight light : intersection.getTrafficLights()) {
|
for (TrafficLight light : intersection.getTrafficLights()) {
|
||||||
trafficLightPool.submit(() -> runTrafficLightCycle(light));
|
|
||||||
|
TrafficLightThread lightTask = new TrafficLightThread(light, this, config);
|
||||||
|
|
||||||
|
trafficLightPool.submit(lightTask);
|
||||||
|
|
||||||
System.out.println(" Started thread for: " + light.getDirection());
|
System.out.println(" Started thread for: " + light.getDirection());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The main loop for a traffic light thread.
|
|
||||||
* Continuously cycles between green and red states.
|
|
||||||
*
|
|
||||||
* only one traffic light can be green at any given time in this intersection.
|
|
||||||
*
|
|
||||||
* @param light The traffic light to control.
|
|
||||||
*/
|
|
||||||
private void runTrafficLightCycle(TrafficLight light) {
|
|
||||||
System.out.println("[" + light.getId() + "] Traffic light thread started.");
|
|
||||||
|
|
||||||
while (running) {
|
|
||||||
try {
|
|
||||||
// Acquire coordination lock to become green
|
|
||||||
trafficCoordinationLock.lock();
|
|
||||||
try {
|
|
||||||
// Wait until no other direction is green
|
|
||||||
while (currentGreenDirection != null && running) {
|
|
||||||
trafficCoordinationLock.unlock();
|
|
||||||
Thread.sleep(100); // Brief wait before retrying
|
|
||||||
trafficCoordinationLock.lock();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!running) {
|
|
||||||
break; // Exit if shutting down
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mark this direction as the current green light
|
|
||||||
currentGreenDirection = light.getDirection();
|
|
||||||
light.changeState(TrafficLightState.GREEN);
|
|
||||||
System.out.println("[" + light.getId() + "] State: GREEN");
|
|
||||||
|
|
||||||
} finally {
|
|
||||||
trafficCoordinationLock.unlock();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process vehicles while green
|
|
||||||
processGreenLight(light);
|
|
||||||
|
|
||||||
// Wait for green duration
|
|
||||||
Thread.sleep((long) (light.getGreenTime() * 1000));
|
|
||||||
|
|
||||||
// Release coordination lock (turn red)
|
|
||||||
trafficCoordinationLock.lock();
|
|
||||||
try {
|
|
||||||
light.changeState(TrafficLightState.RED);
|
|
||||||
currentGreenDirection = null; // Release exclusive access
|
|
||||||
System.out.println("[" + light.getId() + "] State: RED (RELEASED ACCESS)");
|
|
||||||
} finally {
|
|
||||||
trafficCoordinationLock.unlock();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for red duration
|
|
||||||
Thread.sleep((long) (light.getRedTime() * 1000));
|
|
||||||
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
System.out.println("[" + light.getId() + "] Traffic light thread interrupted.");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
System.out.println("[" + light.getId() + "] Traffic light thread stopped.");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Processes vehicles when a traffic light is GREEN.
|
|
||||||
* Dequeues vehicles and sends them to their next destination.
|
|
||||||
*
|
|
||||||
* @param light The traffic light that is currently green.
|
|
||||||
*/
|
|
||||||
private void processGreenLight(TrafficLight light) {
|
|
||||||
while (light.getState() == TrafficLightState.GREEN && light.getQueueSize() > 0) {
|
|
||||||
Vehicle vehicle = light.removeVehicle();
|
|
||||||
|
|
||||||
if (vehicle != null) {
|
|
||||||
// Get crossing time based on vehicle type
|
|
||||||
double crossingTime = getCrossingTimeForVehicle(vehicle);
|
|
||||||
|
|
||||||
// Simulate crossing time
|
|
||||||
try {
|
|
||||||
Thread.sleep((long) (crossingTime * 1000));
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update vehicle statistics
|
|
||||||
vehicle.addCrossingTime(crossingTime);
|
|
||||||
|
|
||||||
// Update intersection statistics
|
|
||||||
intersection.incrementVehiclesSent();
|
|
||||||
|
|
||||||
// Send vehicle to next destination
|
|
||||||
sendVehicleToNextDestination(vehicle);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the crossing time for a vehicle based on its type.
|
|
||||||
*
|
|
||||||
* @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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends a vehicle to its next destination via socket connection.
|
* Sends a vehicle to its next destination via socket connection.
|
||||||
*
|
*
|
||||||
@@ -305,56 +283,60 @@ public class IntersectionProcess {
|
|||||||
*/
|
*/
|
||||||
public void sendVehicleToNextDestination(Vehicle vehicle) {
|
public void sendVehicleToNextDestination(Vehicle vehicle) {
|
||||||
String nextDestination = vehicle.getCurrentDestination();
|
String nextDestination = vehicle.getCurrentDestination();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 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
|
// Create and send message using Message class
|
||||||
MessageProtocol message = new VehicleTransferMessage(
|
MessageProtocol message = new Message(
|
||||||
intersectionId,
|
MessageType.VEHICLE_TRANSFER,
|
||||||
nextDestination,
|
intersectionId,
|
||||||
vehicle
|
nextDestination,
|
||||||
);
|
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) {
|
||||||
System.err.println("[" + intersectionId + "] Failed to send vehicle " +
|
System.err.println("[" + intersectionId + "] Failed to send vehicle " +
|
||||||
vehicle.getId() + " to " + nextDestination + ": " + e.getMessage());
|
vehicle.getId() + " to " + nextDestination + ": " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets an existing connection to a destination or creates a new one.
|
* Gets an existing connection to a destination or creates a new one.
|
||||||
*
|
*
|
||||||
* @param destinationId The ID of the destination node.
|
* @param destinationId The ID of the destination node.
|
||||||
* @return The SocketConnection to that destination.
|
* @return The SocketConnection to that destination.
|
||||||
* @throws IOException If connection cannot be established.
|
* @throws IOException If connection cannot be established.
|
||||||
* @throws InterruptedException If connection attempt is interrupted.
|
* @throws InterruptedException If connection attempt is interrupted.
|
||||||
*/
|
*/
|
||||||
private synchronized SocketConnection getOrCreateConnection(String destinationId)
|
private synchronized SocketConnection getOrCreateConnection(String destinationId)
|
||||||
throws IOException, InterruptedException {
|
throws IOException, InterruptedException {
|
||||||
|
|
||||||
if (!outgoingConnections.containsKey(destinationId)) {
|
if (!outgoingConnections.containsKey(destinationId)) {
|
||||||
String host = getHostForDestination(destinationId);
|
String host = getHostForDestination(destinationId);
|
||||||
int port = getPortForDestination(destinationId);
|
int port = getPortForDestination(destinationId);
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Creating connection to " +
|
System.out.println("[" + intersectionId + "] Creating connection to " +
|
||||||
destinationId + " at " + host + ":" + port);
|
destinationId + " at " + host + ":" + port);
|
||||||
|
|
||||||
SocketConnection connection = new SocketConnection(host, port);
|
SocketConnection connection = new SocketConnection(host, port);
|
||||||
outgoingConnections.put(destinationId, connection);
|
outgoingConnections.put(destinationId, connection);
|
||||||
}
|
}
|
||||||
|
|
||||||
return outgoingConnections.get(destinationId);
|
return outgoingConnections.get(destinationId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the host address for a destination node from configuration.
|
* Gets the host address for a destination node from configuration.
|
||||||
*
|
*
|
||||||
@@ -368,7 +350,7 @@ public class IntersectionProcess {
|
|||||||
return config.getIntersectionHost(destinationId);
|
return config.getIntersectionHost(destinationId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the port number for a destination node from configuration.
|
* Gets the port number for a destination node from configuration.
|
||||||
*
|
*
|
||||||
@@ -382,7 +364,7 @@ public class IntersectionProcess {
|
|||||||
return config.getIntersectionPort(destinationId);
|
return config.getIntersectionPort(destinationId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts the server socket and begins accepting incoming connections.
|
* Starts the server socket and begins accepting incoming connections.
|
||||||
* This is the main listening loop of the process.
|
* This is the main listening loop of the process.
|
||||||
@@ -393,31 +375,51 @@ public class IntersectionProcess {
|
|||||||
int port = config.getIntersectionPort(intersectionId);
|
int port = config.getIntersectionPort(intersectionId);
|
||||||
serverSocket = new ServerSocket(port);
|
serverSocket = new ServerSocket(port);
|
||||||
running = true;
|
running = true;
|
||||||
|
|
||||||
System.out.println("\n[" + intersectionId + "] Server started on port " + port);
|
System.out.println("\n[" + intersectionId + "] Server started on port " + port);
|
||||||
|
|
||||||
// Start traffic light threads when running is true
|
// Start traffic light threads when running is true
|
||||||
startTrafficLights();
|
startTrafficLights();
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Waiting for incoming connections...\n");
|
System.out.println("[" + intersectionId + "] Waiting for incoming connections...\n");
|
||||||
|
|
||||||
// Main accept loop
|
// Main accept loop
|
||||||
while (running) {
|
while (running) {
|
||||||
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) {
|
||||||
if (running) {
|
// Expected when serverSocket.close() is called during shutdown
|
||||||
System.err.println("[" + intersectionId + "] Error accepting connection: " +
|
if (!running) {
|
||||||
e.getMessage());
|
break; // Normal shutdown
|
||||||
}
|
}
|
||||||
|
System.err.println("[" + intersectionId + "] Error accepting connection: " +
|
||||||
|
e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles an incoming connection from another process.
|
* Handles an incoming connection from another process.
|
||||||
* Continuously listens for vehicle transfer messages.
|
* Continuously listens for vehicle transfer messages.
|
||||||
@@ -425,87 +427,153 @@ 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 " +
|
||||||
clientSocket.getInetAddress().getHostAddress());
|
clientSocket.getInetAddress().getHostAddress());
|
||||||
|
|
||||||
// Continuously receive messages while connection is active
|
// Continuously receive messages while connection is active
|
||||||
while (running && connection.isConnected()) {
|
while (running && connection.isConnected()) {
|
||||||
try {
|
try {
|
||||||
MessageProtocol message = connection.receiveMessage();
|
MessageProtocol message = connection.receiveMessage();
|
||||||
|
|
||||||
if (message.getType() == MessageType.VEHICLE_TRANSFER) {
|
// Handle simulation start time synchronization
|
||||||
Vehicle vehicle = (Vehicle) message.getPayload();
|
if (message.getType() == MessageType.SIMULATION_START) {
|
||||||
|
simulationStartMillis = ((Number) message.getPayload()).longValue();
|
||||||
System.out.println("[" + intersectionId + "] Received vehicle: " +
|
System.out.println("[" + intersectionId + "] Simulation start time synchronized");
|
||||||
vehicle.getId() + " from " + message.getSourceNode());
|
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: " +
|
||||||
|
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} 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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
if (running) {
|
if (running) {
|
||||||
System.err.println("[" + intersectionId + "] Connection error: " + e.getMessage());
|
System.err.println("[" + intersectionId + "] Connection error: " + e.getMessage());
|
||||||
}
|
}
|
||||||
|
// Expected during shutdown
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stops the intersection process gracefully.
|
* Stops the intersection process gracefully.
|
||||||
* 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;
|
||||||
|
|
||||||
// Close server socket
|
// 1. Close ServerSocket first
|
||||||
try {
|
if (serverSocket != null && !serverSocket.isClosed()) {
|
||||||
if (serverSocket != null && !serverSocket.isClosed()) {
|
try {
|
||||||
serverSocket.close();
|
serverSocket.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
// Expected
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Error closing server socket: " +
|
|
||||||
e.getMessage());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shutdown thread pools
|
// 2. Shutdown thread pools with force
|
||||||
trafficLightPool.shutdown();
|
if (trafficLightPool != null && !trafficLightPool.isShutdown()) {
|
||||||
connectionHandlerPool.shutdown();
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (!trafficLightPool.awaitTermination(5, TimeUnit.SECONDS)) {
|
|
||||||
trafficLightPool.shutdownNow();
|
|
||||||
}
|
|
||||||
if (!connectionHandlerPool.awaitTermination(5, TimeUnit.SECONDS)) {
|
|
||||||
connectionHandlerPool.shutdownNow();
|
|
||||||
}
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
trafficLightPool.shutdownNow();
|
trafficLightPool.shutdownNow();
|
||||||
|
}
|
||||||
|
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
||||||
connectionHandlerPool.shutdownNow();
|
connectionHandlerPool.shutdownNow();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close all outgoing connections
|
// 3. Wait briefly for termination (don't block forever)
|
||||||
for (Map.Entry<String, SocketConnection> entry : outgoingConnections.entrySet()) {
|
try {
|
||||||
try {
|
if (trafficLightPool != null) {
|
||||||
entry.getValue().close();
|
trafficLightPool.awaitTermination(1, TimeUnit.SECONDS);
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("[" + intersectionId + "] Error closing connection to " +
|
|
||||||
entry.getKey() + ": " + e.getMessage());
|
|
||||||
}
|
}
|
||||||
|
if (connectionHandlerPool != null) {
|
||||||
|
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 4. Close outgoing connections
|
||||||
|
synchronized (outgoingConnections) {
|
||||||
|
for (SocketConnection conn : outgoingConnections.values()) {
|
||||||
|
try {
|
||||||
|
conn.close();
|
||||||
|
} catch (Exception e) {
|
||||||
|
// Ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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("=".repeat(60));
|
System.out.println("============================================================\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the Intersection object managed by this process.
|
* Gets the Intersection object managed by this process.
|
||||||
* Useful for testing and monitoring.
|
* Useful for testing and monitoring.
|
||||||
@@ -515,40 +583,107 @@ public class IntersectionProcess {
|
|||||||
public Intersection getIntersection() {
|
public Intersection getIntersection() {
|
||||||
return intersection;
|
return intersection;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records that a vehicle has arrived at this intersection.
|
||||||
|
*/
|
||||||
|
public void recordVehicleArrival() {
|
||||||
|
totalArrivals++;
|
||||||
|
checkAndSendStats();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records that a vehicle has departed from this intersection.
|
||||||
|
*/
|
||||||
|
public void recordVehicleDeparture() {
|
||||||
|
totalDepartures++;
|
||||||
|
checkAndSendStats();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if it's time to send statistics to the dashboard and sends them if needed.
|
||||||
|
*/
|
||||||
|
private void checkAndSendStats() {
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
long elapsed = now - lastStatsUpdateTime;
|
||||||
|
|
||||||
|
// Send stats every 5 seconds
|
||||||
|
if (elapsed >= 5000) {
|
||||||
|
sendStatsToDashboard();
|
||||||
|
lastStatsUpdateTime = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends current statistics to the dashboard server.
|
||||||
|
*/
|
||||||
|
private void sendStatsToDashboard() {
|
||||||
|
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Calculate current queue size
|
||||||
|
int currentQueueSize = intersection.getTrafficLights().stream()
|
||||||
|
.mapToInt(TrafficLight::getQueueSize)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
StatsUpdatePayload payload = new StatsUpdatePayload()
|
||||||
|
.setIntersectionArrivals(totalArrivals)
|
||||||
|
.setIntersectionDepartures(totalDepartures)
|
||||||
|
.setIntersectionQueueSize(currentQueueSize);
|
||||||
|
|
||||||
|
// Send StatsUpdatePayload directly as the message payload
|
||||||
|
sd.model.Message message = new sd.model.Message(
|
||||||
|
MessageType.STATS_UPDATE,
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// --- Inner class for Vehicle Transfer Messages ---
|
// --- Inner class for Vehicle Transfer Messages ---
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implementation of MessageProtocol for vehicle transfers between processes.
|
* Implementation of MessageProtocol for vehicle transfers between processes.
|
||||||
*/
|
*/
|
||||||
private static class VehicleTransferMessage implements MessageProtocol {
|
private static class VehicleTransferMessage implements MessageProtocol {
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
private final String sourceNode;
|
private final String sourceNode;
|
||||||
private final String destinationNode;
|
private final String destinationNode;
|
||||||
private final Vehicle payload;
|
private final Vehicle payload;
|
||||||
|
|
||||||
public VehicleTransferMessage(String sourceNode, String destinationNode, Vehicle vehicle) {
|
public VehicleTransferMessage(String sourceNode, String destinationNode, Vehicle vehicle) {
|
||||||
this.sourceNode = sourceNode;
|
this.sourceNode = sourceNode;
|
||||||
this.destinationNode = destinationNode;
|
this.destinationNode = destinationNode;
|
||||||
this.payload = vehicle;
|
this.payload = vehicle;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public MessageType getType() {
|
public MessageType getType() {
|
||||||
return MessageType.VEHICLE_TRANSFER;
|
return MessageType.VEHICLE_TRANSFER;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object getPayload() {
|
public Object getPayload() {
|
||||||
return payload;
|
return payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getSourceNode() {
|
public String getSourceNode() {
|
||||||
return sourceNode;
|
return sourceNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getDestinationNode() {
|
public String getDestinationNode() {
|
||||||
return destinationNode;
|
return destinationNode;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ 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;
|
||||||
@@ -24,6 +25,7 @@ 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;
|
||||||
@@ -75,6 +77,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"};
|
||||||
@@ -108,6 +113,9 @@ 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;
|
||||||
|
|
||||||
@@ -132,6 +140,9 @@ 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;
|
||||||
@@ -201,4 +212,77 @@ 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
137
main/src/main/java/sd/dashboard/DashboardClientHandler.java
Normal file
137
main/src/main/java/sd/dashboard/DashboardClientHandler.java
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
165
main/src/main/java/sd/dashboard/DashboardServer.java
Normal file
165
main/src/main/java/sd/dashboard/DashboardServer.java
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
224
main/src/main/java/sd/dashboard/DashboardStatistics.java
Normal file
224
main/src/main/java/sd/dashboard/DashboardStatistics.java
Normal file
@@ -0,0 +1,224 @@
|
|||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
378
main/src/main/java/sd/dashboard/DashboardUI.java
Normal file
378
main/src/main/java/sd/dashboard/DashboardUI.java
Normal file
@@ -0,0 +1,378 @@
|
|||||||
|
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.Label;
|
||||||
|
import javafx.scene.control.TableColumn;
|
||||||
|
import javafx.scene.control.TableView;
|
||||||
|
import javafx.scene.control.TitledPane;
|
||||||
|
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.paint.Color;
|
||||||
|
import javafx.scene.shape.Circle;
|
||||||
|
import javafx.scene.text.Font;
|
||||||
|
import javafx.scene.text.FontWeight;
|
||||||
|
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.setStyle("-fx-background-color: #f5f5f5;");
|
||||||
|
|
||||||
|
// 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, 800);
|
||||||
|
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 (IOException e) {
|
||||||
|
showErrorAlert("Failed to start Dashboard Server", e.getMessage());
|
||||||
|
Platform.exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private VBox createHeader() {
|
||||||
|
VBox header = new VBox(10);
|
||||||
|
header.setPadding(new Insets(20));
|
||||||
|
header.setStyle("-fx-background-color: linear-gradient(to right, #2c3e50, #3498db);");
|
||||||
|
|
||||||
|
Label title = new Label("DISTRIBUTED TRAFFIC SIMULATION DASHBOARD");
|
||||||
|
title.setFont(Font.font("Arial", FontWeight.BOLD, 28));
|
||||||
|
title.setTextFill(Color.WHITE);
|
||||||
|
|
||||||
|
Label subtitle = new Label("Real-time Statistics and Monitoring");
|
||||||
|
subtitle.setFont(Font.font("Arial", FontWeight.NORMAL, 16));
|
||||||
|
subtitle.setTextFill(Color.web("#ecf0f1"));
|
||||||
|
|
||||||
|
header.getChildren().addAll(title, subtitle);
|
||||||
|
header.setAlignment(Pos.CENTER);
|
||||||
|
|
||||||
|
return header;
|
||||||
|
}
|
||||||
|
|
||||||
|
private VBox createMainContent() {
|
||||||
|
VBox mainContent = new VBox(15);
|
||||||
|
mainContent.setPadding(new Insets(20));
|
||||||
|
|
||||||
|
// Global Statistics Panel
|
||||||
|
TitledPane globalStatsPane = createGlobalStatisticsPanel();
|
||||||
|
|
||||||
|
// Vehicle Type Statistics Panel
|
||||||
|
TitledPane vehicleTypePane = createVehicleTypePanel();
|
||||||
|
|
||||||
|
// Intersection Statistics Panel
|
||||||
|
TitledPane intersectionPane = createIntersectionPanel();
|
||||||
|
|
||||||
|
mainContent.getChildren().addAll(globalStatsPane, vehicleTypePane, intersectionPane);
|
||||||
|
|
||||||
|
return mainContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
private TitledPane createGlobalStatisticsPanel() {
|
||||||
|
GridPane grid = new GridPane();
|
||||||
|
grid.setPadding(new Insets(15));
|
||||||
|
grid.setHgap(20);
|
||||||
|
grid.setVgap(15);
|
||||||
|
grid.setStyle("-fx-background-color: white; -fx-border-radius: 5;");
|
||||||
|
|
||||||
|
// Initialize labels
|
||||||
|
lblVehiclesGenerated = createStatLabel("0");
|
||||||
|
lblVehiclesCompleted = createStatLabel("0");
|
||||||
|
lblVehiclesInTransit = createStatLabel("0");
|
||||||
|
lblAvgSystemTime = createStatLabel("0.00 ms");
|
||||||
|
lblAvgWaitingTime = createStatLabel("0.00 ms");
|
||||||
|
|
||||||
|
// Add labels with descriptions
|
||||||
|
addStatRow(grid, 0, "Total Vehicles Generated:", lblVehiclesGenerated);
|
||||||
|
addStatRow(grid, 1, "Total Vehicles Completed:", lblVehiclesCompleted);
|
||||||
|
addStatRow(grid, 2, "Vehicles In Transit:", lblVehiclesInTransit);
|
||||||
|
addStatRow(grid, 3, "Average System Time:", lblAvgSystemTime);
|
||||||
|
addStatRow(grid, 4, "Average Waiting Time:", lblAvgWaitingTime);
|
||||||
|
|
||||||
|
TitledPane pane = new TitledPane("Global Statistics", grid);
|
||||||
|
pane.setCollapsible(false);
|
||||||
|
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
||||||
|
|
||||||
|
return pane;
|
||||||
|
}
|
||||||
|
|
||||||
|
private TitledPane createVehicleTypePanel() {
|
||||||
|
vehicleTypeTable = new TableView<>();
|
||||||
|
vehicleTypeTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
||||||
|
vehicleTypeTable.setPrefHeight(200);
|
||||||
|
|
||||||
|
TableColumn<VehicleTypeRow, String> typeCol = new TableColumn<>("Vehicle Type");
|
||||||
|
typeCol.setCellValueFactory(new PropertyValueFactory<>("vehicleType"));
|
||||||
|
typeCol.setPrefWidth(200);
|
||||||
|
|
||||||
|
TableColumn<VehicleTypeRow, Integer> countCol = new TableColumn<>("Count");
|
||||||
|
countCol.setCellValueFactory(new PropertyValueFactory<>("count"));
|
||||||
|
countCol.setPrefWidth(150);
|
||||||
|
|
||||||
|
TableColumn<VehicleTypeRow, String> avgWaitCol = new TableColumn<>("Avg Wait Time");
|
||||||
|
avgWaitCol.setCellValueFactory(new PropertyValueFactory<>("avgWaitTime"));
|
||||||
|
avgWaitCol.setPrefWidth(150);
|
||||||
|
|
||||||
|
vehicleTypeTable.getColumns().addAll(typeCol, countCol, avgWaitCol);
|
||||||
|
|
||||||
|
TitledPane pane = new TitledPane("Vehicle Type Statistics", vehicleTypeTable);
|
||||||
|
pane.setCollapsible(false);
|
||||||
|
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
||||||
|
|
||||||
|
return pane;
|
||||||
|
}
|
||||||
|
|
||||||
|
private TitledPane createIntersectionPanel() {
|
||||||
|
intersectionTable = new TableView<>();
|
||||||
|
intersectionTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
||||||
|
intersectionTable.setPrefHeight(250);
|
||||||
|
|
||||||
|
TableColumn<IntersectionRow, String> idCol = new TableColumn<>("Intersection ID");
|
||||||
|
idCol.setCellValueFactory(new PropertyValueFactory<>("intersectionId"));
|
||||||
|
idCol.setPrefWidth(200);
|
||||||
|
|
||||||
|
TableColumn<IntersectionRow, Integer> arrivalsCol = new TableColumn<>("Total Arrivals");
|
||||||
|
arrivalsCol.setCellValueFactory(new PropertyValueFactory<>("arrivals"));
|
||||||
|
arrivalsCol.setPrefWidth(150);
|
||||||
|
|
||||||
|
TableColumn<IntersectionRow, Integer> departuresCol = new TableColumn<>("Total Departures");
|
||||||
|
departuresCol.setCellValueFactory(new PropertyValueFactory<>("departures"));
|
||||||
|
departuresCol.setPrefWidth(150);
|
||||||
|
|
||||||
|
TableColumn<IntersectionRow, Integer> queueCol = new TableColumn<>("Current Queue");
|
||||||
|
queueCol.setCellValueFactory(new PropertyValueFactory<>("queueSize"));
|
||||||
|
queueCol.setPrefWidth(150);
|
||||||
|
|
||||||
|
intersectionTable.getColumns().addAll(idCol, arrivalsCol, departuresCol, queueCol);
|
||||||
|
|
||||||
|
TitledPane pane = new TitledPane("Intersection Statistics", intersectionTable);
|
||||||
|
pane.setCollapsible(false);
|
||||||
|
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
||||||
|
|
||||||
|
return pane;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HBox createFooter() {
|
||||||
|
HBox footer = new HBox(10);
|
||||||
|
footer.setPadding(new Insets(10, 20, 10, 20));
|
||||||
|
footer.setStyle("-fx-background-color: #34495e;");
|
||||||
|
footer.setAlignment(Pos.CENTER_LEFT);
|
||||||
|
|
||||||
|
Label statusLabel = new Label("Status:");
|
||||||
|
statusLabel.setTextFill(Color.WHITE);
|
||||||
|
statusLabel.setFont(Font.font("Arial", FontWeight.BOLD, 12));
|
||||||
|
|
||||||
|
Circle statusIndicator = new Circle(6);
|
||||||
|
statusIndicator.setFill(Color.LIME);
|
||||||
|
|
||||||
|
Label statusText = new Label("Connected and Receiving Data");
|
||||||
|
statusText.setTextFill(Color.WHITE);
|
||||||
|
statusText.setFont(Font.font("Arial", 12));
|
||||||
|
|
||||||
|
lblLastUpdate = new Label("Last Update: --:--:--");
|
||||||
|
lblLastUpdate.setTextFill(Color.web("#ecf0f1"));
|
||||||
|
lblLastUpdate.setFont(Font.font("Arial", 12));
|
||||||
|
|
||||||
|
Region spacer = new Region();
|
||||||
|
HBox.setHgrow(spacer, Priority.ALWAYS);
|
||||||
|
|
||||||
|
footer.getChildren().addAll(statusLabel, statusIndicator, statusText, spacer, lblLastUpdate);
|
||||||
|
|
||||||
|
return footer;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Label createStatLabel(String initialValue) {
|
||||||
|
Label label = new Label(initialValue);
|
||||||
|
label.setFont(Font.font("Arial", FontWeight.BOLD, 20));
|
||||||
|
label.setTextFill(Color.web("#2980b9"));
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addStatRow(GridPane grid, int row, String description, Label valueLabel) {
|
||||||
|
Label descLabel = new Label(description);
|
||||||
|
descLabel.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
|
||||||
|
descLabel.setTextFill(Color.web("#34495e"));
|
||||||
|
|
||||||
|
grid.add(descLabel, 0, row);
|
||||||
|
grid.add(valueLabel, 1, 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 ms", statistics.getAverageSystemTime()));
|
||||||
|
lblAvgWaitingTime.setText(String.format("%.2f ms", statistics.getAverageWaitingTime()));
|
||||||
|
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 ms", avgWait)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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; }
|
||||||
|
}
|
||||||
|
}
|
||||||
48
main/src/main/java/sd/dashboard/StatsMessage.java
Normal file
48
main/src/main/java/sd/dashboard/StatsMessage.java
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
121
main/src/main/java/sd/dashboard/StatsUpdatePayload.java
Normal file
121
main/src/main/java/sd/dashboard/StatsUpdatePayload.java
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,150 +9,107 @@ 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; // Starts as 'stopped'
|
this.running = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 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 {
|
||||||
// Main thread loop, continues while 'running' is true
|
while (running && !Thread.currentThread().isInterrupted()) {
|
||||||
// This 'running' flag is controlled by the parent IntersectionProcess
|
|
||||||
while (running) {
|
|
||||||
|
|
||||||
// --- GREEN Phase ---
|
// Request permission to turn green (blocks until granted)
|
||||||
light.changeState(TrafficLightState.GREEN); //
|
process.requestGreenLight(light.getDirection());
|
||||||
System.out.println("[" + light.getId() + "] State: GREEN");
|
|
||||||
|
|
||||||
// Process vehicles in the queue
|
try {
|
||||||
processGreenLightQueue();
|
// --- GREEN Phase ---
|
||||||
|
light.changeState(TrafficLightState.GREEN);
|
||||||
// Wait for green duration
|
System.out.println("[" + light.getId() + "] State: GREEN");
|
||||||
Thread.sleep((long) (light.getGreenTime() * 1000)); //
|
|
||||||
|
processGreenLightQueue();
|
||||||
if (!running) break; // Check flag after sleep
|
|
||||||
|
if (!running || Thread.currentThread().isInterrupted()) break;
|
||||||
|
|
||||||
|
// Wait for green duration
|
||||||
|
Thread.sleep((long) (light.getGreenTime() * 1000));
|
||||||
|
|
||||||
|
if (!running || Thread.currentThread().isInterrupted()) break;
|
||||||
|
|
||||||
// --- RED Phase ---
|
// --- RED Phase ---
|
||||||
light.changeState(TrafficLightState.RED); //
|
light.changeState(TrafficLightState.RED);
|
||||||
System.out.println("[" + light.getId() + "] State: RED");
|
System.out.println("[" + light.getId() + "] State: RED");
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
// 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.");
|
||||||
this.running = false; // Garante que o loop termina
|
Thread.currentThread().interrupt();
|
||||||
|
} finally {
|
||||||
|
this.running = false;
|
||||||
|
System.out.println("[" + light.getId() + "] Traffic light thread stopped.");
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println("[" + light.getId() + "] Traffic light thread stopped.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Processes vehicles in the queue while the traffic light is GREEN.
|
|
||||||
* Logic extracted from IntersectionProcess.processGreenLight()
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
private void processGreenLightQueue() throws InterruptedException {
|
private void processGreenLightQueue() throws InterruptedException {
|
||||||
//
|
while (running && !Thread.currentThread().isInterrupted()
|
||||||
while (running && light.getState() == TrafficLightState.GREEN && light.getQueueSize() > 0) {
|
&& light.getState() == TrafficLightState.GREEN
|
||||||
|
&& light.getQueueSize() > 0) {
|
||||||
|
|
||||||
Vehicle vehicle = light.removeVehicle(); //
|
Vehicle vehicle = light.removeVehicle();
|
||||||
|
|
||||||
if (vehicle != null) {
|
if (vehicle != null) {
|
||||||
// 1. Get the crossing time (t_sem)
|
double crossingTime = getCrossingTimeForVehicle(vehicle);
|
||||||
double crossingTime = getCrossingTimeForVehicle(vehicle); //
|
|
||||||
|
|
||||||
// 2. Simulate the time the vehicle takes to cross
|
Thread.sleep((long) (crossingTime * 1000));
|
||||||
Thread.sleep((long) (crossingTime * 1000)); //
|
|
||||||
|
|
||||||
// 3. Update vehicle statistics
|
vehicle.addCrossingTime(crossingTime);
|
||||||
vehicle.addCrossingTime(crossingTime); //
|
process.getIntersection().incrementVehiclesSent();
|
||||||
|
process.sendVehicleToNextDestination(vehicle);
|
||||||
// 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) {
|
private double getCrossingTimeForVehicle(Vehicle vehicle) {
|
||||||
switch (vehicle.getType()) { //
|
return switch (vehicle.getType()) {
|
||||||
case BIKE:
|
case BIKE -> config.getBikeVehicleCrossingTime();
|
||||||
return config.getBikeVehicleCrossingTime(); //
|
case LIGHT -> config.getLightVehicleCrossingTime();
|
||||||
case LIGHT:
|
case HEAVY -> config.getHeavyVehicleCrossingTime();
|
||||||
return config.getLightVehicleCrossingTime(); //
|
default -> config.getLightVehicleCrossingTime();
|
||||||
case HEAVY:
|
};
|
||||||
return config.getHeavyVehicleCrossingTime(); //
|
|
||||||
default:
|
|
||||||
return config.getLightVehicleCrossingTime(); //
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Requests the thread to stop gracefully (graceful shutdown).
|
* Requests the thread to stop gracefully.
|
||||||
* Sets the 'running' flag to false. The thread will finish
|
* Sets the running flag and interrupts the thread to unblock any sleep() calls.
|
||||||
* 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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,15 @@
|
|||||||
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 Serializable} to allow transmission over the network.
|
* This class implements {@link MessageProtocol} which extends Serializable for network transmission.
|
||||||
*/
|
*/
|
||||||
public class Message implements Serializable {
|
public class Message implements MessageProtocol {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
@@ -132,6 +133,17 @@ public class Message implements Serializable {
|
|||||||
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,6 +19,12 @@ 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,6 +1,8 @@
|
|||||||
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;
|
||||||
@@ -93,6 +95,12 @@ public class TrafficLight {
|
|||||||
* been dequeued (processed) by this light.
|
* been dequeued (processed) by this light.
|
||||||
*/
|
*/
|
||||||
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.
|
||||||
@@ -115,6 +123,7 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,6 +137,7 @@ 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
|
||||||
@@ -152,6 +162,13 @@ 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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -172,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
|
// Deserialize do JSON - use concrete Message class, not interface
|
||||||
return serializer.deserialize(data, MessageProtocol.class);
|
return serializer.deserialize(data, sd.model.Message.class);
|
||||||
|
|
||||||
} catch (SerializationException e) {
|
} catch (SerializationException e) {
|
||||||
throw new IOException("Failed to deserialize message", e);
|
throw new IOException("Failed to deserialize message", e);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.ObjectOutputStream;
|
import java.net.InetSocketAddress;
|
||||||
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,9 +19,10 @@ 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,
|
||||||
* vehicle transfer and network stuff
|
* vehicle transfer and network stuff
|
||||||
*/
|
*/
|
||||||
public class IntersectionProcessTest {
|
public class IntersectionProcessTest {
|
||||||
@@ -37,10 +38,10 @@ public class IntersectionProcessTest {
|
|||||||
public void setUp() throws IOException {
|
public void setUp() throws IOException {
|
||||||
// create temp config file
|
// create temp config file
|
||||||
configFile = tempDir.resolve("test-simulation.properties");
|
configFile = tempDir.resolve("test-simulation.properties");
|
||||||
|
|
||||||
String configContent = """
|
String configContent = """
|
||||||
# Test Simulation Configuration
|
# Test Simulation Configuration
|
||||||
|
|
||||||
# Intersection Network Configuration
|
# Intersection Network Configuration
|
||||||
intersection.Cr1.host=localhost
|
intersection.Cr1.host=localhost
|
||||||
intersection.Cr1.port=18001
|
intersection.Cr1.port=18001
|
||||||
@@ -52,15 +53,15 @@ public class IntersectionProcessTest {
|
|||||||
intersection.Cr4.port=18004
|
intersection.Cr4.port=18004
|
||||||
intersection.Cr5.host=localhost
|
intersection.Cr5.host=localhost
|
||||||
intersection.Cr5.port=18005
|
intersection.Cr5.port=18005
|
||||||
|
|
||||||
# Exit Configuration
|
# Exit Configuration
|
||||||
exit.host=localhost
|
exit.host=localhost
|
||||||
exit.port=18099
|
exit.port=18099
|
||||||
|
|
||||||
# Dashboard Configuration
|
# Dashboard Configuration
|
||||||
dashboard.host=localhost
|
dashboard.host=localhost
|
||||||
dashboard.port=18100
|
dashboard.port=18100
|
||||||
|
|
||||||
# Traffic Light Timing (seconds)
|
# Traffic Light Timing (seconds)
|
||||||
trafficLight.Cr1.East.greenTime=5.0
|
trafficLight.Cr1.East.greenTime=5.0
|
||||||
trafficLight.Cr1.East.redTime=5.0
|
trafficLight.Cr1.East.redTime=5.0
|
||||||
@@ -68,39 +69,45 @@ public class IntersectionProcessTest {
|
|||||||
trafficLight.Cr1.South.redTime=5.0
|
trafficLight.Cr1.South.redTime=5.0
|
||||||
trafficLight.Cr1.West.greenTime=5.0
|
trafficLight.Cr1.West.greenTime=5.0
|
||||||
trafficLight.Cr1.West.redTime=5.0
|
trafficLight.Cr1.West.redTime=5.0
|
||||||
|
|
||||||
trafficLight.Cr2.West.greenTime=4.0
|
trafficLight.Cr2.West.greenTime=4.0
|
||||||
trafficLight.Cr2.West.redTime=6.0
|
trafficLight.Cr2.West.redTime=6.0
|
||||||
trafficLight.Cr2.East.greenTime=4.0
|
trafficLight.Cr2.East.greenTime=4.0
|
||||||
trafficLight.Cr2.East.redTime=6.0
|
trafficLight.Cr2.East.redTime=6.0
|
||||||
trafficLight.Cr2.South.greenTime=4.0
|
trafficLight.Cr2.South.greenTime=4.0
|
||||||
trafficLight.Cr2.South.redTime=6.0
|
trafficLight.Cr2.South.redTime=6.0
|
||||||
|
|
||||||
trafficLight.Cr3.West.greenTime=3.0
|
trafficLight.Cr3.West.greenTime=3.0
|
||||||
trafficLight.Cr3.West.redTime=7.0
|
trafficLight.Cr3.West.redTime=7.0
|
||||||
trafficLight.Cr3.East.greenTime=3.0
|
trafficLight.Cr3.East.greenTime=3.0
|
||||||
trafficLight.Cr3.East.redTime=7.0
|
trafficLight.Cr3.East.redTime=7.0
|
||||||
|
|
||||||
trafficLight.Cr4.East.greenTime=6.0
|
trafficLight.Cr4.East.greenTime=6.0
|
||||||
trafficLight.Cr4.East.redTime=4.0
|
trafficLight.Cr4.East.redTime=4.0
|
||||||
|
|
||||||
trafficLight.Cr5.East.greenTime=5.0
|
trafficLight.Cr5.East.greenTime=5.0
|
||||||
trafficLight.Cr5.East.redTime=5.0
|
trafficLight.Cr5.East.redTime=5.0
|
||||||
|
|
||||||
# Vehicle Crossing Times (seconds)
|
# Vehicle Crossing Times (seconds)
|
||||||
vehicle.bike.crossingTime=2.0
|
vehicle.bike.crossingTime=2.0
|
||||||
vehicle.light.crossingTime=3.0
|
vehicle.light.crossingTime=3.0
|
||||||
vehicle.heavy.crossingTime=5.0
|
vehicle.heavy.crossingTime=5.0
|
||||||
""";
|
""";
|
||||||
|
|
||||||
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) {
|
||||||
intersectionProcess.shutdown();
|
try {
|
||||||
|
// Only shutdown if still running
|
||||||
|
intersectionProcess.shutdown();
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("Error in tearDown: " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
intersectionProcess = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,7 +163,7 @@ public class IntersectionProcessTest {
|
|||||||
public void testTrafficLightCreation_Cr1_HasCorrectDirections() throws IOException {
|
public void testTrafficLightCreation_Cr1_HasCorrectDirections() throws IOException {
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
// cant access private fields but initialization succeds
|
// cant access private fields but initialization succeds
|
||||||
assertNotNull(intersectionProcess);
|
assertNotNull(intersectionProcess);
|
||||||
}
|
}
|
||||||
@@ -165,7 +172,7 @@ public class IntersectionProcessTest {
|
|||||||
public void testTrafficLightCreation_Cr3_HasCorrectDirections() throws IOException {
|
public void testTrafficLightCreation_Cr3_HasCorrectDirections() throws IOException {
|
||||||
intersectionProcess = new IntersectionProcess("Cr3", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr3", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
// Cr3 has west and south only
|
// Cr3 has west and south only
|
||||||
assertNotNull(intersectionProcess);
|
assertNotNull(intersectionProcess);
|
||||||
}
|
}
|
||||||
@@ -174,7 +181,7 @@ public class IntersectionProcessTest {
|
|||||||
public void testTrafficLightCreation_Cr4_HasSingleDirection() throws IOException {
|
public void testTrafficLightCreation_Cr4_HasSingleDirection() throws IOException {
|
||||||
intersectionProcess = new IntersectionProcess("Cr4", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr4", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
// Cr4 only has east direction
|
// Cr4 only has east direction
|
||||||
assertNotNull(intersectionProcess);
|
assertNotNull(intersectionProcess);
|
||||||
}
|
}
|
||||||
@@ -186,8 +193,8 @@ public class IntersectionProcessTest {
|
|||||||
public void testServerStart_BindsToCorrectPort() throws IOException, InterruptedException {
|
public void testServerStart_BindsToCorrectPort() throws IOException, InterruptedException {
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
// start server in seperate thread
|
// start server in separate thread
|
||||||
Thread serverThread = new Thread(() -> {
|
Thread serverThread = new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
intersectionProcess.start();
|
intersectionProcess.start();
|
||||||
@@ -196,14 +203,23 @@ public class IntersectionProcessTest {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
serverThread.start();
|
serverThread.start();
|
||||||
|
|
||||||
Thread.sleep(500); // wait for server to start
|
// Wait for server to actually start with retries
|
||||||
|
boolean serverReady = false;
|
||||||
// try connecting to check if its running
|
for (int i = 0; i < 20; i++) {
|
||||||
try (Socket clientSocket = new Socket("localhost", 18001)) {
|
Thread.sleep(100);
|
||||||
assertTrue(clientSocket.isConnected());
|
try (Socket testSocket = new Socket()) {
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
@@ -214,30 +230,36 @@ public class IntersectionProcessTest {
|
|||||||
// test 2 intersections on diferent ports
|
// test 2 intersections on diferent ports
|
||||||
IntersectionProcess cr1 = new IntersectionProcess("Cr1", configFile.toString());
|
IntersectionProcess cr1 = new IntersectionProcess("Cr1", configFile.toString());
|
||||||
IntersectionProcess cr2 = new IntersectionProcess("Cr2", configFile.toString());
|
IntersectionProcess cr2 = new IntersectionProcess("Cr2", configFile.toString());
|
||||||
|
|
||||||
cr1.initialize();
|
cr1.initialize();
|
||||||
cr2.initialize();
|
cr2.initialize();
|
||||||
|
|
||||||
Thread thread1 = new Thread(() -> {
|
Thread thread1 = new Thread(() -> {
|
||||||
try { cr1.start(); } catch (IOException e) { }
|
try {
|
||||||
|
cr1.start();
|
||||||
|
} catch (IOException e) {
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Thread thread2 = new Thread(() -> {
|
Thread thread2 = new Thread(() -> {
|
||||||
try { cr2.start(); } catch (IOException e) { }
|
try {
|
||||||
|
cr2.start();
|
||||||
|
} catch (IOException e) {
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
thread1.start();
|
thread1.start();
|
||||||
thread2.start();
|
thread2.start();
|
||||||
|
|
||||||
Thread.sleep(500);
|
Thread.sleep(500);
|
||||||
|
|
||||||
// check both are running
|
// check both are running
|
||||||
try (Socket socket1 = new Socket("localhost", 18001);
|
try (Socket socket1 = new Socket("localhost", 18001);
|
||||||
Socket socket2 = new Socket("localhost", 18002)) {
|
Socket socket2 = new Socket("localhost", 18002)) {
|
||||||
assertTrue(socket1.isConnected());
|
assertTrue(socket1.isConnected());
|
||||||
assertTrue(socket2.isConnected());
|
assertTrue(socket2.isConnected());
|
||||||
}
|
}
|
||||||
|
|
||||||
cr1.shutdown();
|
cr1.shutdown();
|
||||||
cr2.shutdown();
|
cr2.shutdown();
|
||||||
thread1.join(2000);
|
thread1.join(2000);
|
||||||
@@ -252,33 +274,35 @@ public class IntersectionProcessTest {
|
|||||||
// setup reciever intersection
|
// setup reciever intersection
|
||||||
intersectionProcess = new IntersectionProcess("Cr2", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr2", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
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);
|
||||||
|
|
||||||
// create test vehicle
|
try {
|
||||||
java.util.List<String> route = Arrays.asList("Cr2", "Cr3", "S");
|
// create test vehicle - FIXED: use 4-parameter constructor
|
||||||
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 0.0, route);
|
java.util.List<String> route = Arrays.asList("Cr2", "Cr3", "S");
|
||||||
|
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 0.0, route);
|
||||||
// send vehicle from Cr1 to Cr2
|
|
||||||
try (Socket socket = new Socket("localhost", 18002)) {
|
// send vehicle from Cr1 to Cr2 - FIXED: use SocketConnection
|
||||||
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
try (Socket socket = new Socket("localhost", 18002);
|
||||||
|
SocketConnection conn = new SocketConnection(socket)) {
|
||||||
TestVehicleMessage message = new TestVehicleMessage("Cr1", "Cr2", vehicle);
|
|
||||||
out.writeObject(message);
|
TestVehicleMessage message = new TestVehicleMessage("Cr1", "Cr2", vehicle);
|
||||||
out.flush();
|
conn.sendMessage(message);
|
||||||
|
|
||||||
Thread.sleep(1000); // wait for procesing
|
Thread.sleep(1000); // wait for processing
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
intersectionProcess.shutdown();
|
||||||
|
serverThread.join(2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
intersectionProcess.shutdown();
|
|
||||||
serverThread.join(2000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// routing config tests
|
// routing config tests
|
||||||
@@ -287,7 +311,7 @@ public class IntersectionProcessTest {
|
|||||||
public void testRoutingConfiguration_Cr1() throws IOException {
|
public void testRoutingConfiguration_Cr1() throws IOException {
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
// indirect test - if init works routing should be ok
|
// indirect test - if init works routing should be ok
|
||||||
assertNotNull(intersectionProcess);
|
assertNotNull(intersectionProcess);
|
||||||
}
|
}
|
||||||
@@ -296,7 +320,7 @@ public class IntersectionProcessTest {
|
|||||||
public void testRoutingConfiguration_Cr5() throws IOException {
|
public void testRoutingConfiguration_Cr5() throws IOException {
|
||||||
intersectionProcess = new IntersectionProcess("Cr5", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr5", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
// Cr5 routes to exit
|
// Cr5 routes to exit
|
||||||
assertNotNull(intersectionProcess);
|
assertNotNull(intersectionProcess);
|
||||||
}
|
}
|
||||||
@@ -308,19 +332,20 @@ public class IntersectionProcessTest {
|
|||||||
public void testShutdown_GracefulTermination() throws IOException, InterruptedException {
|
public void testShutdown_GracefulTermination() throws IOException, InterruptedException {
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
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);
|
||||||
|
|
||||||
// shutdown should be fast
|
// shutdown should be fast
|
||||||
assertDoesNotThrow(() -> intersectionProcess.shutdown());
|
assertDoesNotThrow(() -> intersectionProcess.shutdown());
|
||||||
|
|
||||||
serverThread.join(2000);
|
serverThread.join(2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,31 +354,36 @@ public class IntersectionProcessTest {
|
|||||||
public void testShutdown_ClosesServerSocket() throws IOException, InterruptedException {
|
public void testShutdown_ClosesServerSocket() throws IOException, InterruptedException {
|
||||||
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);
|
||||||
|
|
||||||
// verify server running
|
// Shutdown
|
||||||
try (Socket socket = new Socket("localhost", 18001)) {
|
|
||||||
assertTrue(socket.isConnected());
|
|
||||||
}
|
|
||||||
|
|
||||||
intersectionProcess.shutdown();
|
intersectionProcess.shutdown();
|
||||||
serverThread.join(2000);
|
serverThread.join(2000);
|
||||||
|
|
||||||
// after shutdown conection should fail
|
// Give shutdown time to complete
|
||||||
Thread.sleep(500);
|
Thread.sleep(200);
|
||||||
Exception exception = assertThrows(IOException.class, () -> {
|
|
||||||
Socket socket = new Socket("localhost", 18001);
|
// Verify we cannot connect (server socket is closed)
|
||||||
socket.close();
|
boolean connectionFailed = false;
|
||||||
});
|
try (Socket testSocket = new Socket()) {
|
||||||
assertNotNull(exception);
|
testSocket.connect(new InetSocketAddress("localhost", 18001), 500);
|
||||||
|
} catch (IOException e) {
|
||||||
|
connectionFailed = true; // Expected - server should be closed
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(connectionFailed, "Server socket should be closed after shutdown");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -361,23 +391,24 @@ public class IntersectionProcessTest {
|
|||||||
public void testShutdown_StopsTrafficLightThreads() throws IOException, InterruptedException {
|
public void testShutdown_StopsTrafficLightThreads() throws IOException, InterruptedException {
|
||||||
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
intersectionProcess = new IntersectionProcess("Cr1", configFile.toString());
|
||||||
intersectionProcess.initialize();
|
intersectionProcess.initialize();
|
||||||
|
|
||||||
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);
|
||||||
|
|
||||||
int threadCountBefore = Thread.activeCount();
|
int threadCountBefore = Thread.activeCount();
|
||||||
|
|
||||||
intersectionProcess.shutdown();
|
intersectionProcess.shutdown();
|
||||||
serverThread.join(2000);
|
serverThread.join(2000);
|
||||||
|
|
||||||
Thread.sleep(500); // wait for threads to die
|
Thread.sleep(500); // wait for threads to die
|
||||||
|
|
||||||
// thread count should decrese (traffic light threads stop)
|
// thread count should decrese (traffic light threads stop)
|
||||||
int threadCountAfter = Thread.activeCount();
|
int threadCountAfter = Thread.activeCount();
|
||||||
assertTrue(threadCountAfter <= threadCountBefore);
|
assertTrue(threadCountAfter <= threadCountBefore);
|
||||||
@@ -388,45 +419,68 @@ public class IntersectionProcessTest {
|
|||||||
@Test
|
@Test
|
||||||
@Timeout(15)
|
@Timeout(15)
|
||||||
public void testIntegration_TwoIntersectionsVehicleTransfer() throws IOException, InterruptedException {
|
public void testIntegration_TwoIntersectionsVehicleTransfer() throws IOException, InterruptedException {
|
||||||
// setup 2 intersections
|
IntersectionProcess cr1 = null;
|
||||||
IntersectionProcess cr1 = new IntersectionProcess("Cr1", configFile.toString());
|
IntersectionProcess cr2 = null;
|
||||||
IntersectionProcess cr2 = new IntersectionProcess("Cr2", configFile.toString());
|
Thread thread1 = null;
|
||||||
|
Thread thread2 = null;
|
||||||
cr1.initialize();
|
|
||||||
cr2.initialize();
|
try {
|
||||||
|
// setup 2 intersections
|
||||||
// start both
|
cr1 = new IntersectionProcess("Cr1", configFile.toString());
|
||||||
Thread thread1 = new Thread(() -> {
|
cr2 = new IntersectionProcess("Cr2", configFile.toString());
|
||||||
try { cr1.start(); } catch (IOException e) { }
|
|
||||||
});
|
cr1.initialize();
|
||||||
|
cr2.initialize();
|
||||||
Thread thread2 = new Thread(() -> {
|
|
||||||
try { cr2.start(); } catch (IOException e) { }
|
// start both
|
||||||
});
|
final IntersectionProcess cr1Final = cr1;
|
||||||
|
thread1 = new Thread(() -> {
|
||||||
thread1.start();
|
try {
|
||||||
thread2.start();
|
cr1Final.start();
|
||||||
|
} catch (IOException e) {
|
||||||
Thread.sleep(1000); // wait for servers
|
}
|
||||||
|
});
|
||||||
// send vehicle to Cr1 that goes to Cr2
|
|
||||||
java.util.List<String> route = Arrays.asList("Cr1", "Cr2", "S");
|
final IntersectionProcess cr2Final = cr2;
|
||||||
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 0.0, route);
|
thread2 = new Thread(() -> {
|
||||||
|
try {
|
||||||
try (Socket socket = new Socket("localhost", 18001)) {
|
cr2Final.start();
|
||||||
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
} catch (IOException e) {
|
||||||
|
}
|
||||||
TestVehicleMessage message = new TestVehicleMessage("Entry", "Cr1", vehicle);
|
});
|
||||||
out.writeObject(message);
|
|
||||||
out.flush();
|
thread1.start();
|
||||||
|
thread2.start();
|
||||||
Thread.sleep(2000); // time for processing
|
|
||||||
|
Thread.sleep(1000); // wait for servers
|
||||||
|
|
||||||
|
// send vehicle to Cr1 that goes to Cr2 - FIXED: use 4-parameter constructor
|
||||||
|
java.util.List<String> route = Arrays.asList("Cr1", "Cr2", "S");
|
||||||
|
Vehicle vehicle = new Vehicle("V001", VehicleType.LIGHT, 0.0, route);
|
||||||
|
|
||||||
|
// FIXED: use SocketConnection
|
||||||
|
try (Socket socket = new Socket("localhost", 18001);
|
||||||
|
SocketConnection conn = new SocketConnection(socket)) {
|
||||||
|
|
||||||
|
TestVehicleMessage message = new TestVehicleMessage("Entry", "Cr1", vehicle);
|
||||||
|
conn.sendMessage(message);
|
||||||
|
|
||||||
|
Thread.sleep(2000); // time for processing
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (cr1 != null) {
|
||||||
|
cr1.shutdown();
|
||||||
|
}
|
||||||
|
if (cr2 != null) {
|
||||||
|
cr2.shutdown();
|
||||||
|
}
|
||||||
|
if (thread1 != null) {
|
||||||
|
thread1.join(2000);
|
||||||
|
}
|
||||||
|
if (thread2 != null) {
|
||||||
|
thread2.join(2000);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cr1.shutdown();
|
|
||||||
cr2.shutdown();
|
|
||||||
thread1.join(2000);
|
|
||||||
thread2.join(2000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -439,32 +493,32 @@ public class IntersectionProcessTest {
|
|||||||
// helper class for testing vehicle messages
|
// helper class for testing vehicle messages
|
||||||
private static class TestVehicleMessage implements sd.protocol.MessageProtocol {
|
private static class TestVehicleMessage implements sd.protocol.MessageProtocol {
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
private final String sourceNode;
|
private final String sourceNode;
|
||||||
private final String destinationNode;
|
private final String destinationNode;
|
||||||
private final Vehicle payload;
|
private final Vehicle payload;
|
||||||
|
|
||||||
public TestVehicleMessage(String sourceNode, String destinationNode, Vehicle vehicle) {
|
public TestVehicleMessage(String sourceNode, String destinationNode, Vehicle vehicle) {
|
||||||
this.sourceNode = sourceNode;
|
this.sourceNode = sourceNode;
|
||||||
this.destinationNode = destinationNode;
|
this.destinationNode = destinationNode;
|
||||||
this.payload = vehicle;
|
this.payload = vehicle;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public MessageType getType() {
|
public MessageType getType() {
|
||||||
return MessageType.VEHICLE_TRANSFER;
|
return MessageType.VEHICLE_TRANSFER;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object getPayload() {
|
public Object getPayload() {
|
||||||
return payload;
|
return payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getSourceNode() {
|
public String getSourceNode() {
|
||||||
return sourceNode;
|
return sourceNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getDestinationNode() {
|
public String getDestinationNode() {
|
||||||
return destinationNode;
|
return destinationNode;
|
||||||
|
|||||||
@@ -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 static org.junit.jupiter.api.Assertions.*;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
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("\n✅ Traffic light coordination working correctly!");
|
System.out.println("\nTraffic light coordination working correctly!");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
164
main/src/test/java/sd/dashboard/DashboardTest.java
Normal file
164
main/src/test/java/sd/dashboard/DashboardTest.java
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
60
main/start.sh
Executable file
60
main/start.sh
Executable file
@@ -0,0 +1,60 @@
|
|||||||
|
#!/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 ""
|
||||||
Reference in New Issue
Block a user