mirror of
https://github.com/davidalves04/Trabalho-Pratico-SD.git
synced 2025-12-08 20:43:32 +00:00
moved start to dashboard + fixed holding queue - looped sleep might be fine in this case + better customization via CSS file
This commit is contained in:
@@ -8,6 +8,7 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.locks.Lock;
|
import java.util.concurrent.locks.Lock;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
@@ -47,6 +48,8 @@ public class IntersectionProcess {
|
|||||||
|
|
||||||
private final ExecutorService trafficLightPool;
|
private final ExecutorService trafficLightPool;
|
||||||
|
|
||||||
|
private ScheduledExecutorService statsExecutor;
|
||||||
|
|
||||||
private volatile boolean running; // Quando uma thread escreve um valor volatile, todas as outras
|
private volatile boolean running; // Quando uma thread escreve um valor volatile, todas as outras
|
||||||
// threads veem a mudança imediatamente.
|
// threads veem a mudança imediatamente.
|
||||||
|
|
||||||
@@ -67,7 +70,6 @@ public class IntersectionProcess {
|
|||||||
private SocketClient dashboardClient;
|
private SocketClient dashboardClient;
|
||||||
private volatile int totalArrivals = 0;
|
private volatile int totalArrivals = 0;
|
||||||
private volatile int totalDepartures = 0;
|
private volatile int totalDepartures = 0;
|
||||||
private long lastStatsUpdateTime;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new IntersectionProcess.
|
* Constructs a new IntersectionProcess.
|
||||||
@@ -83,8 +85,9 @@ public class IntersectionProcess {
|
|||||||
this.outgoingConnections = new HashMap<>();
|
this.outgoingConnections = new HashMap<>();
|
||||||
this.connectionHandlerPool = Executors.newCachedThreadPool();
|
this.connectionHandlerPool = Executors.newCachedThreadPool();
|
||||||
this.trafficLightPool = Executors.newFixedThreadPool(4); // Max 4 directions
|
this.trafficLightPool = Executors.newFixedThreadPool(4); // Max 4 directions
|
||||||
|
this.statsExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||||
this.running = false;
|
this.running = false;
|
||||||
this.trafficCoordinationLock = new ReentrantLock();
|
this.trafficCoordinationLock = new ReentrantLock(true); // Fair lock to prevent starvation
|
||||||
this.currentGreenDirection = null;
|
this.currentGreenDirection = null;
|
||||||
|
|
||||||
System.out.println("=".repeat(60));
|
System.out.println("=".repeat(60));
|
||||||
@@ -148,7 +151,6 @@ public class IntersectionProcess {
|
|||||||
dashboardClient.connect();
|
dashboardClient.connect();
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Connected to dashboard.");
|
System.out.println("[" + intersectionId + "] Connected to dashboard.");
|
||||||
lastStatsUpdateTime = System.currentTimeMillis();
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("[" + intersectionId + "] Failed to connect to dashboard: " +
|
System.err.println("[" + intersectionId + "] Failed to connect to dashboard: " +
|
||||||
@@ -365,6 +367,9 @@ public class IntersectionProcess {
|
|||||||
// Start traffic light threads when running is true
|
// Start traffic light threads when running is true
|
||||||
startTrafficLights();
|
startTrafficLights();
|
||||||
|
|
||||||
|
// Start stats updater
|
||||||
|
statsExecutor.scheduleAtFixedRate(this::sendStatsToDashboard, 1, 1, TimeUnit.SECONDS);
|
||||||
|
|
||||||
System.out.println("[" + intersectionId + "] Waiting for incoming connections...\n");
|
System.out.println("[" + intersectionId + "] Waiting for incoming connections...\n");
|
||||||
|
|
||||||
// Main accept loop
|
// Main accept loop
|
||||||
@@ -523,6 +528,9 @@ public class IntersectionProcess {
|
|||||||
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
if (connectionHandlerPool != null && !connectionHandlerPool.isShutdown()) {
|
||||||
connectionHandlerPool.shutdownNow();
|
connectionHandlerPool.shutdownNow();
|
||||||
}
|
}
|
||||||
|
if (statsExecutor != null && !statsExecutor.isShutdown()) {
|
||||||
|
statsExecutor.shutdownNow();
|
||||||
|
}
|
||||||
|
|
||||||
// 3. Wait briefly for termination (don't block forever)
|
// 3. Wait briefly for termination (don't block forever)
|
||||||
try {
|
try {
|
||||||
@@ -532,6 +540,9 @@ public class IntersectionProcess {
|
|||||||
if (connectionHandlerPool != null) {
|
if (connectionHandlerPool != null) {
|
||||||
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
connectionHandlerPool.awaitTermination(1, TimeUnit.SECONDS);
|
||||||
}
|
}
|
||||||
|
if (statsExecutor != null) {
|
||||||
|
statsExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
}
|
}
|
||||||
@@ -572,7 +583,6 @@ public class IntersectionProcess {
|
|||||||
*/
|
*/
|
||||||
public void recordVehicleArrival() {
|
public void recordVehicleArrival() {
|
||||||
totalArrivals++;
|
totalArrivals++;
|
||||||
checkAndSendStats();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -580,22 +590,6 @@ public class IntersectionProcess {
|
|||||||
*/
|
*/
|
||||||
public void recordVehicleDeparture() {
|
public void recordVehicleDeparture() {
|
||||||
totalDepartures++;
|
totalDepartures++;
|
||||||
checkAndSendStats();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if it's time to send statistics to the dashboard and sends them if
|
|
||||||
* needed.
|
|
||||||
*/
|
|
||||||
private void checkAndSendStats() {
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
long elapsed = now - lastStatsUpdateTime;
|
|
||||||
|
|
||||||
// Send stats every 5 seconds
|
|
||||||
if (elapsed >= 5000) {
|
|
||||||
sendStatsToDashboard();
|
|
||||||
lastStatsUpdateTime = now;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ public class CoordinatorProcess {
|
|||||||
|
|
||||||
System.out.println("Connecting to intersection processes...");
|
System.out.println("Connecting to intersection processes...");
|
||||||
|
|
||||||
String[] intersectionIds = {"Cr1", "Cr2", "Cr3", "Cr4", "Cr5"};
|
String[] intersectionIds = { "Cr1", "Cr2", "Cr3", "Cr4", "Cr5" };
|
||||||
|
|
||||||
for (String intersectionId : intersectionIds) {
|
for (String intersectionId : intersectionIds) {
|
||||||
try {
|
try {
|
||||||
@@ -124,6 +124,14 @@ public class CoordinatorProcess {
|
|||||||
generateAndSendVehicle();
|
generateAndSendVehicle();
|
||||||
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
nextGenerationTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep((long) (TIME_STEP * 1000));
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
currentTime += TIME_STEP;
|
currentTime += TIME_STEP;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,7 +146,7 @@ public class CoordinatorProcess {
|
|||||||
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
|
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
|
||||||
|
|
||||||
System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n",
|
System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n",
|
||||||
currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute());
|
currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute());
|
||||||
|
|
||||||
// Send generation count to dashboard
|
// Send generation count to dashboard
|
||||||
sendGenerationStatsToDashboard();
|
sendGenerationStatsToDashboard();
|
||||||
@@ -162,11 +170,10 @@ public class CoordinatorProcess {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
Message message = new Message(
|
Message message = new Message(
|
||||||
MessageType.VEHICLE_SPAWN,
|
MessageType.VEHICLE_SPAWN,
|
||||||
"COORDINATOR",
|
"COORDINATOR",
|
||||||
intersectionId,
|
intersectionId,
|
||||||
vehicle
|
vehicle);
|
||||||
);
|
|
||||||
|
|
||||||
client.send(message);
|
client.send(message);
|
||||||
System.out.printf("->Sent to %s%n", intersectionId);
|
System.out.printf("->Sent to %s%n", intersectionId);
|
||||||
@@ -189,11 +196,10 @@ public class CoordinatorProcess {
|
|||||||
try {
|
try {
|
||||||
if (client.isConnected()) {
|
if (client.isConnected()) {
|
||||||
Message personalizedShutdown = new Message(
|
Message personalizedShutdown = new Message(
|
||||||
MessageType.SHUTDOWN,
|
MessageType.SHUTDOWN,
|
||||||
"COORDINATOR",
|
"COORDINATOR",
|
||||||
intersectionId,
|
intersectionId,
|
||||||
"Simulation complete"
|
"Simulation complete");
|
||||||
);
|
|
||||||
client.send(personalizedShutdown);
|
client.send(personalizedShutdown);
|
||||||
System.out.println("Sent shutdown message to " + intersectionId);
|
System.out.println("Sent shutdown message to " + intersectionId);
|
||||||
}
|
}
|
||||||
@@ -239,14 +245,13 @@ public class CoordinatorProcess {
|
|||||||
payload.setTotalVehiclesGenerated(vehicleCounter);
|
payload.setTotalVehiclesGenerated(vehicleCounter);
|
||||||
|
|
||||||
Message message = new Message(
|
Message message = new Message(
|
||||||
MessageType.STATS_UPDATE,
|
MessageType.STATS_UPDATE,
|
||||||
"COORDINATOR",
|
"COORDINATOR",
|
||||||
"Dashboard",
|
"Dashboard",
|
||||||
payload
|
payload);
|
||||||
);
|
|
||||||
|
|
||||||
dashboardClient.send(message);
|
dashboardClient.send(message);
|
||||||
} catch (Exception e) { //This is fine - can add IOException if need be
|
} catch (Exception e) { // This is fine - can add IOException if need be
|
||||||
// Don't crash if dashboard update fails
|
// Don't crash if dashboard update fails
|
||||||
System.err.println("Failed to send stats to dashboard: " + e.getMessage());
|
System.err.println("Failed to send stats to dashboard: " + e.getMessage());
|
||||||
}
|
}
|
||||||
@@ -259,11 +264,10 @@ public class CoordinatorProcess {
|
|||||||
for (Map.Entry<String, SocketClient> entry : intersectionClients.entrySet()) {
|
for (Map.Entry<String, SocketClient> entry : intersectionClients.entrySet()) {
|
||||||
try {
|
try {
|
||||||
Message message = new Message(
|
Message message = new Message(
|
||||||
MessageType.SIMULATION_START,
|
MessageType.SIMULATION_START,
|
||||||
"COORDINATOR",
|
"COORDINATOR",
|
||||||
entry.getKey(),
|
entry.getKey(),
|
||||||
startTimeMillis
|
startTimeMillis);
|
||||||
);
|
|
||||||
entry.getValue().send(message);
|
entry.getValue().send(message);
|
||||||
} catch (Exception e) { // Same thing here
|
} catch (Exception e) { // Same thing here
|
||||||
System.err.println("Failed to send start time to " + entry.getKey() + ": " + e.getMessage());
|
System.err.println("Failed to send start time to " + entry.getKey() + ": " + e.getMessage());
|
||||||
@@ -274,11 +278,10 @@ public class CoordinatorProcess {
|
|||||||
if (dashboardClient != null && dashboardClient.isConnected()) {
|
if (dashboardClient != null && dashboardClient.isConnected()) {
|
||||||
try {
|
try {
|
||||||
Message message = new Message(
|
Message message = new Message(
|
||||||
MessageType.SIMULATION_START,
|
MessageType.SIMULATION_START,
|
||||||
"COORDINATOR",
|
"COORDINATOR",
|
||||||
"Dashboard",
|
"Dashboard",
|
||||||
startTimeMillis
|
startTimeMillis);
|
||||||
);
|
|
||||||
dashboardClient.send(message);
|
dashboardClient.send(message);
|
||||||
} catch (Exception e) { // And here
|
} catch (Exception e) { // And here
|
||||||
// Don't crash
|
// Don't crash
|
||||||
|
|||||||
@@ -12,10 +12,10 @@ import javafx.geometry.Insets;
|
|||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
import javafx.scene.Scene;
|
import javafx.scene.Scene;
|
||||||
import javafx.scene.control.Alert;
|
import javafx.scene.control.Alert;
|
||||||
|
import javafx.scene.control.Button;
|
||||||
import javafx.scene.control.Label;
|
import javafx.scene.control.Label;
|
||||||
import javafx.scene.control.TableColumn;
|
import javafx.scene.control.TableColumn;
|
||||||
import javafx.scene.control.TableView;
|
import javafx.scene.control.TableView;
|
||||||
import javafx.scene.control.TitledPane;
|
|
||||||
import javafx.scene.control.cell.PropertyValueFactory;
|
import javafx.scene.control.cell.PropertyValueFactory;
|
||||||
import javafx.scene.layout.BorderPane;
|
import javafx.scene.layout.BorderPane;
|
||||||
import javafx.scene.layout.GridPane;
|
import javafx.scene.layout.GridPane;
|
||||||
@@ -23,10 +23,7 @@ import javafx.scene.layout.HBox;
|
|||||||
import javafx.scene.layout.Priority;
|
import javafx.scene.layout.Priority;
|
||||||
import javafx.scene.layout.Region;
|
import javafx.scene.layout.Region;
|
||||||
import javafx.scene.layout.VBox;
|
import javafx.scene.layout.VBox;
|
||||||
import javafx.scene.paint.Color;
|
|
||||||
import javafx.scene.shape.Circle;
|
import javafx.scene.shape.Circle;
|
||||||
import javafx.scene.text.Font;
|
|
||||||
import javafx.scene.text.FontWeight;
|
|
||||||
import javafx.stage.Stage;
|
import javafx.stage.Stage;
|
||||||
import sd.config.SimulationConfig;
|
import sd.config.SimulationConfig;
|
||||||
import sd.model.VehicleType;
|
import sd.model.VehicleType;
|
||||||
@@ -62,8 +59,8 @@ public class DashboardUI extends Application {
|
|||||||
try {
|
try {
|
||||||
// Initialize server
|
// Initialize server
|
||||||
String configFile = getParameters().getRaw().isEmpty()
|
String configFile = getParameters().getRaw().isEmpty()
|
||||||
? "src/main/resources/simulation.properties"
|
? "src/main/resources/simulation.properties"
|
||||||
: getParameters().getRaw().get(0);
|
: getParameters().getRaw().get(0);
|
||||||
|
|
||||||
SimulationConfig config = new SimulationConfig(configFile);
|
SimulationConfig config = new SimulationConfig(configFile);
|
||||||
server = new DashboardServer(config);
|
server = new DashboardServer(config);
|
||||||
@@ -74,7 +71,7 @@ public class DashboardUI extends Application {
|
|||||||
|
|
||||||
// Build UI
|
// Build UI
|
||||||
BorderPane root = new BorderPane();
|
BorderPane root = new BorderPane();
|
||||||
root.setStyle("-fx-background-color: #f5f5f5;");
|
root.getStyleClass().add("root");
|
||||||
|
|
||||||
// Header
|
// Header
|
||||||
VBox header = createHeader();
|
VBox header = createHeader();
|
||||||
@@ -89,7 +86,12 @@ public class DashboardUI extends Application {
|
|||||||
root.setBottom(footer);
|
root.setBottom(footer);
|
||||||
|
|
||||||
// Create scene
|
// Create scene
|
||||||
Scene scene = new Scene(root, 1200, 800);
|
Scene scene = new Scene(root, 1200, 850);
|
||||||
|
|
||||||
|
// Load CSS
|
||||||
|
String cssUrl = getClass().getResource("/dashboard.css").toExternalForm();
|
||||||
|
scene.getStylesheets().add(cssUrl);
|
||||||
|
|
||||||
primaryStage.setTitle("Traffic Simulation Dashboard - Real-time Statistics");
|
primaryStage.setTitle("Traffic Simulation Dashboard - Real-time Statistics");
|
||||||
primaryStage.setScene(scene);
|
primaryStage.setScene(scene);
|
||||||
primaryStage.show();
|
primaryStage.show();
|
||||||
@@ -102,153 +104,204 @@ public class DashboardUI extends Application {
|
|||||||
shutdown();
|
shutdown();
|
||||||
});
|
});
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (Exception e) {
|
||||||
showErrorAlert("Failed to start Dashboard Server", e.getMessage());
|
showErrorAlert("Failed to start Dashboard Server", e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
Platform.exit();
|
Platform.exit();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private VBox createHeader() {
|
private VBox createHeader() {
|
||||||
VBox header = new VBox(10);
|
VBox header = new VBox(10);
|
||||||
header.setPadding(new Insets(20));
|
header.getStyleClass().add("header");
|
||||||
header.setStyle("-fx-background-color: linear-gradient(to right, #2c3e50, #3498db);");
|
header.setAlignment(Pos.CENTER);
|
||||||
|
|
||||||
Label title = new Label("DISTRIBUTED TRAFFIC SIMULATION DASHBOARD");
|
Label title = new Label("DISTRIBUTED TRAFFIC SIMULATION DASHBOARD");
|
||||||
title.setFont(Font.font("Arial", FontWeight.BOLD, 28));
|
title.getStyleClass().add("header-title");
|
||||||
title.setTextFill(Color.WHITE);
|
|
||||||
|
|
||||||
Label subtitle = new Label("Real-time Statistics and Monitoring");
|
Label subtitle = new Label("Real-time Statistics and Monitoring");
|
||||||
subtitle.setFont(Font.font("Arial", FontWeight.NORMAL, 16));
|
subtitle.getStyleClass().add("header-subtitle");
|
||||||
subtitle.setTextFill(Color.web("#ecf0f1"));
|
|
||||||
|
|
||||||
header.getChildren().addAll(title, subtitle);
|
// Control Buttons
|
||||||
header.setAlignment(Pos.CENTER);
|
HBox controls = new HBox(15);
|
||||||
|
controls.setAlignment(Pos.CENTER);
|
||||||
|
|
||||||
|
Button btnStart = new Button("START SIMULATION");
|
||||||
|
btnStart.getStyleClass().add("button-start");
|
||||||
|
|
||||||
|
Button btnStop = new Button("STOP SIMULATION");
|
||||||
|
btnStop.getStyleClass().add("button-stop");
|
||||||
|
btnStop.setDisable(true);
|
||||||
|
|
||||||
|
SimulationProcessManager processManager = new SimulationProcessManager();
|
||||||
|
|
||||||
|
btnStart.setOnAction(e -> {
|
||||||
|
try {
|
||||||
|
processManager.startSimulation();
|
||||||
|
btnStart.setDisable(true);
|
||||||
|
btnStop.setDisable(false);
|
||||||
|
} catch (IOException ex) {
|
||||||
|
showErrorAlert("Start Failed", "Could not start simulation processes: " + ex.getMessage());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
btnStop.setOnAction(e -> {
|
||||||
|
processManager.stopSimulation();
|
||||||
|
btnStart.setDisable(false);
|
||||||
|
btnStop.setDisable(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
controls.getChildren().addAll(btnStart, btnStop);
|
||||||
|
|
||||||
|
header.getChildren().addAll(title, subtitle, controls);
|
||||||
|
|
||||||
return header;
|
return header;
|
||||||
}
|
}
|
||||||
|
|
||||||
private VBox createMainContent() {
|
private VBox createMainContent() {
|
||||||
VBox mainContent = new VBox(15);
|
VBox mainContent = new VBox(20);
|
||||||
mainContent.setPadding(new Insets(20));
|
mainContent.setPadding(new Insets(20));
|
||||||
|
|
||||||
// Global Statistics Panel
|
// Global Statistics Panel
|
||||||
TitledPane globalStatsPane = createGlobalStatisticsPanel();
|
VBox globalStatsCard = createGlobalStatisticsPanel();
|
||||||
|
|
||||||
|
// Tables Container
|
||||||
|
HBox tablesContainer = new HBox(20);
|
||||||
|
tablesContainer.setAlignment(Pos.TOP_CENTER);
|
||||||
|
|
||||||
// Vehicle Type Statistics Panel
|
// Vehicle Type Statistics Panel
|
||||||
TitledPane vehicleTypePane = createVehicleTypePanel();
|
VBox vehicleTypeCard = createVehicleTypePanel();
|
||||||
|
HBox.setHgrow(vehicleTypeCard, Priority.ALWAYS);
|
||||||
|
|
||||||
// Intersection Statistics Panel
|
// Intersection Statistics Panel
|
||||||
TitledPane intersectionPane = createIntersectionPanel();
|
VBox intersectionCard = createIntersectionPanel();
|
||||||
|
HBox.setHgrow(intersectionCard, Priority.ALWAYS);
|
||||||
|
|
||||||
mainContent.getChildren().addAll(globalStatsPane, vehicleTypePane, intersectionPane);
|
tablesContainer.getChildren().addAll(vehicleTypeCard, intersectionCard);
|
||||||
|
|
||||||
|
mainContent.getChildren().addAll(globalStatsCard, tablesContainer);
|
||||||
|
|
||||||
return mainContent;
|
return mainContent;
|
||||||
}
|
}
|
||||||
|
|
||||||
private TitledPane createGlobalStatisticsPanel() {
|
private VBox createGlobalStatisticsPanel() {
|
||||||
|
VBox card = new VBox();
|
||||||
|
card.getStyleClass().add("card");
|
||||||
|
|
||||||
|
// Card Header
|
||||||
|
HBox cardHeader = new HBox();
|
||||||
|
cardHeader.getStyleClass().add("card-header");
|
||||||
|
Label cardTitle = new Label("Global Statistics");
|
||||||
|
cardTitle.getStyleClass().add("card-title");
|
||||||
|
cardHeader.getChildren().add(cardTitle);
|
||||||
|
|
||||||
|
// Card Content
|
||||||
GridPane grid = new GridPane();
|
GridPane grid = new GridPane();
|
||||||
grid.setPadding(new Insets(15));
|
grid.getStyleClass().add("card-content");
|
||||||
grid.setHgap(20);
|
grid.setHgap(40);
|
||||||
grid.setVgap(15);
|
grid.setVgap(15);
|
||||||
grid.setStyle("-fx-background-color: white; -fx-border-radius: 5;");
|
grid.setAlignment(Pos.CENTER);
|
||||||
|
|
||||||
// Initialize labels
|
// Initialize labels
|
||||||
lblVehiclesGenerated = createStatLabel("0");
|
lblVehiclesGenerated = createStatValueLabel("0");
|
||||||
lblVehiclesCompleted = createStatLabel("0");
|
lblVehiclesCompleted = createStatValueLabel("0");
|
||||||
lblVehiclesInTransit = createStatLabel("0");
|
lblVehiclesInTransit = createStatValueLabel("0");
|
||||||
lblAvgSystemTime = createStatLabel("0.00 ms");
|
lblAvgSystemTime = createStatValueLabel("0.00 s");
|
||||||
lblAvgWaitingTime = createStatLabel("0.00 ms");
|
lblAvgWaitingTime = createStatValueLabel("0.00 s");
|
||||||
|
|
||||||
// Add labels with descriptions
|
// Add labels with descriptions
|
||||||
addStatRow(grid, 0, "Total Vehicles Generated:", lblVehiclesGenerated);
|
addStatRow(grid, 0, 0, "Total Vehicles Generated", lblVehiclesGenerated);
|
||||||
addStatRow(grid, 1, "Total Vehicles Completed:", lblVehiclesCompleted);
|
addStatRow(grid, 1, 0, "Total Vehicles Completed", lblVehiclesCompleted);
|
||||||
addStatRow(grid, 2, "Vehicles In Transit:", lblVehiclesInTransit);
|
addStatRow(grid, 2, 0, "Vehicles In Transit", lblVehiclesInTransit);
|
||||||
addStatRow(grid, 3, "Average System Time:", lblAvgSystemTime);
|
addStatRow(grid, 0, 1, "Average System Time", lblAvgSystemTime);
|
||||||
addStatRow(grid, 4, "Average Waiting Time:", lblAvgWaitingTime);
|
addStatRow(grid, 1, 1, "Average Waiting Time", lblAvgWaitingTime);
|
||||||
|
|
||||||
TitledPane pane = new TitledPane("Global Statistics", grid);
|
card.getChildren().addAll(cardHeader, grid);
|
||||||
pane.setCollapsible(false);
|
return card;
|
||||||
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
|
||||||
|
|
||||||
return pane;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private TitledPane createVehicleTypePanel() {
|
private VBox createVehicleTypePanel() {
|
||||||
|
VBox card = new VBox();
|
||||||
|
card.getStyleClass().add("card");
|
||||||
|
|
||||||
|
// Card Header
|
||||||
|
HBox cardHeader = new HBox();
|
||||||
|
cardHeader.getStyleClass().add("card-header");
|
||||||
|
Label cardTitle = new Label("Vehicle Type Statistics");
|
||||||
|
cardTitle.getStyleClass().add("card-title");
|
||||||
|
cardHeader.getChildren().add(cardTitle);
|
||||||
|
|
||||||
|
// Table
|
||||||
vehicleTypeTable = new TableView<>();
|
vehicleTypeTable = new TableView<>();
|
||||||
vehicleTypeTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
vehicleTypeTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
||||||
vehicleTypeTable.setPrefHeight(200);
|
vehicleTypeTable.setPrefHeight(300);
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, String> typeCol = new TableColumn<>("Vehicle Type");
|
TableColumn<VehicleTypeRow, String> typeCol = new TableColumn<>("Vehicle Type");
|
||||||
typeCol.setCellValueFactory(new PropertyValueFactory<>("vehicleType"));
|
typeCol.setCellValueFactory(new PropertyValueFactory<>("vehicleType"));
|
||||||
typeCol.setPrefWidth(200);
|
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, Integer> countCol = new TableColumn<>("Count");
|
TableColumn<VehicleTypeRow, Integer> countCol = new TableColumn<>("Count");
|
||||||
countCol.setCellValueFactory(new PropertyValueFactory<>("count"));
|
countCol.setCellValueFactory(new PropertyValueFactory<>("count"));
|
||||||
countCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
TableColumn<VehicleTypeRow, String> avgWaitCol = new TableColumn<>("Avg Wait Time");
|
TableColumn<VehicleTypeRow, String> avgWaitCol = new TableColumn<>("Avg Wait Time");
|
||||||
avgWaitCol.setCellValueFactory(new PropertyValueFactory<>("avgWaitTime"));
|
avgWaitCol.setCellValueFactory(new PropertyValueFactory<>("avgWaitTime"));
|
||||||
avgWaitCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
vehicleTypeTable.getColumns().addAll(typeCol, countCol, avgWaitCol);
|
vehicleTypeTable.getColumns().addAll(typeCol, countCol, avgWaitCol);
|
||||||
|
|
||||||
TitledPane pane = new TitledPane("Vehicle Type Statistics", vehicleTypeTable);
|
card.getChildren().addAll(cardHeader, vehicleTypeTable);
|
||||||
pane.setCollapsible(false);
|
return card;
|
||||||
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
|
||||||
|
|
||||||
return pane;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private TitledPane createIntersectionPanel() {
|
private VBox createIntersectionPanel() {
|
||||||
|
VBox card = new VBox();
|
||||||
|
card.getStyleClass().add("card");
|
||||||
|
|
||||||
|
// Card Header
|
||||||
|
HBox cardHeader = new HBox();
|
||||||
|
cardHeader.getStyleClass().add("card-header");
|
||||||
|
Label cardTitle = new Label("Intersection Statistics");
|
||||||
|
cardTitle.getStyleClass().add("card-title");
|
||||||
|
cardHeader.getChildren().add(cardTitle);
|
||||||
|
|
||||||
|
// Table
|
||||||
intersectionTable = new TableView<>();
|
intersectionTable = new TableView<>();
|
||||||
intersectionTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
intersectionTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
||||||
intersectionTable.setPrefHeight(250);
|
intersectionTable.setPrefHeight(300);
|
||||||
|
|
||||||
TableColumn<IntersectionRow, String> idCol = new TableColumn<>("Intersection ID");
|
TableColumn<IntersectionRow, String> idCol = new TableColumn<>("Intersection ID");
|
||||||
idCol.setCellValueFactory(new PropertyValueFactory<>("intersectionId"));
|
idCol.setCellValueFactory(new PropertyValueFactory<>("intersectionId"));
|
||||||
idCol.setPrefWidth(200);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> arrivalsCol = new TableColumn<>("Total Arrivals");
|
TableColumn<IntersectionRow, Integer> arrivalsCol = new TableColumn<>("Total Arrivals");
|
||||||
arrivalsCol.setCellValueFactory(new PropertyValueFactory<>("arrivals"));
|
arrivalsCol.setCellValueFactory(new PropertyValueFactory<>("arrivals"));
|
||||||
arrivalsCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> departuresCol = new TableColumn<>("Total Departures");
|
TableColumn<IntersectionRow, Integer> departuresCol = new TableColumn<>("Total Departures");
|
||||||
departuresCol.setCellValueFactory(new PropertyValueFactory<>("departures"));
|
departuresCol.setCellValueFactory(new PropertyValueFactory<>("departures"));
|
||||||
departuresCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
TableColumn<IntersectionRow, Integer> queueCol = new TableColumn<>("Current Queue");
|
TableColumn<IntersectionRow, Integer> queueCol = new TableColumn<>("Current Queue");
|
||||||
queueCol.setCellValueFactory(new PropertyValueFactory<>("queueSize"));
|
queueCol.setCellValueFactory(new PropertyValueFactory<>("queueSize"));
|
||||||
queueCol.setPrefWidth(150);
|
|
||||||
|
|
||||||
intersectionTable.getColumns().addAll(idCol, arrivalsCol, departuresCol, queueCol);
|
intersectionTable.getColumns().addAll(idCol, arrivalsCol, departuresCol, queueCol);
|
||||||
|
|
||||||
TitledPane pane = new TitledPane("Intersection Statistics", intersectionTable);
|
card.getChildren().addAll(cardHeader, intersectionTable);
|
||||||
pane.setCollapsible(false);
|
return card;
|
||||||
pane.setFont(Font.font("Arial", FontWeight.BOLD, 16));
|
|
||||||
|
|
||||||
return pane;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private HBox createFooter() {
|
private HBox createFooter() {
|
||||||
HBox footer = new HBox(10);
|
HBox footer = new HBox(10);
|
||||||
footer.setPadding(new Insets(10, 20, 10, 20));
|
footer.getStyleClass().add("footer");
|
||||||
footer.setStyle("-fx-background-color: #34495e;");
|
|
||||||
footer.setAlignment(Pos.CENTER_LEFT);
|
footer.setAlignment(Pos.CENTER_LEFT);
|
||||||
|
|
||||||
Label statusLabel = new Label("Status:");
|
Label statusLabel = new Label("Status:");
|
||||||
statusLabel.setTextFill(Color.WHITE);
|
statusLabel.getStyleClass().add("footer-text");
|
||||||
statusLabel.setFont(Font.font("Arial", FontWeight.BOLD, 12));
|
statusLabel.setStyle("-fx-font-weight: bold;");
|
||||||
|
|
||||||
Circle statusIndicator = new Circle(6);
|
Circle statusIndicator = new Circle(6);
|
||||||
statusIndicator.setFill(Color.LIME);
|
statusIndicator.setFill(javafx.scene.paint.Color.LIME);
|
||||||
|
|
||||||
Label statusText = new Label("Connected and Receiving Data");
|
Label statusText = new Label("Connected and Receiving Data");
|
||||||
statusText.setTextFill(Color.WHITE);
|
statusText.getStyleClass().add("footer-text");
|
||||||
statusText.setFont(Font.font("Arial", 12));
|
|
||||||
|
|
||||||
lblLastUpdate = new Label("Last Update: --:--:--");
|
lblLastUpdate = new Label("Last Update: --:--:--");
|
||||||
lblLastUpdate.setTextFill(Color.web("#ecf0f1"));
|
lblLastUpdate.getStyleClass().add("footer-text");
|
||||||
lblLastUpdate.setFont(Font.font("Arial", 12));
|
|
||||||
|
|
||||||
Region spacer = new Region();
|
Region spacer = new Region();
|
||||||
HBox.setHgrow(spacer, Priority.ALWAYS);
|
HBox.setHgrow(spacer, Priority.ALWAYS);
|
||||||
@@ -258,20 +311,22 @@ public class DashboardUI extends Application {
|
|||||||
return footer;
|
return footer;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Label createStatLabel(String initialValue) {
|
private Label createStatValueLabel(String initialValue) {
|
||||||
Label label = new Label(initialValue);
|
Label label = new Label(initialValue);
|
||||||
label.setFont(Font.font("Arial", FontWeight.BOLD, 20));
|
label.getStyleClass().add("stat-value");
|
||||||
label.setTextFill(Color.web("#2980b9"));
|
|
||||||
return label;
|
return label;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addStatRow(GridPane grid, int row, String description, Label valueLabel) {
|
private void addStatRow(GridPane grid, int row, int colGroup, String description, Label valueLabel) {
|
||||||
Label descLabel = new Label(description);
|
VBox container = new VBox(5);
|
||||||
descLabel.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
|
container.setAlignment(Pos.CENTER_LEFT);
|
||||||
descLabel.setTextFill(Color.web("#34495e"));
|
|
||||||
|
|
||||||
grid.add(descLabel, 0, row);
|
Label descLabel = new Label(description);
|
||||||
grid.add(valueLabel, 1, row);
|
descLabel.getStyleClass().add("stat-label");
|
||||||
|
|
||||||
|
container.getChildren().addAll(descLabel, valueLabel);
|
||||||
|
|
||||||
|
grid.add(container, colGroup, row);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void startPeriodicUpdates() {
|
private void startPeriodicUpdates() {
|
||||||
@@ -286,9 +341,9 @@ public class DashboardUI extends Application {
|
|||||||
lblVehiclesGenerated.setText(String.valueOf(statistics.getTotalVehiclesGenerated()));
|
lblVehiclesGenerated.setText(String.valueOf(statistics.getTotalVehiclesGenerated()));
|
||||||
lblVehiclesCompleted.setText(String.valueOf(statistics.getTotalVehiclesCompleted()));
|
lblVehiclesCompleted.setText(String.valueOf(statistics.getTotalVehiclesCompleted()));
|
||||||
lblVehiclesInTransit.setText(String.valueOf(
|
lblVehiclesInTransit.setText(String.valueOf(
|
||||||
statistics.getTotalVehiclesGenerated() - statistics.getTotalVehiclesCompleted()));
|
statistics.getTotalVehiclesGenerated() - statistics.getTotalVehiclesCompleted()));
|
||||||
lblAvgSystemTime.setText(String.format("%.2f ms", statistics.getAverageSystemTime()));
|
lblAvgSystemTime.setText(String.format("%.2f s", statistics.getAverageSystemTime() / 1000.0));
|
||||||
lblAvgWaitingTime.setText(String.format("%.2f ms", statistics.getAverageWaitingTime()));
|
lblAvgWaitingTime.setText(String.format("%.2f s", statistics.getAverageWaitingTime() / 1000.0));
|
||||||
lblLastUpdate.setText(String.format("Last Update: %tT", statistics.getLastUpdateTime()));
|
lblLastUpdate.setText(String.format("Last Update: %tT", statistics.getLastUpdateTime()));
|
||||||
|
|
||||||
// Update vehicle type table
|
// Update vehicle type table
|
||||||
@@ -297,20 +352,18 @@ public class DashboardUI extends Application {
|
|||||||
int count = statistics.getVehicleTypeCount(type);
|
int count = statistics.getVehicleTypeCount(type);
|
||||||
double avgWait = statistics.getAverageWaitingTimeByType(type);
|
double avgWait = statistics.getAverageWaitingTimeByType(type);
|
||||||
vehicleTypeTable.getItems().add(new VehicleTypeRow(
|
vehicleTypeTable.getItems().add(new VehicleTypeRow(
|
||||||
type.toString(), count, String.format("%.2f ms", avgWait)));
|
type.toString(), count, String.format("%.2f s", avgWait / 1000.0)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update intersection table
|
// Update intersection table
|
||||||
intersectionTable.getItems().clear();
|
intersectionTable.getItems().clear();
|
||||||
Map<String, DashboardStatistics.IntersectionStats> intersectionStats =
|
Map<String, DashboardStatistics.IntersectionStats> intersectionStats = statistics.getAllIntersectionStats();
|
||||||
statistics.getAllIntersectionStats();
|
|
||||||
for (DashboardStatistics.IntersectionStats stats : intersectionStats.values()) {
|
for (DashboardStatistics.IntersectionStats stats : intersectionStats.values()) {
|
||||||
intersectionTable.getItems().add(new IntersectionRow(
|
intersectionTable.getItems().add(new IntersectionRow(
|
||||||
stats.getIntersectionId(),
|
stats.getIntersectionId(),
|
||||||
stats.getTotalArrivals(),
|
stats.getTotalArrivals(),
|
||||||
stats.getTotalDepartures(),
|
stats.getTotalDepartures(),
|
||||||
stats.getCurrentQueueSize()
|
stats.getCurrentQueueSize()));
|
||||||
));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -352,9 +405,17 @@ public class DashboardUI extends Application {
|
|||||||
this.avgWaitTime = avgWaitTime;
|
this.avgWaitTime = avgWaitTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getVehicleType() { return vehicleType; }
|
public String getVehicleType() {
|
||||||
public int getCount() { return count; }
|
return vehicleType;
|
||||||
public String getAvgWaitTime() { return avgWaitTime; }
|
}
|
||||||
|
|
||||||
|
public int getCount() {
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAvgWaitTime() {
|
||||||
|
return avgWaitTime;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class IntersectionRow {
|
public static class IntersectionRow {
|
||||||
@@ -370,9 +431,20 @@ public class DashboardUI extends Application {
|
|||||||
this.queueSize = queueSize;
|
this.queueSize = queueSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getIntersectionId() { return intersectionId; }
|
public String getIntersectionId() {
|
||||||
public int getArrivals() { return arrivals; }
|
return intersectionId;
|
||||||
public int getDepartures() { return departures; }
|
}
|
||||||
public int getQueueSize() { return queueSize; }
|
|
||||||
|
public int getArrivals() {
|
||||||
|
return arrivals;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getDepartures() {
|
||||||
|
return departures;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getQueueSize() {
|
||||||
|
return queueSize;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
112
main/src/main/java/sd/dashboard/SimulationProcessManager.java
Normal file
112
main/src/main/java/sd/dashboard/SimulationProcessManager.java
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
package sd.dashboard;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manages the lifecycle of simulation processes (Intersections, Exit Node,
|
||||||
|
* Coordinator).
|
||||||
|
* Allows starting and stopping the distributed simulation from within the Java
|
||||||
|
* application.
|
||||||
|
*/
|
||||||
|
public class SimulationProcessManager {
|
||||||
|
|
||||||
|
private final List<Process> runningProcesses;
|
||||||
|
private final String classpath;
|
||||||
|
|
||||||
|
public SimulationProcessManager() {
|
||||||
|
this.runningProcesses = new ArrayList<>();
|
||||||
|
this.classpath = System.getProperty("java.class.path");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the full simulation: 5 Intersections, 1 Exit Node, and 1 Coordinator.
|
||||||
|
*
|
||||||
|
* @throws IOException If a process fails to start.
|
||||||
|
*/
|
||||||
|
public void startSimulation() throws IOException {
|
||||||
|
if (!runningProcesses.isEmpty()) {
|
||||||
|
stopSimulation();
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("Starting simulation processes...");
|
||||||
|
|
||||||
|
// 1. Start Intersections (Cr1 - Cr5)
|
||||||
|
String[] intersectionIds = { "Cr1", "Cr2", "Cr3", "Cr4", "Cr5" };
|
||||||
|
for (String id : intersectionIds) {
|
||||||
|
startProcess("sd.IntersectionProcess", id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Start Exit Node
|
||||||
|
startProcess("sd.ExitNodeProcess", null);
|
||||||
|
|
||||||
|
// 3. Start Coordinator (Wait a bit for others to initialize)
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
startProcess("sd.coordinator.CoordinatorProcess", null);
|
||||||
|
|
||||||
|
System.out.println("All simulation processes started.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stops all running simulation processes.
|
||||||
|
*/
|
||||||
|
public void stopSimulation() {
|
||||||
|
System.out.println("Stopping simulation processes...");
|
||||||
|
|
||||||
|
for (Process process : runningProcesses) {
|
||||||
|
if (process.isAlive()) {
|
||||||
|
process.destroy(); // Try graceful termination first
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait a bit and force kill if necessary
|
||||||
|
try {
|
||||||
|
Thread.sleep(500);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Process process : runningProcesses) {
|
||||||
|
if (process.isAlive()) {
|
||||||
|
process.destroyForcibly();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runningProcesses.clear();
|
||||||
|
System.out.println("All simulation processes stopped.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper to start a single Java process.
|
||||||
|
*/
|
||||||
|
private void startProcess(String className, String arg) throws IOException {
|
||||||
|
String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
|
||||||
|
|
||||||
|
ProcessBuilder builder;
|
||||||
|
if (arg != null) {
|
||||||
|
builder = new ProcessBuilder(javaBin, "-cp", classpath, className, arg);
|
||||||
|
} else {
|
||||||
|
builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||||
|
}
|
||||||
|
|
||||||
|
// this is a linux thing - not sure about windows
|
||||||
|
String logName = className.substring(className.lastIndexOf('.') + 1) + (arg != null ? "-" + arg : "") + ".log";
|
||||||
|
File logFile = new File("/tmp/" + logName);
|
||||||
|
builder.redirectOutput(logFile);
|
||||||
|
builder.redirectError(logFile);
|
||||||
|
|
||||||
|
Process process = builder.start();
|
||||||
|
runningProcesses.add(process);
|
||||||
|
System.out.println("Started " + className + (arg != null ? " " + arg : ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isSimulationRunning() {
|
||||||
|
return !runningProcesses.isEmpty() && runningProcesses.stream().anyMatch(Process::isAlive);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,6 @@ import java.io.Closeable;
|
|||||||
import java.io.DataInputStream;
|
import java.io.DataInputStream;
|
||||||
import java.io.DataOutputStream;
|
import java.io.DataOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.net.ConnectException;
|
import java.net.ConnectException;
|
||||||
@@ -127,7 +126,7 @@ public class SocketConnection implements Closeable {
|
|||||||
* @param message The "envelope" (which contains the Vehicle) to be sent.
|
* @param message The "envelope" (which contains the Vehicle) to be sent.
|
||||||
* @throws IOException If writing to the stream fails or socket is not connected.
|
* @throws IOException If writing to the stream fails or socket is not connected.
|
||||||
*/
|
*/
|
||||||
public void sendMessage(MessageProtocol message) throws IOException {
|
public synchronized void sendMessage(MessageProtocol message) throws IOException {
|
||||||
if (socket == null || !socket.isConnected()) {
|
if (socket == null || !socket.isConnected()) {
|
||||||
throw new IOException("Socket is not connected");
|
throw new IOException("Socket is not connected");
|
||||||
}
|
}
|
||||||
|
|||||||
142
main/src/main/resources/dashboard.css
Normal file
142
main/src/main/resources/dashboard.css
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
/* Global Styles */
|
||||||
|
.root {
|
||||||
|
-fx-background-color: #f4f7f6;
|
||||||
|
-fx-font-family: 'Segoe UI', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Header */
|
||||||
|
.header {
|
||||||
|
-fx-background-color: linear-gradient(to right, #2c3e50, #4ca1af);
|
||||||
|
-fx-padding: 20;
|
||||||
|
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 10, 0, 0, 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-title {
|
||||||
|
-fx-font-size: 28px;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
-fx-text-fill: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-subtitle {
|
||||||
|
-fx-font-size: 16px;
|
||||||
|
-fx-text-fill: #ecf0f1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.button-start {
|
||||||
|
-fx-background-color: #2ecc71;
|
||||||
|
-fx-text-fill: white;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
-fx-padding: 10 20;
|
||||||
|
-fx-background-radius: 5;
|
||||||
|
-fx-cursor: hand;
|
||||||
|
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-start:hover {
|
||||||
|
-fx-background-color: #27ae60;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-start:disabled {
|
||||||
|
-fx-background-color: #95a5a6;
|
||||||
|
-fx-opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-stop {
|
||||||
|
-fx-background-color: #e74c3c;
|
||||||
|
-fx-text-fill: white;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
-fx-padding: 10 20;
|
||||||
|
-fx-background-radius: 5;
|
||||||
|
-fx-cursor: hand;
|
||||||
|
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-stop:hover {
|
||||||
|
-fx-background-color: #c0392b;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-stop:disabled {
|
||||||
|
-fx-background-color: #95a5a6;
|
||||||
|
-fx-opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cards / Panels */
|
||||||
|
.card {
|
||||||
|
-fx-background-color: white;
|
||||||
|
-fx-background-radius: 8;
|
||||||
|
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.05), 10, 0, 0, 2);
|
||||||
|
-fx-padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
-fx-background-color: #ecf0f1;
|
||||||
|
-fx-background-radius: 8 8 0 0;
|
||||||
|
-fx-padding: 10 15;
|
||||||
|
-fx-border-color: #bdc3c7;
|
||||||
|
-fx-border-width: 0 0 1 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-title {
|
||||||
|
-fx-font-size: 16px;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
-fx-text-fill: #2c3e50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-content {
|
||||||
|
-fx-padding: 15;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Statistics Grid */
|
||||||
|
.stat-label {
|
||||||
|
-fx-font-size: 14px;
|
||||||
|
-fx-text-fill: #7f8c8d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-value {
|
||||||
|
-fx-font-size: 20px;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
-fx-text-fill: #2980b9;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tables */
|
||||||
|
.table-view {
|
||||||
|
-fx-background-color: transparent;
|
||||||
|
-fx-border-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-view .column-header-background {
|
||||||
|
-fx-background-color: #ecf0f1;
|
||||||
|
-fx-border-color: #bdc3c7;
|
||||||
|
-fx-border-width: 0 0 1 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-view .column-header .label {
|
||||||
|
-fx-text-fill: #2c3e50;
|
||||||
|
-fx-font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-row-cell {
|
||||||
|
-fx-background-color: white;
|
||||||
|
-fx-border-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-row-cell:odd {
|
||||||
|
-fx-background-color: #f9f9f9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-row-cell:selected {
|
||||||
|
-fx-background-color: #3498db;
|
||||||
|
-fx-text-fill: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Footer */
|
||||||
|
.footer {
|
||||||
|
-fx-background-color: #34495e;
|
||||||
|
-fx-padding: 10 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer-text {
|
||||||
|
-fx-text-fill: #ecf0f1;
|
||||||
|
-fx-font-size: 12px;
|
||||||
|
}
|
||||||
@@ -85,7 +85,7 @@ public class TrafficLightCoordinationTest {
|
|||||||
if (greenCount > 1) {
|
if (greenCount > 1) {
|
||||||
violationCount.incrementAndGet();
|
violationCount.incrementAndGet();
|
||||||
String violation = String.format("[VIOLATION] %d lights GREEN simultaneously: %s",
|
String violation = String.format("[VIOLATION] %d lights GREEN simultaneously: %s",
|
||||||
greenCount, currentState.toString());
|
greenCount, currentState.toString());
|
||||||
violations.add(violation);
|
violations.add(violation);
|
||||||
System.err.println(violation);
|
System.err.println(violation);
|
||||||
}
|
}
|
||||||
@@ -104,9 +104,9 @@ public class TrafficLightCoordinationTest {
|
|||||||
|
|
||||||
// Assert that we never had more than one green light
|
// Assert that we never had more than one green light
|
||||||
assertEquals(0, violationCount.get(),
|
assertEquals(0, violationCount.get(),
|
||||||
"Traffic light coordination violated! Multiple lights were GREEN simultaneously.");
|
"Traffic light coordination violated! Multiple lights were GREEN simultaneously.");
|
||||||
assertTrue(maxGreenSimultaneously.get() <= 1,
|
assertTrue(maxGreenSimultaneously.get() <= 1,
|
||||||
"At most ONE light should be GREEN at any time. Found: " + maxGreenSimultaneously.get());
|
"At most ONE light should be GREEN at any time. Found: " + maxGreenSimultaneously.get());
|
||||||
|
|
||||||
System.out.println("\nTraffic light coordination working correctly!");
|
System.out.println("\nTraffic light coordination working correctly!");
|
||||||
}
|
}
|
||||||
@@ -133,8 +133,8 @@ public class TrafficLightCoordinationTest {
|
|||||||
List<TrafficLight> lights = intersectionProcess.getIntersection().getTrafficLights();
|
List<TrafficLight> lights = intersectionProcess.getIntersection().getTrafficLights();
|
||||||
boolean[] hasBeenGreen = new boolean[lights.size()];
|
boolean[] hasBeenGreen = new boolean[lights.size()];
|
||||||
|
|
||||||
// Monitor for 15 seconds (enough time for all lights to cycle)
|
// Monitor for 60 seconds (enough time for all lights to cycle: 18+18+12 = 48s)
|
||||||
long endTime = System.currentTimeMillis() + 15000;
|
long endTime = System.currentTimeMillis() + 60000;
|
||||||
|
|
||||||
while (System.currentTimeMillis() < endTime) {
|
while (System.currentTimeMillis() < endTime) {
|
||||||
for (int i = 0; i < lights.size(); i++) {
|
for (int i = 0; i < lights.size(); i++) {
|
||||||
@@ -152,7 +152,8 @@ public class TrafficLightCoordinationTest {
|
|||||||
for (int i = 0; i < lights.size(); i++) {
|
for (int i = 0; i < lights.size(); i++) {
|
||||||
String status = hasBeenGreen[i] ? "✓ YES" : "✗ NO";
|
String status = hasBeenGreen[i] ? "✓ YES" : "✗ NO";
|
||||||
System.out.println(lights.get(i).getDirection() + " got GREEN time: " + status);
|
System.out.println(lights.get(i).getDirection() + " got GREEN time: " + status);
|
||||||
if (hasBeenGreen[i]) greenCount++;
|
if (hasBeenGreen[i])
|
||||||
|
greenCount++;
|
||||||
}
|
}
|
||||||
|
|
||||||
assertTrue(greenCount > 0, "At least one light should have been GREEN during the test");
|
assertTrue(greenCount > 0, "At least one light should have been GREEN during the test");
|
||||||
@@ -193,7 +194,7 @@ public class TrafficLightCoordinationTest {
|
|||||||
if (currentState != previousStates[i]) {
|
if (currentState != previousStates[i]) {
|
||||||
transitionCount++;
|
transitionCount++;
|
||||||
System.out.println(lights.get(i).getDirection() + " transitioned: " +
|
System.out.println(lights.get(i).getDirection() + " transitioned: " +
|
||||||
previousStates[i] + " → " + currentState);
|
previousStates[i] + " → " + currentState);
|
||||||
previousStates[i] = currentState;
|
previousStates[i] = currentState;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
1055
main/testing.txt
Normal file
1055
main/testing.txt
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user