mirror of
https://github.com/davidalves04/Trabalho-Pratico-SD.git
synced 2025-12-08 12:33:31 +00:00
Compare commits
78 Commits
v0.2.0
...
ea33d61a9e
| Author | SHA1 | Date | |
|---|---|---|---|
| ea33d61a9e | |||
| 240563419b | |||
| 90db380f61 | |||
| d28a77b6a4 | |||
| 173d9e54ce | |||
| 5202032471 | |||
| 46d148c9d5 | |||
| 0d85d010bf | |||
| 906e958729 | |||
| 19709f0d7a | |||
| 13fa2f877d | |||
| 96c5680f41 | |||
| d74517a27b | |||
| ce7f642246 | |||
| 8f97aab836 | |||
|
|
86c0c4b5b3 | ||
| 6fdcf376b2 | |||
|
|
ecb70fa6a2 | ||
| 06f079ce5b | |||
| 72893f87ae | |||
| 6b94d727e2 | |||
| 84cba39597 | |||
| 5dc1b40c88 | |||
| 3117bdf332 | |||
| 1140c3ca48 | |||
|
|
484cba1eee | ||
|
|
0e5526c3f6 | ||
|
|
cf88db4297 | ||
|
|
0960a7a141 | ||
|
|
3b4f968a59 | ||
| 0c256ad6f5 | |||
| 340e436063 | |||
| 1684a6713e | |||
| 22a7081ade | |||
| 3b699556db | |||
|
|
d078808486 | ||
|
|
98581b562d | ||
|
|
4710c96450 | ||
| f9644bd18c | |||
|
|
c6b710ac52 | ||
|
|
dc4f567e1f | ||
|
|
db5e01021a | ||
|
|
dab0651dbd | ||
|
|
4772add574 | ||
|
|
ae27115791 | ||
|
|
684fb408ef | ||
|
|
d057adeab3 | ||
|
|
be4e7f66d6 | ||
| fd26063f6e | |||
|
|
d8b59cc502 | ||
|
|
06c34a198a | ||
|
|
1524188b29 | ||
|
|
bc1a8da160 | ||
|
|
96903e4b7c | ||
|
|
6c5eab0e72 | ||
| 23f7a74798 | |||
| d7dec0d73e | |||
|
|
534a880e3e | ||
|
|
ba3233eae1 | ||
|
|
d20040835c | ||
|
|
2399b4b472 | ||
|
|
974debf7db | ||
| 8e95bc4c01 | |||
| 33ed84b0c2 | |||
| 9093b13c5d | |||
| 12b7aabe87 | |||
| c30aa25de0 | |||
| 3689f7a207 | |||
| bb18c1119e | |||
| f0dbdb551d | |||
| f519c9aba7 | |||
| 1216089e80 | |||
| 211ea25ca5 | |||
|
|
3fe467a2a3 | ||
|
|
af9b091e76 | ||
|
|
fc46b9b83b | ||
|
|
a7c17ca9b9 | ||
|
|
1c033880e7 |
104
.github/workflows/maven.yml
vendored
Normal file
104
.github/workflows/maven.yml
vendored
Normal file
@@ -0,0 +1,104 @@
|
||||
name: Java CI with Maven
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [ "dev", "cleanup" ]
|
||||
tags:
|
||||
- 'v*.*.*'
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
cache: maven
|
||||
- name: Build with Maven
|
||||
run: mvn -B package
|
||||
working-directory: main
|
||||
- name: Upload built JAR
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: package
|
||||
path: main/target/*.jar
|
||||
- name: Generate dependency graph
|
||||
run: mvn -B -f main/pom.xml com.github.ferstl:depgraph-maven-plugin:4.0.1:graph
|
||||
- name: Upload dependency graph artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dependency-graph
|
||||
path: main/target/**
|
||||
|
||||
build-windows:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
cache: maven
|
||||
- name: Build with Maven (Skip Tests)
|
||||
run: mvn -B package -DskipTests
|
||||
working-directory: main
|
||||
- name: Create JPackage App Image
|
||||
shell: pwsh
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force -Path "dist"
|
||||
jpackage --name "DTSS" `
|
||||
--input main/target `
|
||||
--main-jar main-1.0-SNAPSHOT.jar `
|
||||
--dest dist `
|
||||
--type app-image `
|
||||
--win-console
|
||||
- name: Inject java.exe
|
||||
shell: pwsh
|
||||
run: |
|
||||
$javaPath = (Get-Command java).Source
|
||||
Copy-Item -Path $javaPath -Destination "dist/DTSS/runtime/bin/"
|
||||
- name: Zip Windows Release
|
||||
shell: pwsh
|
||||
run: |
|
||||
Compress-Archive -Path "dist/DTSS" -DestinationPath "dist/DTSS-Windows.zip"
|
||||
- name: Upload Windows Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-package
|
||||
path: dist/DTSS-Windows.zip
|
||||
|
||||
publish-release:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build, build-windows]
|
||||
if: startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch'
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Download Linux JAR
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: package
|
||||
path: main/target/
|
||||
- name: Download Windows Zip
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-package
|
||||
path: windows-dist/
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || 'snapshot-build' }}
|
||||
name: ${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || 'Manual Snapshot Build' }}
|
||||
draft: false
|
||||
prerelease: true
|
||||
make_latest: false
|
||||
files: |
|
||||
main/target/*.jar
|
||||
windows-dist/*.zip
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -3,6 +3,9 @@
|
||||
|
||||
# Log files
|
||||
*.log
|
||||
*.trace
|
||||
logs
|
||||
*.md
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
@@ -48,3 +51,6 @@ build/
|
||||
# Other
|
||||
*.swp
|
||||
*.pdf
|
||||
|
||||
# JAR built pom file
|
||||
dependency-reduced-pom.xml
|
||||
175
TODO.md
175
TODO.md
@@ -1,175 +0,0 @@
|
||||
### Compreender os Conceitos Fundamentais
|
||||
|
||||
Primeiro, as tecnologias e paradigmas chave necessários para este projeto devem ser totalmente compreendidos.
|
||||
|
||||
- **Processos vs. Threads:** O projeto especifica o uso de ambos.
|
||||
|
||||
- **Processos (para Cruzamentos)** são programas independentes, cada um com o seu próprio espaço de memória. Em Java, cada cruzamento será provavelmente executado como uma aplicação Java separada (uma instância distinta da JVM).
|
||||
|
||||
- **Threads (para Semáforos)** existem _dentro_ de um processo e partilham memória. Isto é adequado para os semáforos, pois eles precisam de ser coordenados e partilhar dados (como filas de veículos) dentro do mesmo cruzamento.
|
||||
|
||||
- **Comunicação Entre Processos (IPC - Inter-Process Communication):** Como os cruzamentos são processos separados, é necessário um método para que eles comuniquem. **Sockets** são o método especificado. Quando um veículo sai de um cruzamento (ex: `Cr1`) e vai para outro (ex: `Cr2`), o processo `Cr1` precisa de enviar uma mensagem contendo os dados do veículo para o processo `Cr2` através de uma conexão por socket.
|
||||
|
||||
- **Simulação de Eventos Discretos (DES - Discrete-Event Simulation):** Este é o paradigma de simulação que deve ser utilizado. Em vez de o tempo fluir continuamente, o relógio da simulação salta de um evento para o seguinte.
|
||||
|
||||
- Um **evento** é um objeto que representa algo que acontece num ponto específico no tempo (ex: "Veículo A chega ao Cr2 no tempo 15.7s").
|
||||
|
||||
- Uma **lista de eventos** central, frequentemente uma fila de prioridades, será necessária para armazenar eventos futuros, ordenados pelo seu timestamp. O ciclo principal da simulação retira o próximo evento da lista, processa-o e adiciona quaisquer novos eventos que resultem dele.
|
||||
|
||||
- **Processo de Poisson:** Para o modelo "mais realista" de chegadas de veículos, é especificado um processo de Poisson. A principal conclusão é que o tempo _entre_ chegadas consecutivas de veículos segue uma **distribuição exponencial**. Em Java, este intervalo pode ser gerado usando `Math.log(1 - Math.random()) / -lambda`, onde `lambda` (λi) é a taxa de chegada especificada.
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Uma Sugestão de Arquitetura de Alto Nível
|
||||
|
||||
Abaixo, é apresentada uma possível estrutura para a aplicação distribuída. Pode ser vista como um conjunto de programas independentes que comunicam através de uma rede.
|
||||
|
||||
1. **Processo Coordenador/Gerador (1 Processo):**
|
||||
|
||||
- **Propósito:** Iniciar a simulação, gerar veículos e gerir o relógio global da simulação ou os critérios de paragem.
|
||||
|
||||
- **Responsabilidades:**
|
||||
|
||||
- Lê a configuração da simulação (ex: carga de tráfego λi, tempos dos semáforos).
|
||||
|
||||
- Gera veículos de acordo com o modelo selecionado (intervalo fixo ou processo de Poisson).
|
||||
|
||||
- Atribui a cada novo veículo um percurso com base na distribuição uniforme especificada.
|
||||
|
||||
- Injeta o veículo no sistema enviando uma mensagem para o primeiro processo de cruzamento no seu percurso (ex: de um ponto de entrada E1 para Cr1).
|
||||
|
||||
2. **Processos de Cruzamento (5 Processos):**
|
||||
|
||||
- **Propósito:** Simular cada cruzamento (`Cr1` a `Cr5`) como um processo distinto.
|
||||
|
||||
- **Responsabilidades:**
|
||||
|
||||
- Escuta por veículos a chegar de outros processos.
|
||||
|
||||
- Gere as filas de veículos para os seus semáforos.
|
||||
|
||||
- Executa múltiplas **threads de Semáforo** internamente.
|
||||
|
||||
- Coordena estas threads para garantir que apenas uma direção de tráfego está aberta a cada momento.
|
||||
|
||||
- Quando um veículo atravessa, é encaminhado para o processo seguinte no seu percurso.
|
||||
|
||||
- Envia periodicamente as suas estatísticas (ex: comprimentos atuais das filas) para o Servidor do Dashboard.
|
||||
|
||||
3. **Processo de Nó de Saída (1 Processo):**
|
||||
|
||||
- **Propósito:** Representar o ponto de saída `S` e atuar como um coletor de dados para estatísticas globais.
|
||||
|
||||
- **Responsabilidades:**
|
||||
|
||||
- Recebe veículos que completaram o seu percurso.
|
||||
|
||||
- Calcula métricas globais como o tempo total de viagem (tempo de permanência) para cada veículo.
|
||||
|
||||
- Agrega e calcula as estatísticas finais (ex: tempo de viagem mínimo, máximo e médio por tipo de veículo).
|
||||
|
||||
- Envia estas estatísticas globais para o Servidor do Dashboard.
|
||||
|
||||
4. **Processo do Servidor do Dashboard (1 Processo):**
|
||||
|
||||
- **Propósito:** Agregar e exibir todos os dados da simulação em tempo real.
|
||||
|
||||
- **Responsabilidades:**
|
||||
|
||||
- Abre um socket de servidor e escuta por dados a chegar de todos os processos de Cruzamento e de Saída.
|
||||
|
||||
- Armazena e atualiza as estatísticas à medida que chegam.
|
||||
|
||||
- Apresenta os dados numa interface de utilizador, que deve exibir métricas e ser atualizada durante a simulação.
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Plano
|
||||
|
||||
Nem tudo deve ser construído de uma só vez. Os seguintes passos incrementais são recomendados.
|
||||
|
||||
#### **Passo 1: Modelação e Classes Principais (Não-distribuído)**
|
||||
|
||||
Antes de escrever qualquer lógica complexa, as estruturas de dados devem ser definidas. Devem ser criados Plain Old Java Objects (POJOs) para:
|
||||
|
||||
- `Veiculo`: Com atributos como um identificador único, tipo, tempo de entrada e o percurso realizado. Deve ser tornado `Serializable` para que possa ser enviado através de sockets.
|
||||
|
||||
- `Evento`: Com atributos como um timestamp e o tipo de evento (ex: `VEHICLE_ARRIVAL`), bem como dados associados.
|
||||
|
||||
- `Semaforo`: Para conter o seu estado (`VERDE`/`VERMELHO`) e a fila de veículos.
|
||||
|
||||
- `Cruzamento`: Para conter os seus semáforos e a lógica operacional.
|
||||
|
||||
|
||||
#### **Passo 2: Construir um Protótipo de Processo Único**
|
||||
|
||||
Este é um passo crucial. Sockets e processos devem ser deixados de lado por agora para construir toda a simulação numa única aplicação Java.
|
||||
|
||||
- Deve ser criado um ciclo de simulação central baseado numa fila de prioridades para objetos `Evento`.
|
||||
|
||||
- Todos os objetos `Cruzamento` e `Semaforo` devem ser instanciados.
|
||||
|
||||
- A lógica principal deve ser tornada funcional: veículos a moverem-se entre filas, semáforos a mudar de estado e estatísticas básicas a serem recolhidas.
|
||||
|
||||
- **Objetivo:** Uma simulação totalmente funcional e não-distribuída. Isto torna a depuração significativamente mais fácil.
|
||||
|
||||
|
||||
#### **Passo 3: Distribuir os Cruzamentos**
|
||||
|
||||
O protótipo pode agora ser convertido num sistema distribuído.
|
||||
|
||||
- A classe `Cruzamento` deve ser tornada executável como uma aplicação Java autónoma (com um método `main`). Serão lançadas cinco instâncias, uma para cada cruzamento.
|
||||
|
||||
- Devem ser configurados sockets TCP para comunicação. Cada processo de cruzamento precisa de saber o endereço/porta dos vizinhos para os quais pode enviar veículos.
|
||||
|
||||
- Um **protocolo de comunicação** claro deve ser definido. Por exemplo, quando `Cr1` envia um veículo para `Cr2`, o objeto `Veiculo` é serializado e escrito no socket conectado a `Cr2`. O processo `Cr2` terá uma thread dedicada para escutar estas conexões de entrada.
|
||||
|
||||
|
||||
#### **Passo 4: Implementar as Threads dos Semáforos**
|
||||
|
||||
Dentro de cada processo `Cruzamento`, os semáforos devem ser implementados como threads.
|
||||
|
||||
- O principal desafio aqui é a **sincronização**. As threads dos semáforos num único cruzamento partilham as filas de veículos.
|
||||
|
||||
- As ferramentas de concorrência do Java (como `synchronized`, `ReentrantLock`, `Semaphore`) devem ser usadas para garantir que apenas um semáforo pode estar verde para um percurso conflituante e que o acesso às filas partilhadas é seguro (thread-safe).
|
||||
|
||||
|
||||
#### **Passo 5: Implementar o Dashboard**
|
||||
|
||||
- O processo `DashboardServer` deve ser criado. Ele irá escutar numa porta específica por estatísticas a chegar.
|
||||
|
||||
- Nos processos `Cruzamento` e `Saida`, deve ser adicionado um mecanismo para enviar periodicamente um resumo das suas estatísticas atuais para o Servidor do Dashboard.
|
||||
|
||||
- A UI deve ser construída para exibir estes dados em tempo real.
|
||||
|
||||
|
||||
#### **Passo 6: Testes e Análise**
|
||||
|
||||
Assim que o sistema completo estiver a funcionar, as experiências exigidas pela descrição do projeto podem ser realizadas.
|
||||
|
||||
- A simulação deve ser executada com diferentes taxas de chegada de veículos para simular cargas baixas, médias e altas.
|
||||
|
||||
- Diferentes políticas de temporização dos semáforos devem ser testadas para medir o seu impacto no congestionamento.
|
||||
|
||||
- Diferentes algoritmos de seleção de percurso e o seu impacto no desempenho do sistema devem ser avaliados.
|
||||
|
||||
- Para cada cenário, a simulação deve ser executada várias vezes para recolher estatísticas fiáveis (médias, desvios padrão, intervalos de confiança), conforme solicitado.
|
||||
|
||||
|
||||
#### **Passo 7: Escrever o Relatório**
|
||||
|
||||
À medida que cada passo é concluído, deve ser documentado. Isto tornará a escrita do relatório final muito mais fácil. Todos os pontos mencionados nas secções "Entrega" e "Critérios de Avaliação" devem ser abordados.
|
||||
|
||||
---
|
||||
|
||||
### OBS:
|
||||
|
||||
- **Começar de Forma Simples:** O protótipo de processo único (Passo 2) evitará grandes dificuldades mais tarde.
|
||||
|
||||
- **Protocolo de Comunicação:** O protocolo de mensagens deve ser definido o mais cedo possível. A informação exata que um processo envia para outro deve ser clara//simples//consistente.
|
||||
|
||||
- **Debugging:** Debugging de sistemas distribuídos podem ser difíceis. Uma framework de logging (como Log4j 2 ou SLF4J) pode ser usada para registar eventos//alterações de estado nos diferentes processos.
|
||||
|
||||
- **Configuração:** Valores como endereços IP, números de porta ou parâmetros da simulação não devem ser "hardcoded". Um ficheiro de configuração (ex: um ficheiro `.properties` ou `.json`) torna a aplicação mais fácil de executar e testar.
|
||||
73
main/pom.xml
73
main/pom.xml
@@ -11,6 +11,79 @@
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- JUnit 5 for testing -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.10.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Gson for JSON serialization -->
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.10.1</version>
|
||||
</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>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<!-- Maven Exec Plugin for running examples -->
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<configuration>
|
||||
<mainClass>sd.dashboard.Launcher</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!-- JavaFX Maven Plugin -->
|
||||
<plugin>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-maven-plugin</artifactId>
|
||||
<version>0.0.8</version>
|
||||
<configuration>
|
||||
<mainClass>sd.dashboard.Launcher</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.5.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>sd.dashboard.Launcher</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -1,7 +0,0 @@
|
||||
package sd;
|
||||
|
||||
public class Entry {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Hello, World!");
|
||||
}
|
||||
}
|
||||
557
main/src/main/java/sd/ExitNodeProcess.java
Normal file
557
main/src/main/java/sd/ExitNodeProcess.java
Normal file
@@ -0,0 +1,557 @@
|
||||
package sd;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import sd.config.SimulationConfig;
|
||||
import sd.coordinator.SocketClient;
|
||||
import sd.dashboard.StatsUpdatePayload;
|
||||
import sd.des.DESEventType;
|
||||
import sd.des.EventQueue;
|
||||
import sd.des.SimulationClock;
|
||||
import sd.des.SimulationEvent;
|
||||
import sd.logging.EventLogger;
|
||||
import sd.logging.EventType;
|
||||
import sd.logging.VehicleTracer;
|
||||
import sd.model.Message;
|
||||
import sd.model.MessageType;
|
||||
import sd.model.Vehicle;
|
||||
import sd.model.VehicleType;
|
||||
import sd.protocol.MessageProtocol;
|
||||
import sd.protocol.SocketConnection;
|
||||
|
||||
/**
|
||||
* Destino final de todos os veículos da simulação (nó de saída S).
|
||||
*
|
||||
* <p>Opera como sumidouro da rede:
|
||||
* <ol>
|
||||
* <li>Recebe veículos que completaram a viagem
|
||||
* <li>Regista estatísticas finais (tempo total, espera, travessia)
|
||||
* <li>Envia métricas ao dashboard em tempo real
|
||||
* </ol>
|
||||
*
|
||||
* <p>Participa no DES rastreando eventos, mas opera principalmente
|
||||
* de forma reativa, aguardando chegadas via socket.
|
||||
*/
|
||||
public class ExitNodeProcess {
|
||||
|
||||
private final SimulationConfig config;
|
||||
private ServerSocket serverSocket;
|
||||
private final ExecutorService connectionHandlerPool;
|
||||
|
||||
// DES components
|
||||
private final SimulationClock clock;
|
||||
private final EventQueue eventQueue;
|
||||
private final EventLogger eventLogger;
|
||||
private Thread eventProcessorThread;
|
||||
|
||||
/** Flag de controlo (volatile para visibilidade entre threads) */
|
||||
private volatile boolean running;
|
||||
|
||||
/** Instante de início da simulação (milissegundos) */
|
||||
private long simulationStartMillis;
|
||||
|
||||
/** Contador de veículos que completaram a rota */
|
||||
private int totalVehiclesReceived;
|
||||
|
||||
/** Tempo acumulado no sistema de todos os veículos */
|
||||
private double totalSystemTime;
|
||||
|
||||
/** Tempo acumulado em espera de todos os veículos */
|
||||
private double totalWaitingTime;
|
||||
|
||||
/** Tempo acumulado em travessia de todos os veículos */
|
||||
private double totalCrossingTime;
|
||||
|
||||
/** Contagem de veículos por tipo */
|
||||
private final Map<VehicleType, Integer> vehicleTypeCount;
|
||||
|
||||
/** Tempo de espera acumulado por tipo de veículo */
|
||||
private final Map<VehicleType, Double> vehicleTypeWaitTime;
|
||||
|
||||
/** Cliente socket para envio de estatísticas ao dashboard */
|
||||
private SocketClient dashboardClient;
|
||||
|
||||
/**
|
||||
* Ponto de entrada do processo.
|
||||
*
|
||||
* @param args args[0] (opcional) = caminho do ficheiro de configuração
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
System.out.println("=".repeat(60));
|
||||
System.out.println("EXIT NODE PROCESS");
|
||||
System.out.println("=".repeat(60));
|
||||
|
||||
try {
|
||||
EventLogger.getInstance().log(EventType.PROCESS_STARTED, "ExitNode", "Exit node process started");
|
||||
|
||||
String configFile = args.length > 0 ? args[0] : "src/main/resources/simulation.properties";
|
||||
System.out.println("Loading configuration from: " + configFile);
|
||||
|
||||
SimulationConfig config = new SimulationConfig(configFile);
|
||||
ExitNodeProcess exitNode = new ExitNodeProcess(config);
|
||||
|
||||
System.out.println("\n" + "=".repeat(60));
|
||||
exitNode.initialize();
|
||||
|
||||
System.out.println("\n" + "=".repeat(60));
|
||||
exitNode.start();
|
||||
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to start exit node: " + e.getMessage());
|
||||
EventLogger.getInstance().logError("ExitNode", "Failed to start", e);
|
||||
System.exit(1);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Exit node error: " + e.getMessage());
|
||||
EventLogger.getInstance().logError("ExitNode", "Exit node error", e);
|
||||
System.exit(1);
|
||||
} finally {
|
||||
EventLogger.getInstance().log(EventType.PROCESS_STOPPED, "ExitNode", "Exit node process stopped");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Configura o Nó de Saída.
|
||||
*
|
||||
* Inicializamos os nossos contadores, preparamos a pool de threads para tratar
|
||||
* das ligações de veículos recebidas,
|
||||
* e configuramos os componentes DES para rastreio de eventos.
|
||||
*
|
||||
* @param config A configuração da simulação.
|
||||
*/
|
||||
public ExitNodeProcess(SimulationConfig config) {
|
||||
this.config = config;
|
||||
this.connectionHandlerPool = Executors.newCachedThreadPool();
|
||||
this.running = false;
|
||||
|
||||
this.totalVehiclesReceived = 0;
|
||||
this.totalSystemTime = 0.0;
|
||||
this.totalWaitingTime = 0.0;
|
||||
this.totalCrossingTime = 0.0;
|
||||
this.vehicleTypeCount = new HashMap<>();
|
||||
this.vehicleTypeWaitTime = new HashMap<>();
|
||||
|
||||
// Inicializa os counters para cada tipo de veículo
|
||||
for (VehicleType type : VehicleType.values()) {
|
||||
vehicleTypeCount.put(type, 0);
|
||||
vehicleTypeWaitTime.put(type, 0.0);
|
||||
}
|
||||
|
||||
// Initialize DES components
|
||||
this.clock = new SimulationClock();
|
||||
this.eventQueue = new EventQueue(true); // Track history
|
||||
this.eventLogger = EventLogger.getInstance();
|
||||
|
||||
eventLogger.log(EventType.PROCESS_STARTED, "ExitNode",
|
||||
"Exit node initialized with DES architecture");
|
||||
|
||||
System.out.println("Exit node initialized (DES Mode)");
|
||||
System.out.println(" - Exit port: " + config.getExitPort());
|
||||
System.out.println(" - Dashboard: " + config.getDashboardHost() + ":" + config.getDashboardPort());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tenta estabelecer uma ligação ao dashboard.
|
||||
* Se for bem-sucedido, poderemos enviar estatísticas em tempo real. Se não,
|
||||
* apenas registamos localmente.
|
||||
*/
|
||||
public void initialize() {
|
||||
System.out.println("Connecting to dashboard...");
|
||||
|
||||
try {
|
||||
String host = config.getDashboardHost();
|
||||
int port = config.getDashboardPort();
|
||||
|
||||
dashboardClient = new SocketClient("Dashboard", host, port);
|
||||
dashboardClient.connect();
|
||||
|
||||
System.out.println("Successfully connected to dashboard");
|
||||
} catch (IOException e) {
|
||||
System.err.println("WARNING: Failed to connect to dashboard: " + e.getMessage());
|
||||
System.err.println("Exit node will continue without dashboard connection");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the DES event processing thread.
|
||||
* Currently, ExitNode is primarily reactive (receives vehicles via network),
|
||||
* but maintains event queue for potential scheduled events and history
|
||||
* tracking.
|
||||
*/
|
||||
private void startEventProcessor() {
|
||||
eventProcessorThread = new Thread(() -> {
|
||||
eventLogger.log(EventType.SIMULATION_STARTED, "ExitNode",
|
||||
"Event processor thread started");
|
||||
|
||||
// Keep running while process is active
|
||||
while (running) {
|
||||
SimulationEvent event = eventQueue.poll();
|
||||
if (event == null) {
|
||||
// No events currently, wait before checking again
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Advance clock to event time
|
||||
clock.advanceTo(event.getTimestamp());
|
||||
|
||||
// Process the event
|
||||
processEvent(event);
|
||||
}
|
||||
|
||||
eventLogger.log(EventType.SIMULATION_STOPPED, "ExitNode",
|
||||
String.format("Event processor thread terminated at time %.2f", clock.getCurrentTime()));
|
||||
}, "EventProcessor-ExitNode");
|
||||
|
||||
eventProcessorThread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a discrete event based on its type.
|
||||
* Currently supports VEHICLE_EXIT and SIMULATION_END events.
|
||||
*/
|
||||
private void processEvent(SimulationEvent event) {
|
||||
try {
|
||||
switch (event.getType()) {
|
||||
case VEHICLE_EXIT:
|
||||
// Vehicle exits are handled via network messages in real-time
|
||||
// This event type can be used for scheduled vehicle processing
|
||||
break;
|
||||
|
||||
case SIMULATION_END:
|
||||
handleSimulationEndEvent(event);
|
||||
break;
|
||||
|
||||
default:
|
||||
System.err.println("[ExitNode] Unknown event type: " + event.getType());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("[ExitNode] Error processing event " + event.getType() +
|
||||
" at time " + event.getTimestamp() + ": " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles simulation end event.
|
||||
*/
|
||||
private void handleSimulationEndEvent(SimulationEvent event) {
|
||||
eventLogger.log(EventType.SIMULATION_STOPPED, "ExitNode",
|
||||
String.format("Simulation ended at time %.2f", event.getTimestamp()));
|
||||
running = false;
|
||||
|
||||
// Print final statistics
|
||||
printFinalStatistics();
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports the complete event history for the exit node.
|
||||
* This satisfies the spec requirement: "Deve ser possível verificar a lista
|
||||
* completa de eventos"
|
||||
*/
|
||||
public void exportEventHistory(String outputPath) {
|
||||
String history = eventQueue.exportEventHistory();
|
||||
try (java.io.PrintWriter writer = new java.io.PrintWriter(outputPath)) {
|
||||
writer.println(history);
|
||||
System.out.println("[ExitNode] Event history exported to: " + outputPath);
|
||||
} catch (java.io.FileNotFoundException e) {
|
||||
System.err.println("[ExitNode] Failed to export event history: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a simulation end event at the specified time.
|
||||
*
|
||||
* @param endTime The simulation time when the simulation should end
|
||||
*/
|
||||
public void scheduleSimulationEnd(double endTime) {
|
||||
SimulationEvent endEvent = new SimulationEvent(
|
||||
endTime,
|
||||
DESEventType.SIMULATION_END,
|
||||
null);
|
||||
eventQueue.schedule(endEvent);
|
||||
System.out.println("[ExitNode] Simulation end scheduled at time " + endTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Abre o socket do servidor e começa a escutar por veículos.
|
||||
*
|
||||
* Este é o loop principal. Aceitamos ligações das interseções (de onde vêm os
|
||||
* veículos)
|
||||
* e passamo-las para a nossa pool de threads para processamento.
|
||||
*
|
||||
* @throws IOException Se não conseguirmos fazer bind à porta.
|
||||
*/
|
||||
public void start() throws IOException {
|
||||
start(true); // Default to DES mode
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the exit node process.
|
||||
*
|
||||
* @param useDES If true, starts event processor for DES mode tracking
|
||||
*/
|
||||
public void start(boolean useDES) throws IOException {
|
||||
int port = config.getExitPort();
|
||||
serverSocket = new ServerSocket(port);
|
||||
running = true;
|
||||
simulationStartMillis = System.currentTimeMillis();
|
||||
|
||||
System.out.println("Exit node started on port " + port);
|
||||
if (useDES) {
|
||||
// Note: ExitNode is primarily reactive (network-driven), but maintains
|
||||
// event queue for simulation end events and history tracking
|
||||
System.out.println("Running in DES mode (event history tracking enabled)");
|
||||
}
|
||||
System.out.println("Waiting for vehicles...\\n");
|
||||
|
||||
while (running) {
|
||||
try {
|
||||
Socket clientSocket = serverSocket.accept();
|
||||
connectionHandlerPool.submit(() -> handleIncomingConnection(clientSocket));
|
||||
} catch (IOException e) {
|
||||
if (running) {
|
||||
System.err.println("Error accepting connection: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Trata uma ligação de uma interseção.
|
||||
*
|
||||
* Mantemos a ligação aberta e escutamos por mensagens `VEHICLE_TRANSFER`.
|
||||
* Cada mensagem contém um veículo que acabou de terminar a sua viagem.
|
||||
*
|
||||
* @param clientSocket O socket ligado à interseção.
|
||||
*/
|
||||
private void handleIncomingConnection(Socket clientSocket) {
|
||||
String clientAddress = clientSocket.getInetAddress().getHostAddress();
|
||||
System.out.println("New connection accepted from " + clientAddress);
|
||||
|
||||
try (SocketConnection connection = new SocketConnection(clientSocket)) {
|
||||
|
||||
while (running && connection.isConnected()) {
|
||||
try {
|
||||
System.out.println("[Exit] Waiting for message from " + clientAddress);
|
||||
MessageProtocol message = connection.receiveMessage();
|
||||
System.out.println("[Exit] Received message type: " + message.getType() +
|
||||
" from " + message.getSourceNode());
|
||||
|
||||
if (message.getType() == MessageType.SIMULATION_START) {
|
||||
// Coordinator sends start time - use it instead of our local start
|
||||
simulationStartMillis = ((Number) message.getPayload()).longValue();
|
||||
System.out.println("[Exit] Simulation start time synchronized");
|
||||
} else if (message.getType() == MessageType.VEHICLE_TRANSFER) {
|
||||
Object payload = message.getPayload();
|
||||
System.out.println("[Exit] Payload type: " + payload.getClass().getName());
|
||||
|
||||
// Handle Gson LinkedHashMap
|
||||
Vehicle vehicle;
|
||||
if (payload instanceof com.google.gson.internal.LinkedTreeMap ||
|
||||
payload instanceof java.util.LinkedHashMap) {
|
||||
String json = new com.google.gson.Gson().toJson(payload);
|
||||
vehicle = new com.google.gson.Gson().fromJson(json, Vehicle.class);
|
||||
} else {
|
||||
vehicle = (Vehicle) payload;
|
||||
}
|
||||
|
||||
processExitingVehicle(vehicle);
|
||||
}
|
||||
|
||||
} catch (ClassNotFoundException e) {
|
||||
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) {
|
||||
if (running) {
|
||||
System.err.println("[Exit] Connection error from " + clientAddress + ": " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processa um veículo que acabou de sair do sistema.
|
||||
*
|
||||
* Calculamos quanto tempo demorou, atualizamos as nossas estatísticas globais e
|
||||
* notificamos o dashboard.
|
||||
* Este método é sincronizado porque múltiplos veículos podem chegar ao mesmo
|
||||
* tempo.
|
||||
*
|
||||
* @param vehicle O veículo que completou a sua rota.
|
||||
*/
|
||||
private synchronized void processExitingVehicle(Vehicle vehicle) {
|
||||
totalVehiclesReceived++;
|
||||
|
||||
// Use simulation time instead of wall-clock time
|
||||
// System time = total time vehicle spent in system (wait + crossing times)
|
||||
// This represents the actual simulation time elapsed, not real-time
|
||||
double waitTime = vehicle.getTotalWaitingTime();
|
||||
double crossingTime = vehicle.getTotalCrossingTime();
|
||||
double systemTime = waitTime + crossingTime;
|
||||
|
||||
// Store times in seconds, will be converted to ms when sending to dashboard
|
||||
totalSystemTime += systemTime;
|
||||
totalWaitingTime += waitTime;
|
||||
totalCrossingTime += crossingTime;
|
||||
|
||||
VehicleType type = vehicle.getType();
|
||||
vehicleTypeCount.put(type, vehicleTypeCount.get(type) + 1);
|
||||
vehicleTypeWaitTime.put(type, vehicleTypeWaitTime.get(type) + waitTime);
|
||||
|
||||
System.out.printf("[Exit] Vehicle %s completed (type=%s, system_time=%.2fs, wait=%.2fs, crossing=%.2fs)%n",
|
||||
vehicle.getId(), vehicle.getType(), systemTime, waitTime, crossingTime);
|
||||
|
||||
// Log vehicle exit
|
||||
EventLogger.getInstance().logVehicle(EventType.VEHICLE_EXITED, "ExitNode", vehicle.getId(),
|
||||
String.format("Completed - System: %.2fs, Wait: %.2fs, Crossing: %.2fs", systemTime, waitTime,
|
||||
crossingTime));
|
||||
|
||||
// Complete vehicle trace if tracking
|
||||
VehicleTracer.getInstance().logExit(vehicle, systemTime);
|
||||
|
||||
// Send stats after every vehicle to ensure dashboard updates quickly
|
||||
sendStatsToDashboard();
|
||||
}
|
||||
|
||||
/**
|
||||
* Envia as estatísticas mais recentes para o dashboard.
|
||||
*
|
||||
* Empacotamos as contagens totais e os tempos médios num `StatsUpdatePayload`
|
||||
* e enviamo-lo.
|
||||
*/
|
||||
private void sendStatsToDashboard() {
|
||||
if (dashboardClient == null || !dashboardClient.isConnected()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Create stats payload
|
||||
StatsUpdatePayload payload = new StatsUpdatePayload();
|
||||
|
||||
// Set global stats - convert seconds to milliseconds
|
||||
payload.setTotalVehiclesCompleted(totalVehiclesReceived);
|
||||
payload.setTotalSystemTime((long) (totalSystemTime * 1000.0)); // s -> ms
|
||||
payload.setTotalWaitingTime((long) (totalWaitingTime * 1000.0)); // s -> ms
|
||||
|
||||
// Set intersection-like stats so it shows up correctly in the dashboard table
|
||||
payload.setIntersectionArrivals(totalVehiclesReceived);
|
||||
payload.setIntersectionDepartures(totalVehiclesReceived);
|
||||
payload.setIntersectionQueueSize(0);
|
||||
|
||||
// Set vehicle type stats
|
||||
Map<VehicleType, Integer> typeCounts = new HashMap<>();
|
||||
Map<VehicleType, Long> typeWaitTimes = new HashMap<>();
|
||||
|
||||
for (VehicleType type : VehicleType.values()) {
|
||||
typeCounts.put(type, vehicleTypeCount.get(type));
|
||||
typeWaitTimes.put(type, (long) (vehicleTypeWaitTime.get(type) * 1000.0)); // s -> ms
|
||||
}
|
||||
|
||||
payload.setVehicleTypeCounts(typeCounts);
|
||||
payload.setVehicleTypeWaitTimes(typeWaitTimes);
|
||||
|
||||
// Send message
|
||||
Message message = new Message(
|
||||
MessageType.STATS_UPDATE,
|
||||
"ExitNode",
|
||||
"Dashboard",
|
||||
payload);
|
||||
|
||||
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",
|
||||
totalVehiclesReceived, avgWait);
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("[Exit] Failed to send stats to dashboard: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encerra graciosamente o processo.
|
||||
*
|
||||
* Imprimimos as estatísticas finais, fechamos ligações e limpamos threads.
|
||||
*/
|
||||
public void shutdown() {
|
||||
System.out.println("\n[Exit] Shutting down...");
|
||||
running = false;
|
||||
|
||||
printFinalStatistics();
|
||||
|
||||
sendStatsToDashboard();
|
||||
|
||||
try {
|
||||
if (serverSocket != null && !serverSocket.isClosed()) {
|
||||
serverSocket.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("Error closing server socket: " + e.getMessage());
|
||||
}
|
||||
|
||||
connectionHandlerPool.shutdown();
|
||||
try {
|
||||
if (!connectionHandlerPool.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
connectionHandlerPool.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
connectionHandlerPool.shutdownNow();
|
||||
}
|
||||
|
||||
if (dashboardClient != null) {
|
||||
dashboardClient.close();
|
||||
}
|
||||
|
||||
System.out.println("[Exit] Shutdown complete.");
|
||||
System.out.println("=".repeat(60));
|
||||
}
|
||||
|
||||
/**
|
||||
* Imprime um resumo dos resultados da simulação na consola.
|
||||
* Isto dá-nos uma visão rápida de como a simulação correu (médias, contagens de
|
||||
* veículos, etc.).
|
||||
*/
|
||||
private void printFinalStatistics() {
|
||||
System.out.println("\n=== EXIT NODE STATISTICS ===");
|
||||
System.out.printf("Total Vehicles Completed: %d%n", totalVehiclesReceived);
|
||||
|
||||
if (totalVehiclesReceived > 0) {
|
||||
System.out.printf("%nAVERAGE METRICS:%n");
|
||||
System.out.printf(" System Time: %.2f seconds%n", totalSystemTime / totalVehiclesReceived);
|
||||
System.out.printf(" Waiting Time: %.2f seconds%n", totalWaitingTime / totalVehiclesReceived);
|
||||
System.out.printf(" Crossing Time: %.2f seconds%n", totalCrossingTime / totalVehiclesReceived);
|
||||
}
|
||||
|
||||
System.out.println("\nVEHICLE TYPE DISTRIBUTION:");
|
||||
for (VehicleType type : VehicleType.values()) {
|
||||
int count = vehicleTypeCount.get(type);
|
||||
if (count > 0) {
|
||||
double percentage = (count * 100.0) / totalVehiclesReceived;
|
||||
double avgWait = vehicleTypeWaitTime.get(type) / count;
|
||||
System.out.printf(" %s: %d (%.1f%%), Avg Wait: %.2fs%n",
|
||||
type, count, percentage, avgWait);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
1025
main/src/main/java/sd/IntersectionProcess.java
Normal file
1025
main/src/main/java/sd/IntersectionProcess.java
Normal file
File diff suppressed because it is too large
Load Diff
223
main/src/main/java/sd/analysis/MultiRunAnalyzer.java
Normal file
223
main/src/main/java/sd/analysis/MultiRunAnalyzer.java
Normal file
@@ -0,0 +1,223 @@
|
||||
package sd.analysis;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
import sd.model.VehicleType;
|
||||
|
||||
/**
|
||||
* Executes multiple simulation runs and aggregates results.
|
||||
* Calculates statistical measures including mean, standard deviation,
|
||||
* and confidence intervals across all runs.
|
||||
*/
|
||||
public class MultiRunAnalyzer {
|
||||
|
||||
private final List<SimulationRunResult> results;
|
||||
private final String configurationFile;
|
||||
|
||||
public MultiRunAnalyzer(String configurationFile) {
|
||||
this.configurationFile = configurationFile;
|
||||
this.results = new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a completed simulation run result.
|
||||
*/
|
||||
public void addResult(SimulationRunResult result) {
|
||||
results.add(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the number of completed runs.
|
||||
*/
|
||||
public int getRunCount() {
|
||||
return results.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a comprehensive statistical report.
|
||||
*/
|
||||
public String generateReport() {
|
||||
if (results.isEmpty()) {
|
||||
return "No simulation results to analyze.";
|
||||
}
|
||||
|
||||
StringBuilder report = new StringBuilder();
|
||||
|
||||
// Header
|
||||
report.append("=".repeat(80)).append("\n");
|
||||
report.append("MULTI-RUN STATISTICAL ANALYSIS\n");
|
||||
report.append("=".repeat(80)).append("\n");
|
||||
report.append("Configuration: ").append(configurationFile).append("\n");
|
||||
report.append("Number of Runs: ").append(results.size()).append("\n");
|
||||
report.append("Analysis Date: ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).append("\n");
|
||||
report.append("\n");
|
||||
|
||||
// Global metrics
|
||||
report.append("-".repeat(80)).append("\n");
|
||||
report.append("GLOBAL METRICS\n");
|
||||
report.append("-".repeat(80)).append("\n\n");
|
||||
|
||||
report.append(analyzeMetric("Vehicles Generated",
|
||||
extractValues(r -> (double) r.getTotalVehiclesGenerated())));
|
||||
report.append("\n");
|
||||
|
||||
report.append(analyzeMetric("Vehicles Completed",
|
||||
extractValues(r -> (double) r.getTotalVehiclesCompleted())));
|
||||
report.append("\n");
|
||||
|
||||
report.append(analyzeMetric("Completion Rate (%)",
|
||||
extractValues(r -> r.getTotalVehiclesGenerated() > 0
|
||||
? 100.0 * r.getTotalVehiclesCompleted() / r.getTotalVehiclesGenerated()
|
||||
: 0.0)));
|
||||
report.append("\n");
|
||||
|
||||
report.append(analyzeMetric("Average System Time (seconds)",
|
||||
extractValues(r -> r.getAverageSystemTime())));
|
||||
report.append("\n");
|
||||
|
||||
report.append(analyzeMetric("Average Waiting Time (seconds)",
|
||||
extractValues(r -> r.getAverageWaitingTime())));
|
||||
report.append("\n");
|
||||
|
||||
// Per-vehicle-type analysis
|
||||
report.append("\n");
|
||||
report.append("-".repeat(80)).append("\n");
|
||||
report.append("PER-VEHICLE-TYPE ANALYSIS\n");
|
||||
report.append("-".repeat(80)).append("\n\n");
|
||||
|
||||
for (VehicleType type : VehicleType.values()) {
|
||||
report.append("--- ").append(type).append(" ---\n");
|
||||
|
||||
report.append(analyzeMetric(" Vehicle Count",
|
||||
extractValues(r -> (double) r.getVehicleCountByType().getOrDefault(type, 0))));
|
||||
report.append("\n");
|
||||
|
||||
report.append(analyzeMetric(" Avg System Time (seconds)",
|
||||
extractValues(r -> r.getAvgSystemTimeByType().getOrDefault(type, 0.0))));
|
||||
report.append("\n");
|
||||
|
||||
report.append(analyzeMetric(" Avg Waiting Time (seconds)",
|
||||
extractValues(r -> r.getAvgWaitTimeByType().getOrDefault(type, 0.0))));
|
||||
report.append("\n\n");
|
||||
}
|
||||
|
||||
// Per-intersection analysis
|
||||
report.append("-".repeat(80)).append("\n");
|
||||
report.append("PER-INTERSECTION ANALYSIS\n");
|
||||
report.append("-".repeat(80)).append("\n\n");
|
||||
|
||||
Set<String> allIntersections = new TreeSet<>();
|
||||
for (SimulationRunResult result : results) {
|
||||
allIntersections.addAll(result.getMaxQueueSizeByIntersection().keySet());
|
||||
}
|
||||
|
||||
for (String intersection : allIntersections) {
|
||||
report.append("--- ").append(intersection).append(" ---\n");
|
||||
|
||||
report.append(analyzeMetric(" Max Queue Size",
|
||||
extractValues(r -> (double) r.getMaxQueueSizeByIntersection().getOrDefault(intersection, 0))));
|
||||
report.append("\n");
|
||||
|
||||
report.append(analyzeMetric(" Avg Queue Size",
|
||||
extractValues(r -> r.getAvgQueueSizeByIntersection().getOrDefault(intersection, 0.0))));
|
||||
report.append("\n");
|
||||
|
||||
report.append(analyzeMetric(" Vehicles Processed",
|
||||
extractValues(r -> (double) r.getVehiclesProcessedByIntersection().getOrDefault(intersection, 0))));
|
||||
report.append("\n\n");
|
||||
}
|
||||
|
||||
// Individual run summaries
|
||||
report.append("-".repeat(80)).append("\n");
|
||||
report.append("INDIVIDUAL RUN SUMMARIES\n");
|
||||
report.append("-".repeat(80)).append("\n\n");
|
||||
|
||||
for (SimulationRunResult result : results) {
|
||||
report.append(result.toString()).append("\n\n");
|
||||
}
|
||||
|
||||
report.append("=".repeat(80)).append("\n");
|
||||
report.append("END OF REPORT\n");
|
||||
report.append("=".repeat(80)).append("\n");
|
||||
|
||||
return report.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyzes a single metric and returns formatted statistics.
|
||||
*/
|
||||
private String analyzeMetric(String metricName, List<Double> values) {
|
||||
if (values.isEmpty() || values.stream().allMatch(v -> v == 0.0)) {
|
||||
return metricName + ": No data\n";
|
||||
}
|
||||
|
||||
double mean = StatisticalAnalysis.mean(values);
|
||||
double stdDev = StatisticalAnalysis.standardDeviation(values);
|
||||
double[] ci = StatisticalAnalysis.confidenceInterval95(values);
|
||||
double min = StatisticalAnalysis.min(values);
|
||||
double max = StatisticalAnalysis.max(values);
|
||||
double median = StatisticalAnalysis.median(values);
|
||||
|
||||
return String.format(
|
||||
"%s:\n" +
|
||||
" Mean: %10.2f Std Dev: %10.2f\n" +
|
||||
" Median: %10.2f 95%% CI: [%.2f, %.2f]\n" +
|
||||
" Min: %10.2f Max: %10.2f\n",
|
||||
metricName, mean, stdDev, median, ci[0], ci[1], min, max
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts values using a lambda function.
|
||||
*/
|
||||
private List<Double> extractValues(java.util.function.Function<SimulationRunResult, Double> extractor) {
|
||||
List<Double> values = new ArrayList<>();
|
||||
for (SimulationRunResult result : results) {
|
||||
values.add(extractor.apply(result));
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the report to a file.
|
||||
*/
|
||||
public void saveReport(String filename) throws IOException {
|
||||
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename)))) {
|
||||
writer.print(generateReport());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a CSV summary for easy import into spreadsheet tools.
|
||||
*/
|
||||
public void saveCSVSummary(String filename) throws IOException {
|
||||
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename)))) {
|
||||
// Header
|
||||
writer.println("Run,VehiclesGenerated,VehiclesCompleted,CompletionRate," +
|
||||
"AvgSystemTime,AvgWaitingTime,MinSystemTime,MaxSystemTime");
|
||||
|
||||
// Data rows
|
||||
for (SimulationRunResult result : results) {
|
||||
double completionRate = result.getTotalVehiclesGenerated() > 0
|
||||
? 100.0 * result.getTotalVehiclesCompleted() / result.getTotalVehiclesGenerated()
|
||||
: 0.0;
|
||||
|
||||
writer.printf("%d,%d,%d,%.2f,%.2f,%.2f,%.2f,%.2f\n",
|
||||
result.getRunNumber(),
|
||||
result.getTotalVehiclesGenerated(),
|
||||
result.getTotalVehiclesCompleted(),
|
||||
completionRate,
|
||||
result.getAverageSystemTime(),
|
||||
result.getAverageWaitingTime(),
|
||||
result.getMinSystemTime(),
|
||||
result.getMaxSystemTime()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
172
main/src/main/java/sd/analysis/SimulationBatchRunner.java
Normal file
172
main/src/main/java/sd/analysis/SimulationBatchRunner.java
Normal file
@@ -0,0 +1,172 @@
|
||||
package sd.analysis;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Orquestra múltiplas execuções de simulação para análise estatística.
|
||||
*
|
||||
* Em vez de correr uma única simulação manualmente, esta ferramenta permite
|
||||
* correr um "lote"
|
||||
* de N simulações consecutivas. Isto é essencial para recolher dados
|
||||
* estatisticamente significativos
|
||||
* (calcular intervalos de confiança, etc.) conforme exigido pelas
|
||||
* especificações do projeto.
|
||||
*
|
||||
* Utilização:
|
||||
* java sd.analysis.SimulationBatchRunner <ficheiro-config> <num-execucoes>
|
||||
* <dir-saida>
|
||||
*/
|
||||
public class SimulationBatchRunner {
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length < 3) {
|
||||
System.err.println("Usage: SimulationBatchRunner <config-file> <num-runs> <output-dir>");
|
||||
System.err.println("Example: SimulationBatchRunner simulation-medium.properties 10 results/medium");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
String configFile = args[0];
|
||||
int numRuns;
|
||||
String outputDir = args[2];
|
||||
|
||||
try {
|
||||
numRuns = Integer.parseInt(args[1]);
|
||||
if (numRuns < 1 || numRuns > 100) {
|
||||
throw new IllegalArgumentException("Number of runs must be between 1 and 100");
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
System.err.println("Error: Invalid number of runs: " + args[1]);
|
||||
System.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("=".repeat(80));
|
||||
System.out.println("SIMULATION BATCH RUNNER");
|
||||
System.out.println("=".repeat(80));
|
||||
System.out.println("Configuration: " + configFile);
|
||||
System.out.println("Number of Runs: " + numRuns);
|
||||
System.out.println("Output Directory: " + outputDir);
|
||||
System.out.println("=".repeat(80));
|
||||
System.out.println();
|
||||
|
||||
// Create output directory
|
||||
try {
|
||||
Files.createDirectories(Paths.get(outputDir));
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to create output directory: " + e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
MultiRunAnalyzer analyzer = new MultiRunAnalyzer(configFile);
|
||||
|
||||
// Execute runs
|
||||
for (int i = 1; i <= numRuns; i++) {
|
||||
System.out.println("\n" + "=".repeat(80));
|
||||
System.out.println("STARTING RUN " + i + " OF " + numRuns);
|
||||
System.out.println("=".repeat(80));
|
||||
|
||||
SimulationRunResult result = executeSimulationRun(i, configFile, outputDir);
|
||||
|
||||
if (result != null) {
|
||||
analyzer.addResult(result);
|
||||
System.out.println("\n" + result);
|
||||
} else {
|
||||
System.err.println("Run " + i + " failed!");
|
||||
}
|
||||
|
||||
// Pause between runs
|
||||
if (i < numRuns) {
|
||||
System.out.println("\nWaiting 10 seconds before next run...");
|
||||
try {
|
||||
Thread.sleep(10000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate reports
|
||||
System.out.println("\n\n" + "=".repeat(80));
|
||||
System.out.println("ALL RUNS COMPLETE - GENERATING REPORTS");
|
||||
System.out.println("=".repeat(80));
|
||||
|
||||
try {
|
||||
String timestamp = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
|
||||
String reportFile = outputDir + "/analysis-report-" + timestamp + ".txt";
|
||||
String csvFile = outputDir + "/summary-" + timestamp + ".csv";
|
||||
|
||||
analyzer.saveReport(reportFile);
|
||||
analyzer.saveCSVSummary(csvFile);
|
||||
|
||||
System.out.println("\nReports generated:");
|
||||
System.out.println(" - Analysis Report: " + reportFile);
|
||||
System.out.println(" - CSV Summary: " + csvFile);
|
||||
System.out.println();
|
||||
|
||||
// Print report to console
|
||||
System.out.println(analyzer.generateReport());
|
||||
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to generate reports: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executa uma única instância da simulação.
|
||||
*
|
||||
* Idealmente, este método iniciaria todos os processos necessários
|
||||
* (Interseções, Nó de Saída, Coordenador),
|
||||
* esperaria que terminassem e depois recolheria os resultados.
|
||||
*
|
||||
* Atualmente, serve como um espaço reservado estrutural para demonstrar como
|
||||
* funciona o pipeline de análise.
|
||||
* Para correr uma simulação real, deve iniciar os componentes manualmente ou
|
||||
* usar um script shell.
|
||||
*/
|
||||
private static SimulationRunResult executeSimulationRun(int runNumber, String configFile, String outputDir) {
|
||||
SimulationRunResult result = new SimulationRunResult(runNumber, configFile);
|
||||
|
||||
try {
|
||||
// TODO: Implement actual simulation execution
|
||||
// This would involve:
|
||||
// 1. Starting intersection processes
|
||||
// 2. Starting exit node process
|
||||
// 3. Starting dashboard process
|
||||
// 4. Running coordinator
|
||||
// 5. Collecting results from dashboard/exit node
|
||||
// 6. Shutting down all processes
|
||||
|
||||
System.out.println("NOTE: Actual simulation execution not yet implemented.");
|
||||
System.out.println("This batch runner demonstrates the framework structure.");
|
||||
System.out.println("To run actual simulations, you need to:");
|
||||
System.out.println(" 1. Start all intersection processes manually");
|
||||
System.out.println(" 2. Start exit node process");
|
||||
System.out.println(" 3. Start dashboard process");
|
||||
System.out.println(" 4. Run coordinator with the configuration file");
|
||||
System.out.println(" 5. Results will be collected automatically");
|
||||
|
||||
// Placeholder: simulate some results
|
||||
// In real implementation, these would be collected from the actual simulation
|
||||
result.setTotalVehiclesGenerated(100);
|
||||
result.setTotalVehiclesCompleted(85);
|
||||
result.setAverageSystemTime(120.5);
|
||||
result.setMinSystemTime(45.2);
|
||||
result.setMaxSystemTime(250.8);
|
||||
result.setAverageWaitingTime(45.3);
|
||||
|
||||
return result;
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error executing run " + runNumber + ": " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
143
main/src/main/java/sd/analysis/SimulationRunResult.java
Normal file
143
main/src/main/java/sd/analysis/SimulationRunResult.java
Normal file
@@ -0,0 +1,143 @@
|
||||
package sd.analysis;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import sd.model.VehicleType;
|
||||
|
||||
/**
|
||||
* Stores the results of a single simulation run.
|
||||
* Contains all key metrics for post-simulation analysis.
|
||||
*/
|
||||
public class SimulationRunResult {
|
||||
|
||||
private final int runNumber;
|
||||
private final String configurationFile;
|
||||
private final long startTimeMillis;
|
||||
private final long endTimeMillis;
|
||||
|
||||
// Global metrics
|
||||
private int totalVehiclesGenerated;
|
||||
private int totalVehiclesCompleted;
|
||||
private double averageSystemTime; // seconds
|
||||
private double minSystemTime; // seconds
|
||||
private double maxSystemTime; // seconds
|
||||
private double averageWaitingTime; // seconds
|
||||
|
||||
// Per-type metrics
|
||||
private final Map<VehicleType, Integer> vehicleCountByType;
|
||||
private final Map<VehicleType, Double> avgSystemTimeByType;
|
||||
private final Map<VehicleType, Double> avgWaitTimeByType;
|
||||
|
||||
// Per-intersection metrics
|
||||
private final Map<String, Integer> maxQueueSizeByIntersection;
|
||||
private final Map<String, Double> avgQueueSizeByIntersection;
|
||||
private final Map<String, Integer> vehiclesProcessedByIntersection;
|
||||
|
||||
public SimulationRunResult(int runNumber, String configurationFile) {
|
||||
this.runNumber = runNumber;
|
||||
this.configurationFile = configurationFile;
|
||||
this.startTimeMillis = System.currentTimeMillis();
|
||||
this.endTimeMillis = 0;
|
||||
|
||||
this.vehicleCountByType = new HashMap<>();
|
||||
this.avgSystemTimeByType = new HashMap<>();
|
||||
this.avgWaitTimeByType = new HashMap<>();
|
||||
this.maxQueueSizeByIntersection = new HashMap<>();
|
||||
this.avgQueueSizeByIntersection = new HashMap<>();
|
||||
this.vehiclesProcessedByIntersection = new HashMap<>();
|
||||
}
|
||||
|
||||
public void markCompleted() {
|
||||
// This will be called when the run finishes
|
||||
}
|
||||
|
||||
// Getters
|
||||
public int getRunNumber() { return runNumber; }
|
||||
public String getConfigurationFile() { return configurationFile; }
|
||||
public long getStartTimeMillis() { return startTimeMillis; }
|
||||
public long getEndTimeMillis() { return endTimeMillis; }
|
||||
public long getDurationMillis() { return endTimeMillis - startTimeMillis; }
|
||||
|
||||
public int getTotalVehiclesGenerated() { return totalVehiclesGenerated; }
|
||||
public int getTotalVehiclesCompleted() { return totalVehiclesCompleted; }
|
||||
public double getAverageSystemTime() { return averageSystemTime; }
|
||||
public double getMinSystemTime() { return minSystemTime; }
|
||||
public double getMaxSystemTime() { return maxSystemTime; }
|
||||
public double getAverageWaitingTime() { return averageWaitingTime; }
|
||||
|
||||
public Map<VehicleType, Integer> getVehicleCountByType() {
|
||||
return new HashMap<>(vehicleCountByType);
|
||||
}
|
||||
public Map<VehicleType, Double> getAvgSystemTimeByType() {
|
||||
return new HashMap<>(avgSystemTimeByType);
|
||||
}
|
||||
public Map<VehicleType, Double> getAvgWaitTimeByType() {
|
||||
return new HashMap<>(avgWaitTimeByType);
|
||||
}
|
||||
public Map<String, Integer> getMaxQueueSizeByIntersection() {
|
||||
return new HashMap<>(maxQueueSizeByIntersection);
|
||||
}
|
||||
public Map<String, Double> getAvgQueueSizeByIntersection() {
|
||||
return new HashMap<>(avgQueueSizeByIntersection);
|
||||
}
|
||||
public Map<String, Integer> getVehiclesProcessedByIntersection() {
|
||||
return new HashMap<>(vehiclesProcessedByIntersection);
|
||||
}
|
||||
|
||||
// Setters
|
||||
public void setTotalVehiclesGenerated(int count) {
|
||||
this.totalVehiclesGenerated = count;
|
||||
}
|
||||
public void setTotalVehiclesCompleted(int count) {
|
||||
this.totalVehiclesCompleted = count;
|
||||
}
|
||||
public void setAverageSystemTime(double time) {
|
||||
this.averageSystemTime = time;
|
||||
}
|
||||
public void setMinSystemTime(double time) {
|
||||
this.minSystemTime = time;
|
||||
}
|
||||
public void setMaxSystemTime(double time) {
|
||||
this.maxSystemTime = time;
|
||||
}
|
||||
public void setAverageWaitingTime(double time) {
|
||||
this.averageWaitingTime = time;
|
||||
}
|
||||
|
||||
public void setVehicleCountByType(VehicleType type, int count) {
|
||||
vehicleCountByType.put(type, count);
|
||||
}
|
||||
public void setAvgSystemTimeByType(VehicleType type, double time) {
|
||||
avgSystemTimeByType.put(type, time);
|
||||
}
|
||||
public void setAvgWaitTimeByType(VehicleType type, double time) {
|
||||
avgWaitTimeByType.put(type, time);
|
||||
}
|
||||
public void setMaxQueueSize(String intersection, int size) {
|
||||
maxQueueSizeByIntersection.put(intersection, size);
|
||||
}
|
||||
public void setAvgQueueSize(String intersection, double size) {
|
||||
avgQueueSizeByIntersection.put(intersection, size);
|
||||
}
|
||||
public void setVehiclesProcessed(String intersection, int count) {
|
||||
vehiclesProcessedByIntersection.put(intersection, count);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format(
|
||||
"Run #%d [%s]:\n" +
|
||||
" Generated: %d, Completed: %d (%.1f%%)\n" +
|
||||
" Avg System Time: %.2fs\n" +
|
||||
" Avg Waiting Time: %.2fs",
|
||||
runNumber,
|
||||
configurationFile,
|
||||
totalVehiclesGenerated,
|
||||
totalVehiclesCompleted,
|
||||
totalVehiclesGenerated > 0 ? 100.0 * totalVehiclesCompleted / totalVehiclesGenerated : 0.0,
|
||||
averageSystemTime,
|
||||
averageWaitingTime
|
||||
);
|
||||
}
|
||||
}
|
||||
160
main/src/main/java/sd/analysis/StatisticalAnalysis.java
Normal file
160
main/src/main/java/sd/analysis/StatisticalAnalysis.java
Normal file
@@ -0,0 +1,160 @@
|
||||
package sd.analysis;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Statistical analysis utilities for simulation results.
|
||||
* Calculates mean, standard deviation, and confidence intervals.
|
||||
*/
|
||||
public class StatisticalAnalysis {
|
||||
|
||||
/**
|
||||
* Calculates the mean (average) of a list of values.
|
||||
*/
|
||||
public static double mean(List<Double> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return 0.0;
|
||||
}
|
||||
double sum = 0.0;
|
||||
for (double value : values) {
|
||||
sum += value;
|
||||
}
|
||||
return sum / values.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the sample standard deviation.
|
||||
*/
|
||||
public static double standardDeviation(List<Double> values) {
|
||||
if (values == null || values.size() < 2) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double mean = mean(values);
|
||||
double sumSquaredDiff = 0.0;
|
||||
|
||||
for (double value : values) {
|
||||
double diff = value - mean;
|
||||
sumSquaredDiff += diff * diff;
|
||||
}
|
||||
|
||||
// Sample standard deviation (n-1 denominator)
|
||||
return Math.sqrt(sumSquaredDiff / (values.size() - 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the 95% confidence interval for the mean.
|
||||
* Uses t-distribution for small samples (n < 30).
|
||||
*
|
||||
* @return Array of [lowerBound, upperBound]
|
||||
*/
|
||||
public static double[] confidenceInterval95(List<Double> values) {
|
||||
if (values == null || values.size() < 2) {
|
||||
double m = mean(values);
|
||||
return new double[]{m, m};
|
||||
}
|
||||
|
||||
double mean = mean(values);
|
||||
double stdDev = standardDeviation(values);
|
||||
int n = values.size();
|
||||
|
||||
// Critical value from t-distribution (approximation for common sample sizes)
|
||||
double tCritical = getTCriticalValue(n);
|
||||
|
||||
// Standard error of the mean
|
||||
double standardError = stdDev / Math.sqrt(n);
|
||||
|
||||
// Margin of error
|
||||
double marginOfError = tCritical * standardError;
|
||||
|
||||
return new double[]{
|
||||
mean - marginOfError, // Lower bound
|
||||
mean + marginOfError // Upper bound
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the t-critical value for 95% confidence interval.
|
||||
* Approximations for common degrees of freedom (n-1).
|
||||
*/
|
||||
private static double getTCriticalValue(int sampleSize) {
|
||||
int df = sampleSize - 1; // degrees of freedom
|
||||
|
||||
// t-critical values for 95% confidence (two-tailed)
|
||||
if (df >= 30) return 1.96; // z-score for large samples
|
||||
if (df >= 20) return 2.086;
|
||||
if (df >= 15) return 2.131;
|
||||
if (df >= 10) return 2.228;
|
||||
if (df >= 5) return 2.571;
|
||||
if (df >= 3) return 3.182;
|
||||
if (df >= 2) return 4.303;
|
||||
return 12.706; // df = 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the minimum value.
|
||||
*/
|
||||
public static double min(List<Double> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return 0.0;
|
||||
}
|
||||
return Collections.min(values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the maximum value.
|
||||
*/
|
||||
public static double max(List<Double> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return 0.0;
|
||||
}
|
||||
return Collections.max(values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the median value.
|
||||
*/
|
||||
public static double median(List<Double> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
List<Double> sorted = new ArrayList<>(values);
|
||||
Collections.sort(sorted);
|
||||
|
||||
int size = sorted.size();
|
||||
if (size % 2 == 0) {
|
||||
return (sorted.get(size / 2 - 1) + sorted.get(size / 2)) / 2.0;
|
||||
} else {
|
||||
return sorted.get(size / 2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a statistical summary as a string.
|
||||
*/
|
||||
public static String formatSummary(String metricName, List<Double> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return metricName + ": No data";
|
||||
}
|
||||
|
||||
double mean = mean(values);
|
||||
double stdDev = standardDeviation(values);
|
||||
double[] ci = confidenceInterval95(values);
|
||||
double min = min(values);
|
||||
double max = max(values);
|
||||
|
||||
return String.format(
|
||||
"%s:\n" +
|
||||
" Mean: %.2f\n" +
|
||||
" Std Dev: %.2f\n" +
|
||||
" 95%% CI: [%.2f, %.2f]\n" +
|
||||
" Min: %.2f\n" +
|
||||
" Max: %.2f\n" +
|
||||
" Samples: %d",
|
||||
metricName, mean, stdDev, ci[0], ci[1], min, max, values.size()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,110 +3,414 @@ package sd.config;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
/**
|
||||
* Class to load and manage simulation configurations.
|
||||
* Configurations are read from a .properties file.
|
||||
* Carrega e gere configurações da simulação.
|
||||
*
|
||||
* <p>Lê propriedades de um ficheiro .properties e fornece getters
|
||||
* type-safe com valores padrão para robustez.
|
||||
*/
|
||||
public class SimulationConfig {
|
||||
private final Properties properties;
|
||||
|
||||
public SimulationConfig(String filePath) throws IOException {
|
||||
properties = new Properties();
|
||||
try (InputStream input = new FileInputStream(filePath)) {
|
||||
properties.load(input);
|
||||
/** Propriedades carregadas do ficheiro */
|
||||
private final Properties properties;
|
||||
private NetworkConfig networkConfig;
|
||||
|
||||
public static class NetworkConfig {
|
||||
private List<IntersectionConfig> intersections;
|
||||
|
||||
public List<IntersectionConfig> getIntersections() {
|
||||
return intersections;
|
||||
}
|
||||
}
|
||||
|
||||
// Network configurations
|
||||
public static class IntersectionConfig {
|
||||
private String id;
|
||||
private List<String> lights;
|
||||
private Map<String, String> routes;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<String> getLights() {
|
||||
return lights;
|
||||
}
|
||||
|
||||
public Map<String, String> getRoutes() {
|
||||
return routes;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Carrega propriedades do ficheiro especificado.
|
||||
*
|
||||
* <p>Tenta múltiplas estratégias:
|
||||
* <ol>
|
||||
* <li>Caminho direto no sistema de ficheiros
|
||||
* <li>Recurso no classpath (com normalização automática)
|
||||
* <li>Recurso no classpath com barra inicial
|
||||
* </ol>
|
||||
*
|
||||
* @param filePath caminho do ficheiro .properties
|
||||
* @throws IOException se o ficheiro não for encontrado
|
||||
*/
|
||||
public SimulationConfig(String filePath) throws IOException {
|
||||
properties = new Properties();
|
||||
|
||||
// List to track all attempted paths for better error reporting
|
||||
List<String> attemptedPaths = new ArrayList<>();
|
||||
IOException fileSystemException = null;
|
||||
|
||||
// Strategy 1: Try to load directly from file system
|
||||
try (InputStream input = new FileInputStream(filePath)) {
|
||||
properties.load(input);
|
||||
loadNetworkConfig();
|
||||
return; // Successfully loaded from file system
|
||||
} catch (IOException e) {
|
||||
fileSystemException = e;
|
||||
attemptedPaths.add("File system: " + filePath);
|
||||
}
|
||||
|
||||
// Strategy 2: Try to load from classpath with path normalization
|
||||
String resourcePath = filePath;
|
||||
|
||||
// Remove common src/main/resources prefixes
|
||||
resourcePath = resourcePath.replace("src/main/resources/", "").replace("src\\main\\resources\\", "");
|
||||
|
||||
// Remove classpath: prefix if provided
|
||||
if (resourcePath.startsWith("classpath:")) {
|
||||
resourcePath = resourcePath.substring("classpath:".length());
|
||||
if (resourcePath.startsWith("/")) {
|
||||
resourcePath = resourcePath.substring(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Try loading from classpath using thread context class loader
|
||||
InputStream resourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
|
||||
attemptedPaths.add("Classpath (context): " + resourcePath);
|
||||
|
||||
if (resourceStream == null) {
|
||||
// Strategy 3: Try with leading slash
|
||||
String slashPath = "/" + resourcePath;
|
||||
resourceStream = SimulationConfig.class.getResourceAsStream(slashPath);
|
||||
attemptedPaths.add("Classpath (class): " + slashPath);
|
||||
}
|
||||
|
||||
if (resourceStream != null) {
|
||||
try (InputStream input = resourceStream) {
|
||||
properties.load(input);
|
||||
loadNetworkConfig();
|
||||
return; // Successfully loaded from classpath
|
||||
} catch (IOException e) {
|
||||
// Failed to read from classpath resource
|
||||
throw new IOException(
|
||||
String.format("Failed to read properties from classpath resource '%s': %s",
|
||||
resourcePath, e.getMessage()),
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
// All strategies failed - provide comprehensive error message
|
||||
StringBuilder errorMsg = new StringBuilder();
|
||||
errorMsg.append("Configuration file '").append(filePath).append("' could not be found.\n");
|
||||
errorMsg.append("Attempted locations:\n");
|
||||
for (String path : attemptedPaths) {
|
||||
errorMsg.append(" - ").append(path).append("\n");
|
||||
}
|
||||
|
||||
if (fileSystemException != null) {
|
||||
errorMsg.append("\nOriginal error: ").append(fileSystemException.getMessage());
|
||||
}
|
||||
|
||||
throw new IOException(errorMsg.toString(), fileSystemException);
|
||||
}
|
||||
|
||||
private void loadNetworkConfig() {
|
||||
try (InputStream is = getClass().getClassLoader().getResourceAsStream("network_config.json")) {
|
||||
if (is == null) {
|
||||
System.err.println("Warning: network_config.json not found in classpath. Using defaults/empty.");
|
||||
return;
|
||||
}
|
||||
try (Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
|
||||
Gson gson = new Gson();
|
||||
this.networkConfig = gson.fromJson(reader, NetworkConfig.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to load network_config.json: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public NetworkConfig getNetworkConfig() {
|
||||
return networkConfig;
|
||||
}
|
||||
|
||||
// --- Network configurations ---
|
||||
|
||||
/**
|
||||
* Gets the host address for a specific intersection.
|
||||
*
|
||||
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
||||
* @return The host (e.g., "localhost").
|
||||
*/
|
||||
public String getIntersectionHost(String intersectionId) {
|
||||
return properties.getProperty("intersection." + intersectionId + ".host", "localhost");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the port number for a specific intersection.
|
||||
*
|
||||
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
||||
* @return The port number.
|
||||
*/
|
||||
public int getIntersectionPort(String intersectionId) {
|
||||
return Integer.parseInt(properties.getProperty("intersection." + intersectionId + ".port", "0"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the host address for the dashboard server.
|
||||
*
|
||||
* @return The dashboard host.
|
||||
*/
|
||||
public String getDashboardHost() {
|
||||
return properties.getProperty("dashboard.host", "localhost");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the port number for the dashboard server.
|
||||
*
|
||||
* @return The dashboard port.
|
||||
*/
|
||||
public int getDashboardPort() {
|
||||
return Integer.parseInt(properties.getProperty("dashboard.port", "9000"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the host address for the exit node.
|
||||
*
|
||||
* @return The exit node host.
|
||||
*/
|
||||
public String getExitHost() {
|
||||
return properties.getProperty("exit.host", "localhost");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the port number for the exit node.
|
||||
*
|
||||
* @return The exit node port.
|
||||
*/
|
||||
public int getExitPort() {
|
||||
return Integer.parseInt(properties.getProperty("exit.port", "9001"));
|
||||
}
|
||||
|
||||
// Simulation configurations
|
||||
// --- Simulation configurations ---
|
||||
|
||||
/**
|
||||
* Gets the total duration of the simulation in virtual seconds.
|
||||
*
|
||||
* @return The simulation duration.
|
||||
*/
|
||||
public double getSimulationDuration() {
|
||||
return Double.parseDouble(properties.getProperty("simulation.duration", "3600.0"));
|
||||
return Double.parseDouble(properties.getProperty("simulation.duration", "3600"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get time scaling factor for visualization.
|
||||
* 0 = instant (pure DES), 0.01 = 100x speed, 0.1 = 10x speed, 1.0 = real-time
|
||||
*/
|
||||
public double getTimeScale() {
|
||||
return Double.parseDouble(properties.getProperty("simulation.time.scale", "0"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the drain time (in virtual seconds) to allow vehicles to exit after
|
||||
* generation stops.
|
||||
*
|
||||
* @return The drain time.
|
||||
*/
|
||||
public double getDrainTime() {
|
||||
return Double.parseDouble(properties.getProperty("simulation.drain.time", "60.0"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the vehicle arrival model ("POISSON" or "FIXED").
|
||||
*
|
||||
* @return The arrival model as a string.
|
||||
*/
|
||||
public String getArrivalModel() {
|
||||
return properties.getProperty("simulation.arrival.model", "POISSON");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the average arrival rate (lambda) for the POISSON model.
|
||||
* This represents the average number of vehicles arriving per second.
|
||||
*
|
||||
* @return The arrival rate.
|
||||
*/
|
||||
public double getArrivalRate() {
|
||||
return Double.parseDouble(properties.getProperty("simulation.arrival.rate", "0.5"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the fixed time interval between vehicle arrivals for the FIXED model.
|
||||
*
|
||||
* @return The fixed interval in seconds.
|
||||
*/
|
||||
public double getFixedArrivalInterval() {
|
||||
return Double.parseDouble(properties.getProperty("simulation.arrival.fixed.interval", "2.0"));
|
||||
}
|
||||
|
||||
// Traffic light configurations
|
||||
// --- Traffic light configurations ---
|
||||
|
||||
/**
|
||||
* Gets the duration of the GREEN light state for a specific traffic light.
|
||||
*
|
||||
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
||||
* @param direction The direction of the light (e.g., "North").
|
||||
* @return The green light time in seconds.
|
||||
*/
|
||||
public double getTrafficLightGreenTime(String intersectionId, String direction) {
|
||||
String key = "trafficlight." + intersectionId + "." + direction + ".green";
|
||||
return Double.parseDouble(properties.getProperty(key, "30.0"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the duration of the RED light state for a specific traffic light.
|
||||
*
|
||||
* @param intersectionId The ID of the intersection (e.g., "Cr1").
|
||||
* @param direction The direction of the light (e.g., "North").
|
||||
* @return The red light time in seconds.
|
||||
*/
|
||||
public double getTrafficLightRedTime(String intersectionId, String direction) {
|
||||
String key = "trafficlight." + intersectionId + "." + direction + ".red";
|
||||
return Double.parseDouble(properties.getProperty(key, "30.0"));
|
||||
}
|
||||
|
||||
// Vehicle configurations
|
||||
// --- Vehicle configurations ---
|
||||
|
||||
/**
|
||||
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type LIGHT.
|
||||
*
|
||||
* @return The probability for LIGHT vehicles.
|
||||
*/
|
||||
public double getLightVehicleProbability() {
|
||||
return Double.parseDouble(properties.getProperty("vehicle.probability.light", "0.7"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the average time it takes a LIGHT vehicle to cross an intersection.
|
||||
*
|
||||
* @return The crossing time in seconds.
|
||||
*/
|
||||
public double getLightVehicleCrossingTime() {
|
||||
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.light", "2.0"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type BIKE.
|
||||
*
|
||||
* @return The probability for BIKE vehicles.
|
||||
*/
|
||||
public double getBikeVehicleProbability() {
|
||||
return Double.parseDouble(properties.getProperty("vehicle.probability.bike", "0.0"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the average time it takes a BIKE vehicle to cross an intersection.
|
||||
*
|
||||
* @return The crossing time in seconds.
|
||||
*/
|
||||
public double getBikeVehicleCrossingTime() {
|
||||
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.bike", "1.5"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the probability (0.0 to 1.0) that a generated vehicle is of type HEAVY.
|
||||
*
|
||||
* @return The probability for HEAVY vehicles.
|
||||
*/
|
||||
public double getHeavyVehicleProbability() {
|
||||
return Double.parseDouble(properties.getProperty("vehicle.probability.heavy", "0.0"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the average time it takes a HEAVY vehicle to cross an intersection.
|
||||
*
|
||||
* @return The crossing time in seconds.
|
||||
*/
|
||||
public double getHeavyVehicleCrossingTime() {
|
||||
return Double.parseDouble(properties.getProperty("vehicle.crossing.time.heavy", "4.0"));
|
||||
}
|
||||
|
||||
// Statistics
|
||||
public double getStatisticsUpdateInterval() {
|
||||
return Double.parseDouble(properties.getProperty("statistics.update.interval", "10.0"));
|
||||
/**
|
||||
* Gets the base travel time between intersections for light vehicles.
|
||||
*
|
||||
* @return The base travel time in seconds.
|
||||
*/
|
||||
public double getBaseTravelTime() {
|
||||
return Double.parseDouble(properties.getProperty("vehicle.travel.time.base", "8.0"));
|
||||
}
|
||||
|
||||
// Generic method to get any property
|
||||
/**
|
||||
* Gets the travel time multiplier for bike vehicles.
|
||||
* Bike travel time = base time × this multiplier.
|
||||
*
|
||||
* @return The multiplier for bike travel time.
|
||||
*/
|
||||
public double getBikeTravelTimeMultiplier() {
|
||||
return Double.parseDouble(properties.getProperty("vehicle.travel.time.bike.multiplier", "0.5"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the travel time multiplier for heavy vehicles.
|
||||
* Heavy vehicle travel time = base time × this multiplier.
|
||||
*
|
||||
* @return The multiplier for heavy vehicle travel time.
|
||||
*/
|
||||
public double getHeavyTravelTimeMultiplier() {
|
||||
return Double.parseDouble(properties.getProperty("vehicle.travel.time.heavy.multiplier", "4.0"));
|
||||
}
|
||||
|
||||
// --- Statistics ---
|
||||
|
||||
/**
|
||||
* Gets the interval (in virtual seconds) between periodic statistics updates.
|
||||
*
|
||||
* @return The statistics update interval.
|
||||
*/
|
||||
public double getStatisticsUpdateInterval() {
|
||||
return Double.parseDouble(properties.getProperty("statistics.update.interval", "1.0"));
|
||||
}
|
||||
|
||||
// --- Generic getters ---
|
||||
|
||||
/**
|
||||
* Generic method to get any property as a string, with a default value.
|
||||
*
|
||||
* @param key The property key.
|
||||
* @param defaultValue The value to return if the key is not found.
|
||||
* @return The property value or the default.
|
||||
*/
|
||||
public String getProperty(String key, String defaultValue) {
|
||||
return properties.getProperty(key, defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic method to get any property as a string.
|
||||
*
|
||||
* @param key The property key.
|
||||
* @return The property value, or null if not found.
|
||||
*/
|
||||
public String getProperty(String key) {
|
||||
return properties.getProperty(key);
|
||||
}
|
||||
|
||||
416
main/src/main/java/sd/coordinator/CoordinatorProcess.java
Normal file
416
main/src/main/java/sd/coordinator/CoordinatorProcess.java
Normal file
@@ -0,0 +1,416 @@
|
||||
package sd.coordinator;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import sd.config.SimulationConfig;
|
||||
import sd.dashboard.StatsUpdatePayload;
|
||||
import sd.des.DESEventType;
|
||||
import sd.des.EventQueue;
|
||||
import sd.des.SimulationClock;
|
||||
import sd.des.SimulationEvent;
|
||||
import sd.logging.EventLogger;
|
||||
import sd.model.Message;
|
||||
import sd.model.MessageType;
|
||||
import sd.model.Vehicle;
|
||||
import sd.serialization.SerializationException;
|
||||
import sd.util.VehicleGenerator;
|
||||
|
||||
/**
|
||||
* Coordenador central da simulação distribuída.
|
||||
*
|
||||
* <p>Responsabilidades:
|
||||
* <ol>
|
||||
* <li>Gerar veículos segundo modelo configurado (Poisson/Fixed)
|
||||
* <li>Injetar veículos nas interseções de entrada
|
||||
* <li>Gerir relógio global e sincronizar componentes
|
||||
* </ol>
|
||||
*
|
||||
* <p>Usa motor DES para agendar eventos de geração com precisão.
|
||||
* Mantém fila de prioridade e processa eventos em ordem cronológica.
|
||||
*/
|
||||
public class CoordinatorProcess {
|
||||
|
||||
private final SimulationConfig config;
|
||||
private final VehicleGenerator vehicleGenerator;
|
||||
private final Map<String, SocketClient> intersectionClients;
|
||||
private SocketClient dashboardClient;
|
||||
|
||||
private final SimulationClock clock;
|
||||
private final EventQueue eventQueue;
|
||||
private final EventLogger eventLogger;
|
||||
|
||||
private int vehicleCounter;
|
||||
private boolean running;
|
||||
private double timeScale;
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("=".repeat(60));
|
||||
System.out.println("COORDINATOR PROCESS - DISTRIBUTED TRAFFIC SIMULATION");
|
||||
System.out.println("=".repeat(60));
|
||||
|
||||
try {
|
||||
// 1. Load configuration
|
||||
String configFile = args.length > 0 ? args[0] : "src/main/resources/simulation.properties";
|
||||
System.out.println("Loading configuration from: " + configFile);
|
||||
|
||||
SimulationConfig config = new SimulationConfig(configFile);
|
||||
CoordinatorProcess coordinator = new CoordinatorProcess(config);
|
||||
|
||||
// 2. Connect to intersection processes
|
||||
System.out.println("\n" + "=".repeat(60));
|
||||
coordinator.initialize();
|
||||
|
||||
// 3. Run the sim
|
||||
System.out.println("\n" + "=".repeat(60));
|
||||
coordinator.run();
|
||||
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to load configuration: " + e.getMessage());
|
||||
System.exit(1);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Coordinator error: " + e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
public CoordinatorProcess(SimulationConfig config) {
|
||||
this.config = config;
|
||||
this.vehicleGenerator = new VehicleGenerator(config);
|
||||
this.intersectionClients = new HashMap<>();
|
||||
this.vehicleCounter = 0;
|
||||
this.running = false;
|
||||
this.timeScale = config.getTimeScale();
|
||||
|
||||
this.clock = new SimulationClock();
|
||||
this.eventQueue = new EventQueue(true);
|
||||
|
||||
this.eventLogger = EventLogger.getInstance();
|
||||
eventLogger.log(sd.logging.EventType.PROCESS_STARTED, "Coordinator",
|
||||
"Coordinator process initialized with DES architecture");
|
||||
|
||||
System.out.println("Coordinator initialized with configuration:");
|
||||
System.out.println(" - Simulation duration: " + config.getSimulationDuration() + "s");
|
||||
System.out.println(" - Arrival model: " + config.getArrivalModel());
|
||||
System.out.println(" - Arrival rate: " + config.getArrivalRate() + " vehicles/s");
|
||||
System.out.println(" - DES Mode: ENABLED (Event-driven, no time-stepping)");
|
||||
}
|
||||
|
||||
public void initialize() {
|
||||
// Connect to dashboard first
|
||||
connectToDashboard();
|
||||
|
||||
System.out.println("Connecting to intersection processes...");
|
||||
|
||||
String[] intersectionIds = { "Cr1", "Cr2", "Cr3", "Cr4", "Cr5" };
|
||||
|
||||
for (String intersectionId : intersectionIds) {
|
||||
try {
|
||||
String host = config.getIntersectionHost(intersectionId);
|
||||
int port = config.getIntersectionPort(intersectionId);
|
||||
|
||||
SocketClient client = new SocketClient(intersectionId, host, port);
|
||||
client.connect();
|
||||
intersectionClients.put(intersectionId, client);
|
||||
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to connect to " + intersectionId + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("Successfully connected to " + intersectionClients.size() + " intersection(s)");
|
||||
|
||||
if (intersectionClients.isEmpty()) {
|
||||
System.err.println("WARNING: No intersections connected. Simulation cannot proceed.");
|
||||
}
|
||||
}
|
||||
|
||||
public void run() {
|
||||
double duration = config.getSimulationDuration();
|
||||
double drainTime = config.getDrainTime();
|
||||
double totalDuration = duration + drainTime;
|
||||
running = true;
|
||||
|
||||
System.out.println("Starting DES-based vehicle generation simulation...");
|
||||
System.out.println("Duration: " + duration + "s (+ " + drainTime + "s drain)");
|
||||
System.out.println();
|
||||
|
||||
// Log simulation start
|
||||
eventLogger.log(sd.logging.EventType.SIMULATION_STARTED, "Coordinator",
|
||||
String.format("Starting simulation - Duration: %.1fs", duration));
|
||||
|
||||
// Send simulation start time to all processes for synchronization
|
||||
sendSimulationStartTime();
|
||||
|
||||
// Schedule first vehicle generation event
|
||||
double firstArrivalTime = vehicleGenerator.getNextArrivalTime(clock.getCurrentTime());
|
||||
eventQueue.schedule(new SimulationEvent(
|
||||
firstArrivalTime,
|
||||
DESEventType.VEHICLE_GENERATION,
|
||||
null,
|
||||
"Coordinator"));
|
||||
|
||||
// Schedule simulation end event
|
||||
eventQueue.schedule(new SimulationEvent(
|
||||
totalDuration,
|
||||
DESEventType.SIMULATION_END,
|
||||
null,
|
||||
"Coordinator"));
|
||||
|
||||
System.out.printf("Initial event scheduled at t=%.3fs\n", firstArrivalTime);
|
||||
System.out.println("Entering DES event loop...\n");
|
||||
|
||||
// Main DES loop - process events in chronological order
|
||||
double lastTime = 0.0;
|
||||
while (running && !eventQueue.isEmpty()) {
|
||||
SimulationEvent event = eventQueue.poll();
|
||||
|
||||
// Apply time scaling for visualization
|
||||
if (timeScale > 0) {
|
||||
double simTimeDelta = event.getTimestamp() - lastTime;
|
||||
long realDelayMs = (long) (simTimeDelta * timeScale * 1000);
|
||||
if (realDelayMs > 0) {
|
||||
try {
|
||||
Thread.sleep(realDelayMs);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
lastTime = event.getTimestamp();
|
||||
}
|
||||
|
||||
// Advance simulation time to event time
|
||||
clock.advanceTo(event.getTimestamp());
|
||||
|
||||
// Process the event
|
||||
processEvent(event, duration);
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.printf("Simulation complete at t=%.2fs\n", clock.getCurrentTime());
|
||||
System.out.println("Total vehicles generated: " + vehicleCounter);
|
||||
System.out.println("Total events processed: " + eventQueue.getProcessedCount());
|
||||
|
||||
// Log simulation end
|
||||
eventLogger.log(sd.logging.EventType.SIMULATION_STOPPED, "Coordinator",
|
||||
String.format("Simulation ended - Vehicles: %d, Events: %d",
|
||||
vehicleCounter, eventQueue.getProcessedCount()));
|
||||
|
||||
// Export event history (spec requirement: view complete event list)
|
||||
exportEventHistory();
|
||||
|
||||
shutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Trata um único evento de simulação.
|
||||
*
|
||||
* É aqui que a magia acontece. Dependendo do tipo de evento (como
|
||||
* VEHICLE_GENERATION),
|
||||
* atualizamos o estado do mundo. Para a geração de veículos, criamos um novo
|
||||
* veículo,
|
||||
* enviamo-lo para uma interseção e depois agendamos o *próximo* evento de
|
||||
* geração.
|
||||
*/
|
||||
private void processEvent(SimulationEvent event, double generationDuration) {
|
||||
double currentTime = clock.getCurrentTime();
|
||||
|
||||
switch (event.getType()) {
|
||||
case VEHICLE_GENERATION:
|
||||
// Only generate if we're still in the generation phase
|
||||
if (currentTime < generationDuration) {
|
||||
generateAndSendVehicle();
|
||||
|
||||
// Schedule next vehicle generation
|
||||
double nextArrivalTime = vehicleGenerator.getNextArrivalTime(currentTime);
|
||||
eventQueue.schedule(new SimulationEvent(
|
||||
nextArrivalTime,
|
||||
DESEventType.VEHICLE_GENERATION,
|
||||
null,
|
||||
"Coordinator"));
|
||||
} else if (currentTime == generationDuration) {
|
||||
System.out.printf("\n[t=%.2f] Generation phase complete. Entering DRAIN MODE...\n",
|
||||
currentTime);
|
||||
}
|
||||
break;
|
||||
|
||||
case SIMULATION_END:
|
||||
System.out.printf("[t=%.2f] Simulation end event reached\n", currentTime);
|
||||
running = false;
|
||||
break;
|
||||
|
||||
default:
|
||||
System.err.println("WARNING: Unknown event type: " + event.getType());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarda o histórico completo de eventos de simulação num ficheiro de texto.
|
||||
* Isto permite-nos auditar exatamente o que aconteceu e quando, o que é crucial
|
||||
* para depuração e verificação.
|
||||
*/
|
||||
private void exportEventHistory() {
|
||||
try (java.io.PrintWriter writer = new java.io.PrintWriter(
|
||||
new java.io.FileWriter("logs/coordinator-event-history.txt"))) {
|
||||
String history = eventQueue.exportEventHistory();
|
||||
writer.println(history);
|
||||
System.out.println("\nEvent history exported to: logs/coordinator-event-history.txt");
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to export event history: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void generateAndSendVehicle() {
|
||||
double currentTime = clock.getCurrentTime();
|
||||
Vehicle vehicle = vehicleGenerator.generateVehicle("V" + (++vehicleCounter), currentTime);
|
||||
|
||||
System.out.printf("[t=%.2f] Vehicle %s generated (type=%s, route=%s)%n",
|
||||
currentTime, vehicle.getId(), vehicle.getType(), vehicle.getRoute());
|
||||
|
||||
// Log to event logger
|
||||
eventLogger.log(sd.logging.EventType.VEHICLE_GENERATED, "Coordinator",
|
||||
String.format("[%s] Type: %s, Route: %s", vehicle.getId(), vehicle.getType(), vehicle.getRoute()));
|
||||
|
||||
// Send generation count to dashboard
|
||||
sendGenerationStatsToDashboard();
|
||||
|
||||
if (vehicle.getRoute().isEmpty()) {
|
||||
System.err.println("ERROR: Vehicle " + vehicle.getId() + " has empty route!");
|
||||
return;
|
||||
}
|
||||
|
||||
String entryIntersection = vehicle.getRoute().get(0);
|
||||
sendVehicleToIntersection(vehicle, entryIntersection);
|
||||
}
|
||||
|
||||
private void sendVehicleToIntersection(Vehicle vehicle, String intersectionId) {
|
||||
SocketClient client = intersectionClients.get(intersectionId);
|
||||
|
||||
if (client == null || !client.isConnected()) {
|
||||
System.err.println("ERROR: No connection to " + intersectionId + " for vehicle " + vehicle.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Message message = new Message(
|
||||
MessageType.VEHICLE_SPAWN,
|
||||
"COORDINATOR",
|
||||
intersectionId,
|
||||
vehicle);
|
||||
|
||||
client.send(message);
|
||||
System.out.printf("->Sent to %s%n", intersectionId);
|
||||
|
||||
} catch (SerializationException | IOException e) {
|
||||
System.err.println("ERROR: Failed to send vehicle " + vehicle.getId() + " to " + intersectionId);
|
||||
System.err.println("Reason: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
System.out.println();
|
||||
System.out.println("=".repeat(60));
|
||||
System.out.println("Shutting down coordinator...");
|
||||
|
||||
for (Map.Entry<String, SocketClient> entry : intersectionClients.entrySet()) {
|
||||
String intersectionId = entry.getKey();
|
||||
SocketClient client = entry.getValue();
|
||||
|
||||
try {
|
||||
if (client.isConnected()) {
|
||||
Message personalizedShutdown = new Message(
|
||||
MessageType.SHUTDOWN,
|
||||
"COORDINATOR",
|
||||
intersectionId,
|
||||
"Simulation complete");
|
||||
client.send(personalizedShutdown);
|
||||
System.out.println("Sent shutdown message to " + intersectionId);
|
||||
}
|
||||
} catch (SerializationException | IOException e) {
|
||||
System.err.println("Error sending shutdown to " + intersectionId + ": " + e.getMessage());
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("Coordinator shutdown complete");
|
||||
System.out.println("=".repeat(60));
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
System.out.println("\nStop signal received...");
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
122
main/src/main/java/sd/coordinator/SocketClient.java
Normal file
122
main/src/main/java/sd/coordinator/SocketClient.java
Normal file
@@ -0,0 +1,122 @@
|
||||
package sd.coordinator;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.Socket;
|
||||
|
||||
import sd.model.Message;
|
||||
import sd.serialization.MessageSerializer;
|
||||
import sd.serialization.SerializationException;
|
||||
import sd.serialization.SerializerFactory;
|
||||
|
||||
/**
|
||||
* Cliente socket para comunicação com um processo de interseção.
|
||||
*
|
||||
* <p>Gere uma ligação TCP persistente para uma interseção,
|
||||
* fornecendo uma forma simples de enviar mensagens serializadas.</p>
|
||||
*/
|
||||
public class SocketClient {
|
||||
|
||||
private final String intersectionId;
|
||||
private final String host;
|
||||
private final int port;
|
||||
private Socket socket;
|
||||
private OutputStream outputStream;
|
||||
private MessageSerializer serializer;
|
||||
|
||||
/**
|
||||
* Cria um novo cliente socket para uma interseção.
|
||||
*
|
||||
* @param intersectionId ID da interseção (ex: "Cr1")
|
||||
* @param host endereço do host (ex: "localhost")
|
||||
* @param port número da porta
|
||||
*/
|
||||
public SocketClient(String intersectionId, String host, int port) {
|
||||
this.intersectionId = intersectionId;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.serializer = SerializerFactory.createDefault();
|
||||
}
|
||||
|
||||
/**
|
||||
* Liga-se ao processo da interseção via TCP.
|
||||
*
|
||||
* @throws IOException se a ligação não puder ser estabelecida
|
||||
*/
|
||||
public void connect() throws IOException {
|
||||
try {
|
||||
socket = new Socket(host, port);
|
||||
outputStream = socket.getOutputStream();
|
||||
System.out.println("Connected to " + intersectionId + " at " + host + ":" + port);
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to connect to " + intersectionId + " at " + host + ":" + port);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Envia uma mensagem para a interseção ligada.
|
||||
* A mensagem é serializada e enviada pelo socket.
|
||||
*
|
||||
* @param message mensagem a enviar
|
||||
* @throws SerializationException se a serialização falhar
|
||||
* @throws IOException se a escrita no socket falhar
|
||||
*/
|
||||
public void send(Message message) throws SerializationException, IOException {
|
||||
if (socket == null || socket.isClosed()) {
|
||||
throw new IOException("Socket is not connected to " + intersectionId);
|
||||
}
|
||||
|
||||
try {
|
||||
byte[] data = serializer.serialize(message);
|
||||
|
||||
int length = data.length;
|
||||
outputStream.write((length >> 24) & 0xFF);
|
||||
outputStream.write((length >> 16) & 0xFF);
|
||||
outputStream.write((length >> 8) & 0xFF);
|
||||
outputStream.write(length & 0xFF);
|
||||
|
||||
outputStream.write(data);
|
||||
outputStream.flush();
|
||||
|
||||
} catch (SerializationException | IOException e) {
|
||||
System.err.println("Error sending message to " + intersectionId + ": " + e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the socket connection safely.
|
||||
* Calling it multiple times won’t cause issues.
|
||||
*/
|
||||
public void close() {
|
||||
try {
|
||||
if (outputStream != null) {
|
||||
outputStream.close();
|
||||
}
|
||||
if (socket != null && !socket.isClosed()) {
|
||||
socket.close();
|
||||
System.out.println("Closed connection to " + intersectionId);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("Error closing connection to " + intersectionId + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if connected and socket is open, false otherwise
|
||||
*/
|
||||
public boolean isConnected() {
|
||||
return socket != null && socket.isConnected() && !socket.isClosed();
|
||||
}
|
||||
|
||||
public String getIntersectionId() {
|
||||
return intersectionId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("SocketClient[intersection=%s, host=%s, port=%d, connected=%s]",
|
||||
intersectionId, host, port, isConnected());
|
||||
}
|
||||
}
|
||||
167
main/src/main/java/sd/dashboard/ConfigurationDialog.java
Normal file
167
main/src/main/java/sd/dashboard/ConfigurationDialog.java
Normal file
@@ -0,0 +1,167 @@
|
||||
package sd.dashboard;
|
||||
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.control.ButtonType;
|
||||
import javafx.scene.control.ComboBox;
|
||||
import javafx.scene.control.Dialog;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.Separator;
|
||||
import javafx.scene.control.Spinner;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.stage.Modality;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
/**
|
||||
* Diálogo para configuração avançada de parâmetros da simulação.
|
||||
* Permite ajustar parâmetros em runtime antes de iniciar a simulação.
|
||||
*/
|
||||
public class ConfigurationDialog {
|
||||
|
||||
/**
|
||||
* Mostra um diálogo com opções avançadas de configuração.
|
||||
*
|
||||
* @param owner janela pai
|
||||
* @return true se o utilizador confirmar, false se cancelar
|
||||
*/
|
||||
public static boolean showAdvancedConfig(Stage owner) {
|
||||
Dialog<ButtonType> dialog = new Dialog<>();
|
||||
dialog.initOwner(owner);
|
||||
dialog.initModality(Modality.APPLICATION_MODAL);
|
||||
dialog.setTitle("Configuração Avançada da Simulação");
|
||||
dialog.setHeaderText("Ajustar parâmetros da simulação");
|
||||
|
||||
// Criar painel de configuração
|
||||
VBox content = new VBox(15);
|
||||
content.setPadding(new Insets(20));
|
||||
|
||||
// Seção 1: Parâmetros de Chegada
|
||||
Label arrivalHeader = new Label("Parâmetros de Chegada de Veículos");
|
||||
arrivalHeader.setStyle("-fx-font-weight: bold; -fx-font-size: 14px;");
|
||||
|
||||
GridPane arrivalGrid = new GridPane();
|
||||
arrivalGrid.setHgap(10);
|
||||
arrivalGrid.setVgap(10);
|
||||
arrivalGrid.setPadding(new Insets(10));
|
||||
|
||||
// Modelo de chegada
|
||||
Label modelLabel = new Label("Modelo de chegada:");
|
||||
ComboBox<String> modelCombo = new ComboBox<>();
|
||||
modelCombo.getItems().addAll("POISSON", "FIXED");
|
||||
modelCombo.setValue("POISSON");
|
||||
arrivalGrid.add(modelLabel, 0, 0);
|
||||
arrivalGrid.add(modelCombo, 1, 0);
|
||||
|
||||
// Taxa de chegada (λ)
|
||||
Label rateLabel = new Label("Taxa de chegada (λ) [veículos/s]:");
|
||||
Spinner<Double> rateSpinner = new Spinner<>(0.1, 2.0, 0.5, 0.1);
|
||||
rateSpinner.setEditable(true);
|
||||
rateSpinner.setPrefWidth(100);
|
||||
arrivalGrid.add(rateLabel, 0, 1);
|
||||
arrivalGrid.add(rateSpinner, 1, 1);
|
||||
|
||||
// Intervalo fixo (se aplicável)
|
||||
Label intervalLabel = new Label("Intervalo fixo [s]:");
|
||||
Spinner<Double> intervalSpinner = new Spinner<>(0.5, 10.0, 2.0, 0.5);
|
||||
intervalSpinner.setEditable(true);
|
||||
intervalSpinner.setPrefWidth(100);
|
||||
intervalSpinner.setDisable(true);
|
||||
arrivalGrid.add(intervalLabel, 0, 2);
|
||||
arrivalGrid.add(intervalSpinner, 1, 2);
|
||||
|
||||
// Habilitar/desabilitar intervalo baseado no modelo
|
||||
modelCombo.setOnAction(e -> {
|
||||
boolean isFixed = "FIXED".equals(modelCombo.getValue());
|
||||
intervalSpinner.setDisable(!isFixed);
|
||||
rateSpinner.setDisable(isFixed);
|
||||
});
|
||||
|
||||
// Seção 2: Parâmetros de Tempo
|
||||
Label timeHeader = new Label("Parâmetros de Tempo");
|
||||
timeHeader.setStyle("-fx-font-weight: bold; -fx-font-size: 14px;");
|
||||
|
||||
GridPane timeGrid = new GridPane();
|
||||
timeGrid.setHgap(10);
|
||||
timeGrid.setVgap(10);
|
||||
timeGrid.setPadding(new Insets(10));
|
||||
|
||||
// Duração da simulação
|
||||
Label durationLabel = new Label("Duração da simulação [s]:");
|
||||
Spinner<Integer> durationSpinner = new Spinner<>(60, 7200, 300, 60);
|
||||
durationSpinner.setEditable(true);
|
||||
durationSpinner.setPrefWidth(100);
|
||||
timeGrid.add(durationLabel, 0, 0);
|
||||
timeGrid.add(durationSpinner, 1, 0);
|
||||
|
||||
// Escala temporal (para visualização)
|
||||
Label scaleLabel = new Label("Escala temporal (0=instantâneo, 1=tempo real):");
|
||||
Spinner<Double> scaleSpinner = new Spinner<>(0.0, 1.0, 0.01, 0.01);
|
||||
scaleSpinner.setEditable(true);
|
||||
scaleSpinner.setPrefWidth(100);
|
||||
timeGrid.add(scaleLabel, 0, 1);
|
||||
timeGrid.add(scaleSpinner, 1, 1);
|
||||
|
||||
// Tempo de drenagem
|
||||
Label drainLabel = new Label("Tempo de drenagem [s]:");
|
||||
Spinner<Integer> drainSpinner = new Spinner<>(0, 300, 60, 10);
|
||||
drainSpinner.setEditable(true);
|
||||
drainSpinner.setPrefWidth(100);
|
||||
timeGrid.add(drainLabel, 0, 2);
|
||||
timeGrid.add(drainSpinner, 1, 2);
|
||||
|
||||
// Seção 3: Distribuição de Tipos de Veículos
|
||||
Label vehicleHeader = new Label("Distribuição de Tipos de Veículos");
|
||||
vehicleHeader.setStyle("-fx-font-weight: bold; -fx-font-size: 14px;");
|
||||
|
||||
GridPane vehicleGrid = new GridPane();
|
||||
vehicleGrid.setHgap(10);
|
||||
vehicleGrid.setVgap(10);
|
||||
vehicleGrid.setPadding(new Insets(10));
|
||||
|
||||
Label bikeLabel = new Label("Bicicletas/Motos [%]:");
|
||||
Spinner<Integer> bikeSpinner = new Spinner<>(0, 100, 10, 5);
|
||||
bikeSpinner.setEditable(true);
|
||||
bikeSpinner.setPrefWidth(100);
|
||||
vehicleGrid.add(bikeLabel, 0, 0);
|
||||
vehicleGrid.add(bikeSpinner, 1, 0);
|
||||
|
||||
Label lightLabel = new Label("Veículos Ligeiros [%]:");
|
||||
Spinner<Integer> lightSpinner = new Spinner<>(0, 100, 70, 5);
|
||||
lightSpinner.setEditable(true);
|
||||
lightSpinner.setPrefWidth(100);
|
||||
vehicleGrid.add(lightLabel, 0, 1);
|
||||
vehicleGrid.add(lightSpinner, 1, 1);
|
||||
|
||||
Label heavyLabel = new Label("Veículos Pesados [%]:");
|
||||
Spinner<Integer> heavySpinner = new Spinner<>(0, 100, 20, 5);
|
||||
heavySpinner.setEditable(true);
|
||||
heavySpinner.setPrefWidth(100);
|
||||
vehicleGrid.add(heavyLabel, 0, 2);
|
||||
vehicleGrid.add(heavySpinner, 1, 2);
|
||||
|
||||
// Nota informativa
|
||||
Label noteLabel = new Label("Nota: Estes parâmetros sobrepõem os valores do ficheiro .properties selecionado.\n" +
|
||||
"Para usar os valores padrão do ficheiro, deixe em branco ou cancele.");
|
||||
noteLabel.setWrapText(true);
|
||||
noteLabel.setStyle("-fx-font-size: 11px; -fx-text-fill: #666666;");
|
||||
|
||||
// Adicionar tudo ao conteúdo
|
||||
content.getChildren().addAll(
|
||||
arrivalHeader, arrivalGrid,
|
||||
new Separator(),
|
||||
timeHeader, timeGrid,
|
||||
new Separator(),
|
||||
vehicleHeader, vehicleGrid,
|
||||
new Separator(),
|
||||
noteLabel
|
||||
);
|
||||
|
||||
dialog.getDialogPane().setContent(content);
|
||||
dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
|
||||
|
||||
// Mostrar diálogo e processar resultado
|
||||
return dialog.showAndWait()
|
||||
.map(buttonType -> buttonType == ButtonType.OK)
|
||||
.orElse(false);
|
||||
}
|
||||
}
|
||||
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;
|
||||
|
||||
/**
|
||||
* Agrega e apresenta estatísticas em tempo real de todos os processos da simulação.
|
||||
* Usa um thread pool para gerir ligações concorrentes de clientes.
|
||||
*/
|
||||
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;
|
||||
|
||||
/**
|
||||
* Armazenamento thread-safe de estatísticas agregadas da simulação.
|
||||
* Usa tipos atómicos e coleções concorrentes para atualizações sem locks.
|
||||
*/
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
543
main/src/main/java/sd/dashboard/DashboardUI.java
Normal file
543
main/src/main/java/sd/dashboard/DashboardUI.java
Normal file
@@ -0,0 +1,543 @@
|
||||
package sd.dashboard;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javafx.application.Application;
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Alert;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.ComboBox;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.TableColumn;
|
||||
import javafx.scene.control.TableView;
|
||||
import javafx.scene.control.cell.PropertyValueFactory;
|
||||
import javafx.scene.layout.BorderPane;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.scene.layout.HBox;
|
||||
import javafx.scene.layout.Priority;
|
||||
import javafx.scene.layout.Region;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.scene.shape.Circle;
|
||||
import javafx.stage.Stage;
|
||||
import sd.config.SimulationConfig;
|
||||
import sd.model.VehicleType;
|
||||
|
||||
/**
|
||||
* JavaFX-based Dashboard UI for displaying real-time simulation statistics.
|
||||
* Provides a graphical interface with auto-updating statistics panels.
|
||||
*/
|
||||
public class DashboardUI extends Application {
|
||||
|
||||
private DashboardServer server;
|
||||
private DashboardStatistics statistics;
|
||||
|
||||
// Global Statistics Labels
|
||||
private Label lblVehiclesGenerated;
|
||||
private Label lblVehiclesCompleted;
|
||||
private Label lblVehiclesInTransit;
|
||||
private Label lblAvgSystemTime;
|
||||
private Label lblAvgWaitingTime;
|
||||
private Label lblLastUpdate;
|
||||
|
||||
// Vehicle Type Table
|
||||
private TableView<VehicleTypeRow> vehicleTypeTable;
|
||||
|
||||
// Intersection Table
|
||||
private TableView<IntersectionRow> intersectionTable;
|
||||
|
||||
// Update scheduler
|
||||
private ScheduledExecutorService updateScheduler;
|
||||
|
||||
// Configuration controls
|
||||
private ComboBox<String> configFileSelector;
|
||||
private String selectedConfigFile = "simulation.properties";
|
||||
private Label configInfoLabel;
|
||||
|
||||
@Override
|
||||
public void start(Stage primaryStage) {
|
||||
try {
|
||||
// Initialize server
|
||||
String configFile = getParameters().getRaw().isEmpty()
|
||||
? "src/main/resources/simulation.properties"
|
||||
: getParameters().getRaw().get(0);
|
||||
|
||||
SimulationConfig config = new SimulationConfig(configFile);
|
||||
server = new DashboardServer(config);
|
||||
statistics = server.getStatistics();
|
||||
|
||||
// Start the dashboard server
|
||||
server.start();
|
||||
|
||||
// Build UI
|
||||
BorderPane root = new BorderPane();
|
||||
root.getStyleClass().add("root");
|
||||
|
||||
// Header
|
||||
VBox header = createHeader();
|
||||
root.setTop(header);
|
||||
|
||||
// Main content
|
||||
VBox mainContent = createMainContent();
|
||||
root.setCenter(mainContent);
|
||||
|
||||
// Footer
|
||||
HBox footer = createFooter();
|
||||
root.setBottom(footer);
|
||||
|
||||
// Create scene
|
||||
Scene scene = new Scene(root, 1200, 850);
|
||||
|
||||
// Load CSS
|
||||
String cssUrl = getClass().getResource("/dashboard.css").toExternalForm();
|
||||
scene.getStylesheets().add(cssUrl);
|
||||
|
||||
primaryStage.setTitle("Traffic Simulation Dashboard - Real-time Statistics");
|
||||
primaryStage.setScene(scene);
|
||||
primaryStage.show();
|
||||
|
||||
// Start periodic updates
|
||||
startPeriodicUpdates();
|
||||
|
||||
// Handle window close
|
||||
primaryStage.setOnCloseRequest(event -> {
|
||||
shutdown();
|
||||
});
|
||||
|
||||
} catch (Exception e) {
|
||||
showErrorAlert("Failed to start Dashboard Server", e.getMessage());
|
||||
e.printStackTrace();
|
||||
Platform.exit();
|
||||
}
|
||||
}
|
||||
|
||||
private VBox createHeader() {
|
||||
VBox header = new VBox(10);
|
||||
header.getStyleClass().add("header");
|
||||
header.setAlignment(Pos.CENTER);
|
||||
|
||||
Label title = new Label("DISTRIBUTED TRAFFIC SIMULATION DASHBOARD");
|
||||
title.getStyleClass().add("header-title");
|
||||
|
||||
Label subtitle = new Label("Real-time Statistics and Monitoring");
|
||||
subtitle.getStyleClass().add("header-subtitle");
|
||||
|
||||
// Configuration Panel
|
||||
VBox configPanel = createConfigurationPanel();
|
||||
|
||||
// Control Buttons
|
||||
HBox controls = new HBox(15);
|
||||
controls.setAlignment(Pos.CENTER);
|
||||
|
||||
Button btnStart = new Button("START SIMULATION");
|
||||
btnStart.getStyleClass().add("button-start");
|
||||
|
||||
Button btnStop = new Button("STOP SIMULATION");
|
||||
btnStop.getStyleClass().add("button-stop");
|
||||
btnStop.setDisable(true);
|
||||
|
||||
SimulationProcessManager processManager = new SimulationProcessManager();
|
||||
|
||||
btnStart.setOnAction(e -> {
|
||||
try {
|
||||
// Passar o ficheiro de configuração selecionado
|
||||
processManager.setConfigFile(selectedConfigFile);
|
||||
processManager.startSimulation();
|
||||
btnStart.setDisable(true);
|
||||
btnStop.setDisable(false);
|
||||
configFileSelector.setDisable(true); // Bloquear mudanças durante simulação
|
||||
} catch (IOException ex) {
|
||||
showErrorAlert("Start Failed", "Could not start simulation processes: " + ex.getMessage());
|
||||
}
|
||||
});
|
||||
|
||||
btnStop.setOnAction(e -> {
|
||||
processManager.stopSimulation();
|
||||
btnStart.setDisable(false);
|
||||
btnStop.setDisable(true);
|
||||
configFileSelector.setDisable(false); // Desbloquear para nova simulação
|
||||
});
|
||||
|
||||
controls.getChildren().addAll(btnStart, btnStop);
|
||||
|
||||
header.getChildren().addAll(title, subtitle, configPanel, controls);
|
||||
|
||||
return header;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cria o painel de configuração com seleção de cenário e parâmetros.
|
||||
*/
|
||||
private VBox createConfigurationPanel() {
|
||||
VBox configBox = new VBox(10);
|
||||
configBox.setAlignment(Pos.CENTER);
|
||||
configBox.setPadding(new Insets(10));
|
||||
configBox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.05); -fx-background-radius: 5;");
|
||||
|
||||
Label configLabel = new Label("Configuração da Simulação");
|
||||
configLabel.setStyle("-fx-font-size: 14px; -fx-font-weight: bold;");
|
||||
|
||||
HBox configControls = new HBox(20);
|
||||
configControls.setAlignment(Pos.CENTER);
|
||||
|
||||
// Scenario selector
|
||||
VBox scenarioBox = new VBox(5);
|
||||
scenarioBox.setAlignment(Pos.CENTER);
|
||||
Label scenarioLabel = new Label("Cenário:");
|
||||
scenarioLabel.setStyle("-fx-font-size: 12px;");
|
||||
|
||||
configFileSelector = new ComboBox<>();
|
||||
configFileSelector.getItems().addAll(
|
||||
"simulation.properties",
|
||||
"simulation-low.properties",
|
||||
"simulation-medium.properties",
|
||||
"simulation-high.properties"
|
||||
);
|
||||
configFileSelector.setValue("simulation.properties");
|
||||
configFileSelector.setOnAction(e -> {
|
||||
selectedConfigFile = configFileSelector.getValue();
|
||||
updateConfigInfo();
|
||||
System.out.println("Configuração selecionada: " + selectedConfigFile);
|
||||
});
|
||||
|
||||
scenarioBox.getChildren().addAll(scenarioLabel, configFileSelector);
|
||||
configControls.getChildren().add(scenarioBox);
|
||||
|
||||
// Advanced configuration button
|
||||
Button btnAdvancedConfig = new Button("Configuração Avançada...");
|
||||
btnAdvancedConfig.setStyle("-fx-font-size: 11px;");
|
||||
btnAdvancedConfig.setOnAction(e -> {
|
||||
ConfigurationDialog.showAdvancedConfig((Stage) configBox.getScene().getWindow());
|
||||
});
|
||||
configControls.getChildren().add(btnAdvancedConfig);
|
||||
|
||||
// Configuration info display
|
||||
configInfoLabel = new Label();
|
||||
configInfoLabel.setStyle("-fx-font-size: 11px; -fx-text-fill: #aaaaaa;");
|
||||
configInfoLabel.setWrapText(true);
|
||||
configInfoLabel.setMaxWidth(800);
|
||||
configInfoLabel.setAlignment(Pos.CENTER);
|
||||
updateConfigInfo();
|
||||
|
||||
configBox.getChildren().addAll(configLabel, configControls, configInfoLabel);
|
||||
return configBox;
|
||||
}
|
||||
|
||||
private VBox createMainContent() {
|
||||
VBox mainContent = new VBox(20);
|
||||
mainContent.setPadding(new Insets(20));
|
||||
|
||||
// Global Statistics Panel
|
||||
VBox globalStatsCard = createGlobalStatisticsPanel();
|
||||
|
||||
// Tables Container
|
||||
HBox tablesContainer = new HBox(20);
|
||||
tablesContainer.setAlignment(Pos.TOP_CENTER);
|
||||
|
||||
// Vehicle Type Statistics Panel
|
||||
VBox vehicleTypeCard = createVehicleTypePanel();
|
||||
HBox.setHgrow(vehicleTypeCard, Priority.ALWAYS);
|
||||
|
||||
// Intersection Statistics Panel
|
||||
VBox intersectionCard = createIntersectionPanel();
|
||||
HBox.setHgrow(intersectionCard, Priority.ALWAYS);
|
||||
|
||||
tablesContainer.getChildren().addAll(vehicleTypeCard, intersectionCard);
|
||||
|
||||
mainContent.getChildren().addAll(globalStatsCard, tablesContainer);
|
||||
|
||||
return mainContent;
|
||||
}
|
||||
|
||||
private VBox createGlobalStatisticsPanel() {
|
||||
VBox card = new VBox();
|
||||
card.getStyleClass().add("card");
|
||||
|
||||
// Card Header
|
||||
HBox cardHeader = new HBox();
|
||||
cardHeader.getStyleClass().add("card-header");
|
||||
Label cardTitle = new Label("Global Statistics");
|
||||
cardTitle.getStyleClass().add("card-title");
|
||||
cardHeader.getChildren().add(cardTitle);
|
||||
|
||||
// Card Content
|
||||
GridPane grid = new GridPane();
|
||||
grid.getStyleClass().add("card-content");
|
||||
grid.setHgap(40);
|
||||
grid.setVgap(15);
|
||||
grid.setAlignment(Pos.CENTER);
|
||||
|
||||
// Initialize labels
|
||||
lblVehiclesGenerated = createStatValueLabel("0");
|
||||
lblVehiclesCompleted = createStatValueLabel("0");
|
||||
lblVehiclesInTransit = createStatValueLabel("0");
|
||||
lblAvgSystemTime = createStatValueLabel("0.00 s");
|
||||
lblAvgWaitingTime = createStatValueLabel("0.00 s");
|
||||
|
||||
// Add labels with descriptions
|
||||
addStatRow(grid, 0, 0, "Total Vehicles Generated", lblVehiclesGenerated);
|
||||
addStatRow(grid, 1, 0, "Total Vehicles Completed", lblVehiclesCompleted);
|
||||
addStatRow(grid, 2, 0, "Vehicles In Transit", lblVehiclesInTransit);
|
||||
addStatRow(grid, 0, 1, "Average System Time", lblAvgSystemTime);
|
||||
addStatRow(grid, 1, 1, "Average Waiting Time", lblAvgWaitingTime);
|
||||
|
||||
card.getChildren().addAll(cardHeader, grid);
|
||||
return card;
|
||||
}
|
||||
|
||||
private VBox createVehicleTypePanel() {
|
||||
VBox card = new VBox();
|
||||
card.getStyleClass().add("card");
|
||||
|
||||
// Card Header
|
||||
HBox cardHeader = new HBox();
|
||||
cardHeader.getStyleClass().add("card-header");
|
||||
Label cardTitle = new Label("Vehicle Type Statistics");
|
||||
cardTitle.getStyleClass().add("card-title");
|
||||
cardHeader.getChildren().add(cardTitle);
|
||||
|
||||
// Table
|
||||
vehicleTypeTable = new TableView<>();
|
||||
vehicleTypeTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
||||
vehicleTypeTable.setPrefHeight(300);
|
||||
|
||||
TableColumn<VehicleTypeRow, String> typeCol = new TableColumn<>("Vehicle Type");
|
||||
typeCol.setCellValueFactory(new PropertyValueFactory<>("vehicleType"));
|
||||
|
||||
TableColumn<VehicleTypeRow, Integer> countCol = new TableColumn<>("Count");
|
||||
countCol.setCellValueFactory(new PropertyValueFactory<>("count"));
|
||||
|
||||
TableColumn<VehicleTypeRow, String> avgWaitCol = new TableColumn<>("Avg Wait Time");
|
||||
avgWaitCol.setCellValueFactory(new PropertyValueFactory<>("avgWaitTime"));
|
||||
|
||||
vehicleTypeTable.getColumns().addAll(typeCol, countCol, avgWaitCol);
|
||||
|
||||
card.getChildren().addAll(cardHeader, vehicleTypeTable);
|
||||
return card;
|
||||
}
|
||||
|
||||
private VBox createIntersectionPanel() {
|
||||
VBox card = new VBox();
|
||||
card.getStyleClass().add("card");
|
||||
|
||||
// Card Header
|
||||
HBox cardHeader = new HBox();
|
||||
cardHeader.getStyleClass().add("card-header");
|
||||
Label cardTitle = new Label("Intersection Statistics");
|
||||
cardTitle.getStyleClass().add("card-title");
|
||||
cardHeader.getChildren().add(cardTitle);
|
||||
|
||||
// Table
|
||||
intersectionTable = new TableView<>();
|
||||
intersectionTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
|
||||
intersectionTable.setPrefHeight(300);
|
||||
|
||||
TableColumn<IntersectionRow, String> idCol = new TableColumn<>("Intersection ID");
|
||||
idCol.setCellValueFactory(new PropertyValueFactory<>("intersectionId"));
|
||||
|
||||
TableColumn<IntersectionRow, Integer> arrivalsCol = new TableColumn<>("Total Arrivals");
|
||||
arrivalsCol.setCellValueFactory(new PropertyValueFactory<>("arrivals"));
|
||||
|
||||
TableColumn<IntersectionRow, Integer> departuresCol = new TableColumn<>("Total Departures");
|
||||
departuresCol.setCellValueFactory(new PropertyValueFactory<>("departures"));
|
||||
|
||||
TableColumn<IntersectionRow, Integer> queueCol = new TableColumn<>("Current Queue");
|
||||
queueCol.setCellValueFactory(new PropertyValueFactory<>("queueSize"));
|
||||
|
||||
intersectionTable.getColumns().addAll(idCol, arrivalsCol, departuresCol, queueCol);
|
||||
|
||||
card.getChildren().addAll(cardHeader, intersectionTable);
|
||||
return card;
|
||||
}
|
||||
|
||||
private HBox createFooter() {
|
||||
HBox footer = new HBox(10);
|
||||
footer.getStyleClass().add("footer");
|
||||
footer.setAlignment(Pos.CENTER_LEFT);
|
||||
|
||||
Label statusLabel = new Label("Status:");
|
||||
statusLabel.getStyleClass().add("footer-text");
|
||||
statusLabel.setStyle("-fx-font-weight: bold;");
|
||||
|
||||
Circle statusIndicator = new Circle(6);
|
||||
statusIndicator.setFill(javafx.scene.paint.Color.LIME);
|
||||
|
||||
Label statusText = new Label("Connected and Receiving Data");
|
||||
statusText.getStyleClass().add("footer-text");
|
||||
|
||||
lblLastUpdate = new Label("Last Update: --:--:--");
|
||||
lblLastUpdate.getStyleClass().add("footer-text");
|
||||
|
||||
Region spacer = new Region();
|
||||
HBox.setHgrow(spacer, Priority.ALWAYS);
|
||||
|
||||
footer.getChildren().addAll(statusLabel, statusIndicator, statusText, spacer, lblLastUpdate);
|
||||
|
||||
return footer;
|
||||
}
|
||||
|
||||
private Label createStatValueLabel(String initialValue) {
|
||||
Label label = new Label(initialValue);
|
||||
label.getStyleClass().add("stat-value");
|
||||
return label;
|
||||
}
|
||||
|
||||
private void addStatRow(GridPane grid, int row, int colGroup, String description, Label valueLabel) {
|
||||
VBox container = new VBox(5);
|
||||
container.setAlignment(Pos.CENTER_LEFT);
|
||||
|
||||
Label descLabel = new Label(description);
|
||||
descLabel.getStyleClass().add("stat-label");
|
||||
|
||||
container.getChildren().addAll(descLabel, valueLabel);
|
||||
|
||||
grid.add(container, colGroup, row);
|
||||
}
|
||||
|
||||
private void startPeriodicUpdates() {
|
||||
updateScheduler = Executors.newSingleThreadScheduledExecutor();
|
||||
updateScheduler.scheduleAtFixedRate(() -> {
|
||||
Platform.runLater(this::updateUI);
|
||||
}, 0, 100, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private void updateUI() {
|
||||
// Update global statistics
|
||||
lblVehiclesGenerated.setText(String.valueOf(statistics.getTotalVehiclesGenerated()));
|
||||
lblVehiclesCompleted.setText(String.valueOf(statistics.getTotalVehiclesCompleted()));
|
||||
lblVehiclesInTransit.setText(String.valueOf(
|
||||
statistics.getTotalVehiclesGenerated() - statistics.getTotalVehiclesCompleted()));
|
||||
lblAvgSystemTime.setText(String.format("%.2f s", statistics.getAverageSystemTime() / 1000.0));
|
||||
lblAvgWaitingTime.setText(String.format("%.2f s", statistics.getAverageWaitingTime() / 1000.0));
|
||||
lblLastUpdate.setText(String.format("Last Update: %tT", statistics.getLastUpdateTime()));
|
||||
|
||||
// Update vehicle type table
|
||||
vehicleTypeTable.getItems().clear();
|
||||
for (VehicleType type : VehicleType.values()) {
|
||||
int count = statistics.getVehicleTypeCount(type);
|
||||
double avgWait = statistics.getAverageWaitingTimeByType(type);
|
||||
vehicleTypeTable.getItems().add(new VehicleTypeRow(
|
||||
type.toString(), count, String.format("%.2f s", avgWait / 1000.0)));
|
||||
}
|
||||
|
||||
// Update intersection table
|
||||
intersectionTable.getItems().clear();
|
||||
Map<String, DashboardStatistics.IntersectionStats> intersectionStats = statistics.getAllIntersectionStats();
|
||||
for (DashboardStatistics.IntersectionStats stats : intersectionStats.values()) {
|
||||
intersectionTable.getItems().add(new IntersectionRow(
|
||||
stats.getIntersectionId(),
|
||||
stats.getTotalArrivals(),
|
||||
stats.getTotalDepartures(),
|
||||
stats.getCurrentQueueSize()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atualiza a informação exibida sobre a configuração selecionada.
|
||||
*/
|
||||
private void updateConfigInfo() {
|
||||
String info = "";
|
||||
switch (selectedConfigFile) {
|
||||
case "simulation-low.properties":
|
||||
info = "🟢 CARGA BAIXA: 0.2 veículos/s (~720/hora) | Sem congestionamento esperado";
|
||||
break;
|
||||
case "simulation-medium.properties":
|
||||
info = "🟡 CARGA MÉDIA: 0.5 veículos/s (~1800/hora) | Algum congestionamento esperado";
|
||||
break;
|
||||
case "simulation-high.properties":
|
||||
info = "🔴 CARGA ALTA: 1.0 veículo/s (~3600/hora) | Congestionamento significativo esperado";
|
||||
break;
|
||||
default:
|
||||
info = "⚙️ CONFIGURAÇÃO PADRÃO: Verificar ficheiro para parâmetros";
|
||||
break;
|
||||
}
|
||||
configInfoLabel.setText(info);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
7
main/src/main/java/sd/dashboard/Launcher.java
Normal file
7
main/src/main/java/sd/dashboard/Launcher.java
Normal file
@@ -0,0 +1,7 @@
|
||||
package sd.dashboard;
|
||||
|
||||
public class Launcher {
|
||||
public static void main(String[] args) {
|
||||
DashboardUI.main(args);
|
||||
}
|
||||
}
|
||||
129
main/src/main/java/sd/dashboard/SimulationProcessManager.java
Normal file
129
main/src/main/java/sd/dashboard/SimulationProcessManager.java
Normal file
@@ -0,0 +1,129 @@
|
||||
package sd.dashboard;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Gere o ciclo de vida dos processos de simulação (Intersections, Exit Node,
|
||||
* Coordinator).
|
||||
* Permite iniciar e parar a simulação distribuída dentro da aplicação Java.
|
||||
*/
|
||||
public class SimulationProcessManager {
|
||||
|
||||
private final List<Process> runningProcesses;
|
||||
private final String classpath;
|
||||
private String configFile;
|
||||
|
||||
public SimulationProcessManager() {
|
||||
this.runningProcesses = new ArrayList<>();
|
||||
this.classpath = System.getProperty("java.class.path");
|
||||
this.configFile = "src/main/resources/simulation.properties";
|
||||
}
|
||||
|
||||
/**
|
||||
* Define o ficheiro de configuração a usar.
|
||||
*
|
||||
* @param configFile nome do ficheiro (ex: "simulation-low.properties")
|
||||
*/
|
||||
public void setConfigFile(String configFile) {
|
||||
this.configFile = "src/main/resources/" + configFile;
|
||||
System.out.println("Configuration file set to: " + this.configFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inicia a simulação completa: 5 Intersections, 1 Exit Node, e 1 Coordinator.
|
||||
*
|
||||
* @throws IOException se um processo falhar ao iniciar
|
||||
*/
|
||||
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 para iniciar um único processo Java.
|
||||
*/
|
||||
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, configFile);
|
||||
} else {
|
||||
builder = new ProcessBuilder(javaBin, "-cp", classpath, className, configFile);
|
||||
}
|
||||
|
||||
// get the OS temp folder
|
||||
// Linux: /tmp/
|
||||
// Windows: %AppData%\Local\Temp\
|
||||
String tempDir = System.getProperty("java.io.tmpdir");
|
||||
|
||||
String logName = className.substring(className.lastIndexOf('.') + 1) + (arg != null ? "-" + arg : "") + ".log";
|
||||
|
||||
// use the (File parent, String child) constructor to handle slash/backslash
|
||||
// automatically
|
||||
File logFile = new File(tempDir, logName);
|
||||
|
||||
builder.redirectOutput(logFile);
|
||||
builder.redirectError(logFile);
|
||||
|
||||
Process process = builder.start();
|
||||
runningProcesses.add(process);
|
||||
System.out.println("Started " + className + (arg != null ? " " + arg : ""));
|
||||
// print where the logs are actually going
|
||||
System.out.println("Logs redirected to: " + logFile.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
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;
|
||||
|
||||
/**
|
||||
* DTO para atualizações de estatísticas ao dashboard.
|
||||
* Campos com valor -1 não são atualizados nesta mensagem.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
39
main/src/main/java/sd/des/DESEventType.java
Normal file
39
main/src/main/java/sd/des/DESEventType.java
Normal file
@@ -0,0 +1,39 @@
|
||||
package sd.des;
|
||||
|
||||
/**
|
||||
* Tipos de eventos discretos da simulação.
|
||||
*
|
||||
* <p>Representa os eventos DES que avançam o estado da simulação,
|
||||
* não categorias de logging (EventType está noutro package).
|
||||
*/
|
||||
public enum DESEventType {
|
||||
/** Gerar novo veículo num ponto de entrada */
|
||||
VEHICLE_GENERATION,
|
||||
|
||||
/** Veículo chega a uma interseção */
|
||||
VEHICLE_ARRIVAL,
|
||||
|
||||
/** Veículo começa a atravessar o semáforo */
|
||||
VEHICLE_CROSSING_START,
|
||||
|
||||
/** Veículo termina a travessia */
|
||||
VEHICLE_CROSSING_END,
|
||||
|
||||
/** Veículo parte para o próximo destino */
|
||||
VEHICLE_DEPARTURE,
|
||||
|
||||
/** Veículo sai do sistema no nó de saída */
|
||||
VEHICLE_EXIT,
|
||||
|
||||
/** Semáforo muda de estado (VERMELHO para VERDE ou vice-versa) */
|
||||
TRAFFIC_LIGHT_CHANGE,
|
||||
|
||||
/** Processar veículos que esperam num semáforo recém-verde */
|
||||
PROCESS_GREEN_LIGHT,
|
||||
|
||||
/** Atualização periódica de estatísticas */
|
||||
STATISTICS_UPDATE,
|
||||
|
||||
/** Terminação da simulação */
|
||||
SIMULATION_END
|
||||
}
|
||||
137
main/src/main/java/sd/des/EventQueue.java
Normal file
137
main/src/main/java/sd/des/EventQueue.java
Normal file
@@ -0,0 +1,137 @@
|
||||
package sd.des;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
/**
|
||||
* Gere a Lista de Eventos Futuros (FEL) para Simulação de Eventos Discretos.
|
||||
*
|
||||
* <p>A FEL é uma fila de prioridade que mantém todos os eventos futuros agendados,
|
||||
* ordenados por timestamp. Este é o coração do paradigma DES - a simulação avança
|
||||
* processando eventos em ordem cronológica.</p>
|
||||
*/
|
||||
public class EventQueue {
|
||||
private final PriorityQueue<SimulationEvent> queue;
|
||||
private final List<SimulationEvent> processedEvents; // For logging and analysis
|
||||
private final boolean trackHistory;
|
||||
|
||||
public EventQueue() {
|
||||
this(true);
|
||||
}
|
||||
|
||||
public EventQueue(boolean trackHistory) {
|
||||
this.queue = new PriorityQueue<>();
|
||||
this.processedEvents = trackHistory ? new ArrayList<>() : null;
|
||||
this.trackHistory = trackHistory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agenda um novo evento.
|
||||
*
|
||||
* @param event evento a agendar
|
||||
*/
|
||||
public void schedule(SimulationEvent event) {
|
||||
queue.offer(event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Agenda um evento com um atraso relativo ao tempo atual.
|
||||
*
|
||||
* @param currentTime tempo atual da simulação
|
||||
* @param delay atraso em segundos
|
||||
* @param type tipo de evento
|
||||
* @param payload dados do evento
|
||||
* @param location localização do evento
|
||||
*/
|
||||
public void scheduleIn(double currentTime, double delay, DESEventType type,
|
||||
Object payload, String location) {
|
||||
double eventTime = currentTime + delay;
|
||||
schedule(new SimulationEvent(eventTime, type, payload, location));
|
||||
}
|
||||
|
||||
/** Obtém o próximo evento sem o remover */
|
||||
public SimulationEvent peek() {
|
||||
return queue.peek();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém e remove o próximo evento.
|
||||
* Se o rastreamento de histórico estiver ativo, adiciona-o aos eventos processados.
|
||||
*/
|
||||
public SimulationEvent poll() {
|
||||
SimulationEvent event = queue.poll();
|
||||
if (event != null && trackHistory) {
|
||||
processedEvents.add(event);
|
||||
}
|
||||
return event;
|
||||
}
|
||||
|
||||
/** Verifica se existem eventos pendentes */
|
||||
public boolean isEmpty() {
|
||||
return queue.isEmpty();
|
||||
}
|
||||
|
||||
/** @return número de eventos pendentes */
|
||||
public int size() {
|
||||
return queue.size();
|
||||
}
|
||||
|
||||
/** Limpa todos os eventos pendentes */
|
||||
public void clear() {
|
||||
queue.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém todos os eventos processados (se o rastreamento estiver ativo).
|
||||
* Retorna uma cópia para evitar modificações.
|
||||
*/
|
||||
public List<SimulationEvent> getProcessedEvents() {
|
||||
if (!trackHistory) {
|
||||
throw new UnsupportedOperationException("History tracking is disabled");
|
||||
}
|
||||
return new ArrayList<>(processedEvents);
|
||||
}
|
||||
|
||||
/** @return número de eventos processados */
|
||||
public int getProcessedCount() {
|
||||
return trackHistory ? processedEvents.size() : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exporta o histórico de eventos para uma string formatada.
|
||||
* Útil para debugging e visualização da lista completa de eventos.
|
||||
*/
|
||||
public String exportEventHistory() {
|
||||
if (!trackHistory) {
|
||||
return "Event history tracking is disabled";
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("=".repeat(80)).append("\n");
|
||||
sb.append("SIMULATION EVENT HISTORY\n");
|
||||
sb.append("Total Events Processed: ").append(processedEvents.size()).append("\n");
|
||||
sb.append("=".repeat(80)).append("\n");
|
||||
sb.append(String.format("%-10s | %-25s | %-20s | %s\n",
|
||||
"Time", "Event Type", "Location", "Details"));
|
||||
sb.append("-".repeat(80)).append("\n");
|
||||
|
||||
for (SimulationEvent event : processedEvents) {
|
||||
String details = event.getPayload() != null ?
|
||||
event.getPayload().getClass().getSimpleName() : "null";
|
||||
sb.append(String.format("%-10.3f | %-25s | %-20s | %s\n",
|
||||
event.getTimestamp(),
|
||||
event.getType(),
|
||||
event.getLocation() != null ? event.getLocation() : "N/A",
|
||||
details));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("EventQueue[pending=%d, processed=%d]",
|
||||
queue.size(), getProcessedCount());
|
||||
}
|
||||
}
|
||||
67
main/src/main/java/sd/des/SimulationClock.java
Normal file
67
main/src/main/java/sd/des/SimulationClock.java
Normal file
@@ -0,0 +1,67 @@
|
||||
package sd.des;
|
||||
|
||||
/**
|
||||
* Gere o tempo de simulação para Simulação de Eventos Discretos.
|
||||
*
|
||||
* <p>No DES, o tempo avança em saltos discretos de evento para evento,
|
||||
* não de forma contínua como o tempo real.</p>
|
||||
*
|
||||
* <p>Esta classe garante que todos os processos no sistema distribuído
|
||||
* mantêm uma visão sincronizada do tempo de simulação.</p>
|
||||
*/
|
||||
public class SimulationClock {
|
||||
private double currentTime;
|
||||
private final double startTime;
|
||||
private final long wallClockStart;
|
||||
|
||||
public SimulationClock() {
|
||||
this(0.0);
|
||||
}
|
||||
|
||||
public SimulationClock(double startTime) {
|
||||
this.currentTime = startTime;
|
||||
this.startTime = startTime;
|
||||
this.wallClockStart = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
/**
|
||||
* Avança o tempo de simulação para o timestamp dado.
|
||||
* O tempo só pode avançar, nunca recuar.
|
||||
*
|
||||
* @param newTime novo tempo de simulação
|
||||
* @throws IllegalArgumentException se newTime for anterior ao tempo atual
|
||||
*/
|
||||
public void advanceTo(double newTime) {
|
||||
if (newTime < currentTime) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Cannot move time backwards: %.3f -> %.3f", currentTime, newTime));
|
||||
}
|
||||
this.currentTime = newTime;
|
||||
}
|
||||
|
||||
/** @return tempo atual da simulação */
|
||||
public double getCurrentTime() {
|
||||
return currentTime;
|
||||
}
|
||||
|
||||
/** @return tempo de simulação decorrido desde o início */
|
||||
public double getElapsedTime() {
|
||||
return currentTime - startTime;
|
||||
}
|
||||
|
||||
/** @return tempo real decorrido em milissegundos */
|
||||
public long getWallClockElapsed() {
|
||||
return System.currentTimeMillis() - wallClockStart;
|
||||
}
|
||||
|
||||
/** Reinicia o relógio para o tempo inicial */
|
||||
public void reset() {
|
||||
this.currentTime = startTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("SimulationClock[time=%.3fs, elapsed=%.3fs]",
|
||||
currentTime, getElapsedTime());
|
||||
}
|
||||
}
|
||||
98
main/src/main/java/sd/des/SimulationEvent.java
Normal file
98
main/src/main/java/sd/des/SimulationEvent.java
Normal file
@@ -0,0 +1,98 @@
|
||||
package sd.des;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Evento discreto da simulação.
|
||||
*
|
||||
* <p>Unidade fundamental de execução num sistema DES:
|
||||
* <ul>
|
||||
* <li>timestamp - quando ocorre
|
||||
* <li>type - o que acontece
|
||||
* <li>payload - dados associados
|
||||
* <li>location - qual processo o trata
|
||||
* </ul>
|
||||
*/
|
||||
public class SimulationEvent implements Comparable<SimulationEvent>, Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final double timestamp;
|
||||
private final DESEventType type;
|
||||
private final Object payload;
|
||||
private final String location; // Process ID (e.g., "Cr1", "Coordinator", "Exit")
|
||||
|
||||
/**
|
||||
* Cria um novo evento de simulação.
|
||||
*
|
||||
* @param timestamp instante do evento (tempo de simulação em segundos)
|
||||
* @param type tipo de evento
|
||||
* @param payload dados associados (ex: objeto Vehicle)
|
||||
* @param location processo que trata o evento
|
||||
*/
|
||||
public SimulationEvent(double timestamp, DESEventType type, Object payload, String location) {
|
||||
this.timestamp = timestamp;
|
||||
this.type = type;
|
||||
this.payload = payload;
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
/** Cria evento sem localização (para eventos locais) */
|
||||
public SimulationEvent(double timestamp, DESEventType type, Object payload) {
|
||||
this(timestamp, type, payload, null);
|
||||
}
|
||||
|
||||
public double getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public DESEventType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public Object getPayload() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return location;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordena eventos por timestamp (mais cedo primeiro).
|
||||
* Em caso de empate, ordena por tipo para determinismo.
|
||||
*/
|
||||
@Override
|
||||
public int compareTo(SimulationEvent other) {
|
||||
int timeComparison = Double.compare(this.timestamp, other.timestamp);
|
||||
if (timeComparison != 0) {
|
||||
return timeComparison;
|
||||
}
|
||||
// Tie-breaker: order by event type name
|
||||
return this.type.name().compareTo(other.type.name());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("Event[t=%.3f, type=%s, location=%s]",
|
||||
timestamp, type, location);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) return true;
|
||||
if (!(obj instanceof SimulationEvent)) return false;
|
||||
SimulationEvent other = (SimulationEvent) obj;
|
||||
return Double.compare(timestamp, other.timestamp) == 0 &&
|
||||
type == other.type &&
|
||||
(location == null ? other.location == null : location.equals(other.location));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = 17;
|
||||
result = 31 * result + Double.hashCode(timestamp);
|
||||
result = 31 * result + type.hashCode();
|
||||
result = 31 * result + (location != null ? location.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
36
main/src/main/java/sd/des/TrafficLightEvent.java
Normal file
36
main/src/main/java/sd/des/TrafficLightEvent.java
Normal file
@@ -0,0 +1,36 @@
|
||||
package sd.des;
|
||||
|
||||
import sd.model.TrafficLight;
|
||||
|
||||
/**
|
||||
* Payload for traffic light change events.
|
||||
* Contains the traffic light and its direction.
|
||||
*/
|
||||
public class TrafficLightEvent {
|
||||
private final TrafficLight light;
|
||||
private final String direction;
|
||||
private final String intersectionId;
|
||||
|
||||
public TrafficLightEvent(TrafficLight light, String direction, String intersectionId) {
|
||||
this.light = light;
|
||||
this.direction = direction;
|
||||
this.intersectionId = intersectionId;
|
||||
}
|
||||
|
||||
public TrafficLight getLight() {
|
||||
return light;
|
||||
}
|
||||
|
||||
public String getDirection() {
|
||||
return direction;
|
||||
}
|
||||
|
||||
public String getIntersectionId() {
|
||||
return intersectionId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("TrafficLightEvent[%s-%s]", intersectionId, direction);
|
||||
}
|
||||
}
|
||||
213
main/src/main/java/sd/logging/EventLogger.java
Normal file
213
main/src/main/java/sd/logging/EventLogger.java
Normal file
@@ -0,0 +1,213 @@
|
||||
package sd.logging;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* Sistema de registo centralizado de eventos para a simulação distribuída.
|
||||
*
|
||||
* <p>Regista todos os eventos da simulação num ficheiro com timestamps e categorização.
|
||||
* Thread-safe e não-bloqueante para impacto mínimo na performance.</p>
|
||||
*/
|
||||
public class EventLogger {
|
||||
|
||||
private static EventLogger instance;
|
||||
private static final Object instanceLock = new Object();
|
||||
|
||||
private final PrintWriter writer;
|
||||
private final BlockingQueue<LogEntry> logQueue;
|
||||
private final Thread writerThread;
|
||||
private final AtomicBoolean running;
|
||||
private final SimpleDateFormat timestampFormat;
|
||||
private final long simulationStartMillis;
|
||||
|
||||
/** Construtor privado para padrão singleton */
|
||||
private EventLogger(String logFilePath) throws IOException {
|
||||
this.writer = new PrintWriter(new BufferedWriter(new FileWriter(logFilePath, false)), true);
|
||||
this.logQueue = new LinkedBlockingQueue<>(10000);
|
||||
this.running = new AtomicBoolean(true);
|
||||
this.timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
|
||||
this.simulationStartMillis = System.currentTimeMillis();
|
||||
|
||||
writer.println("=".repeat(80));
|
||||
writer.println("SIMULATION EVENT LOG");
|
||||
writer.println("Started: " + timestampFormat.format(new Date()));
|
||||
writer.println("=".repeat(80));
|
||||
writer.println();
|
||||
writer.printf("%-23s | %-8s | %-20s | %-15s | %s\n",
|
||||
"TIMESTAMP", "REL_TIME", "EVENT_TYPE", "COMPONENT", "DESCRIPTION");
|
||||
writer.println("-".repeat(80));
|
||||
writer.flush();
|
||||
|
||||
this.writerThread = new Thread(this::processLogQueue, "EventLogger-Writer");
|
||||
this.writerThread.setDaemon(true);
|
||||
this.writerThread.start();
|
||||
}
|
||||
|
||||
/** Obtém ou cria a instância singleton */
|
||||
public static EventLogger getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (instanceLock) {
|
||||
if (instance == null) {
|
||||
try {
|
||||
String logFile = "logs/simulation-events.log";
|
||||
java.nio.file.Files.createDirectories(
|
||||
java.nio.file.Paths.get("logs"));
|
||||
instance = new EventLogger(logFile);
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to initialize EventLogger: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize with custom log file path.
|
||||
*/
|
||||
public static void initialize(String logFilePath) throws IOException {
|
||||
synchronized (instanceLock) {
|
||||
if (instance != null) {
|
||||
instance.shutdown();
|
||||
}
|
||||
instance = new EventLogger(logFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs an event (non-blocking).
|
||||
*/
|
||||
public void log(EventType eventType, String component, String description) {
|
||||
if (!running.get()) return;
|
||||
|
||||
LogEntry entry = new LogEntry(
|
||||
System.currentTimeMillis(),
|
||||
eventType,
|
||||
component,
|
||||
description
|
||||
);
|
||||
|
||||
// Non-blocking offer - if queue is full, drop oldest
|
||||
if (!logQueue.offer(entry)) {
|
||||
// Queue full - this shouldn't happen with 10k buffer, but handle gracefully
|
||||
System.err.println("EventLogger queue full - dropping event: " + eventType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs an event with vehicle context.
|
||||
*/
|
||||
public void logVehicle(EventType eventType, String component, String vehicleId, String description) {
|
||||
log(eventType, component, "[" + vehicleId + "] " + description);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs an error event.
|
||||
*/
|
||||
public void logError(String component, String description, Exception e) {
|
||||
String fullDescription = description + (e != null ? ": " + e.getMessage() : "");
|
||||
log(EventType.ERROR, component, fullDescription);
|
||||
}
|
||||
|
||||
/**
|
||||
* Background thread that writes log entries to file.
|
||||
*/
|
||||
private void processLogQueue() {
|
||||
while (running.get() || !logQueue.isEmpty()) {
|
||||
try {
|
||||
LogEntry entry = logQueue.poll(100, java.util.concurrent.TimeUnit.MILLISECONDS);
|
||||
if (entry != null) {
|
||||
writeEntry(entry);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Flush remaining entries
|
||||
while (!logQueue.isEmpty()) {
|
||||
LogEntry entry = logQueue.poll();
|
||||
if (entry != null) {
|
||||
writeEntry(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a single log entry to file.
|
||||
*/
|
||||
private void writeEntry(LogEntry entry) {
|
||||
String timestamp = timestampFormat.format(new Date(entry.timestampMillis));
|
||||
double relativeTime = (entry.timestampMillis - simulationStartMillis) / 1000.0;
|
||||
|
||||
writer.printf("%-23s | %8.3fs | %-20s | %-15s | %s\n",
|
||||
timestamp,
|
||||
relativeTime,
|
||||
entry.eventType.toString(),
|
||||
truncate(entry.component, 15),
|
||||
entry.description
|
||||
);
|
||||
|
||||
// Flush periodically for real-time viewing
|
||||
if (logQueue.size() < 10) {
|
||||
writer.flush();
|
||||
}
|
||||
}
|
||||
|
||||
private String truncate(String str, int maxLength) {
|
||||
if (str == null) return "";
|
||||
return str.length() <= maxLength ? str : str.substring(0, maxLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuts down the logger and flushes all pending entries.
|
||||
*/
|
||||
public void shutdown() {
|
||||
if (!running.compareAndSet(true, false)) {
|
||||
return; // Already shut down
|
||||
}
|
||||
|
||||
try {
|
||||
// Wait for writer thread to finish
|
||||
writerThread.join(5000); // Wait up to 5 seconds
|
||||
|
||||
// Write footer
|
||||
writer.println();
|
||||
writer.println("-".repeat(80));
|
||||
writer.println("SIMULATION ENDED");
|
||||
writer.println("Ended: " + timestampFormat.format(new Date()));
|
||||
writer.println("=".repeat(80));
|
||||
|
||||
writer.close();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal class to represent a log entry.
|
||||
*/
|
||||
private static class LogEntry {
|
||||
final long timestampMillis;
|
||||
final EventType eventType;
|
||||
final String component;
|
||||
final String description;
|
||||
|
||||
LogEntry(long timestampMillis, EventType eventType, String component, String description) {
|
||||
this.timestampMillis = timestampMillis;
|
||||
this.eventType = eventType;
|
||||
this.component = component;
|
||||
this.description = description;
|
||||
}
|
||||
}
|
||||
}
|
||||
47
main/src/main/java/sd/logging/EventType.java
Normal file
47
main/src/main/java/sd/logging/EventType.java
Normal file
@@ -0,0 +1,47 @@
|
||||
package sd.logging;
|
||||
|
||||
/**
|
||||
* Tipos de eventos que podem ocorrer na simulação.
|
||||
* Usados para categorizar e filtrar logs.
|
||||
*/
|
||||
public enum EventType {
|
||||
VEHICLE_GENERATED("Vehicle Generated"),
|
||||
VEHICLE_ARRIVED("Vehicle Arrived"),
|
||||
VEHICLE_QUEUED("Vehicle Queued"),
|
||||
VEHICLE_DEPARTED("Vehicle Departed"),
|
||||
VEHICLE_EXITED("Vehicle Exited"),
|
||||
|
||||
LIGHT_CHANGED_GREEN("Light Changed to Green"),
|
||||
LIGHT_CHANGED_RED("Light Changed to Red"),
|
||||
LIGHT_REQUEST_GREEN("Light Requested Green"),
|
||||
LIGHT_RELEASE_GREEN("Light Released Green"),
|
||||
|
||||
SIMULATION_STARTED("Simulation Started"),
|
||||
SIMULATION_STOPPED("Simulation Stopped"),
|
||||
PROCESS_STARTED("Process Started"),
|
||||
PROCESS_STOPPED("Process Stopped"),
|
||||
|
||||
STATS_UPDATE("Statistics Update"),
|
||||
|
||||
CONNECTION_ESTABLISHED("Connection Established"),
|
||||
CONNECTION_LOST("Connection Lost"),
|
||||
MESSAGE_SENT("Message Sent"),
|
||||
MESSAGE_RECEIVED("Message Received"),
|
||||
|
||||
ERROR("Error");
|
||||
|
||||
private final String displayName;
|
||||
|
||||
EventType(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return displayName;
|
||||
}
|
||||
}
|
||||
331
main/src/main/java/sd/logging/VehicleTracer.java
Normal file
331
main/src/main/java/sd/logging/VehicleTracer.java
Normal file
@@ -0,0 +1,331 @@
|
||||
package sd.logging;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import sd.model.Vehicle;
|
||||
|
||||
/**
|
||||
* Rastreia e regista a viagem completa de veículos individuais.
|
||||
*
|
||||
* <p>Cria ficheiros de trace detalhados com:
|
||||
* <ul>
|
||||
* <li>Timestamps de todos os eventos
|
||||
* <li>Localizações (interseções)
|
||||
* <li>Tempos de espera em cada semáforo
|
||||
* <li>Tempos de travessia
|
||||
* <li>Tempo total no sistema
|
||||
* </ul>
|
||||
*/
|
||||
public class VehicleTracer {
|
||||
|
||||
private static VehicleTracer instance;
|
||||
private static final Object instanceLock = new Object();
|
||||
|
||||
private final Map<String, VehicleTrace> trackedVehicles;
|
||||
private final SimpleDateFormat timestampFormat;
|
||||
private final long simulationStartMillis;
|
||||
private final String traceDirectory;
|
||||
|
||||
/** Construtor privado (singleton) */
|
||||
private VehicleTracer(String traceDirectory) {
|
||||
this.trackedVehicles = new ConcurrentHashMap<>();
|
||||
this.timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
|
||||
this.simulationStartMillis = System.currentTimeMillis();
|
||||
this.traceDirectory = traceDirectory;
|
||||
|
||||
try {
|
||||
java.nio.file.Files.createDirectories(java.nio.file.Paths.get(traceDirectory));
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to create trace directory: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Obtém ou cria a instância singleton */
|
||||
public static VehicleTracer getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (instanceLock) {
|
||||
if (instance == null) {
|
||||
instance = new VehicleTracer("logs/traces");
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/** Inicializa com diretório de trace customizado */
|
||||
public static void initialize(String traceDirectory) {
|
||||
synchronized (instanceLock) {
|
||||
if (instance != null) {
|
||||
instance.shutdown();
|
||||
}
|
||||
instance = new VehicleTracer(traceDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Começa a rastrear um veículo específico.
|
||||
* Cria ficheiro de trace para este veículo.
|
||||
*/
|
||||
public void startTracking(String vehicleId) {
|
||||
if (trackedVehicles.containsKey(vehicleId)) {
|
||||
return; // Already tracking
|
||||
}
|
||||
|
||||
VehicleTrace trace = new VehicleTrace(vehicleId, traceDirectory);
|
||||
trackedVehicles.put(vehicleId, trace);
|
||||
|
||||
trace.logEvent("TRACKING_STARTED", "", "Started tracking vehicle " + vehicleId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops tracking a vehicle and closes its trace file.
|
||||
*/
|
||||
public void stopTracking(String vehicleId) {
|
||||
VehicleTrace trace = trackedVehicles.remove(vehicleId);
|
||||
if (trace != null) {
|
||||
trace.logEvent("TRACKING_STOPPED", "", "Stopped tracking vehicle " + vehicleId);
|
||||
trace.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a vehicle is being tracked.
|
||||
*/
|
||||
public boolean isTracking(String vehicleId) {
|
||||
return trackedVehicles.containsKey(vehicleId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs when a vehicle is generated.
|
||||
*/
|
||||
public void logGenerated(Vehicle vehicle) {
|
||||
if (!isTracking(vehicle.getId())) return;
|
||||
|
||||
VehicleTrace trace = trackedVehicles.get(vehicle.getId());
|
||||
if (trace != null) {
|
||||
trace.logEvent("GENERATED", "Coordinator",
|
||||
String.format("Type: %s, Entry Time: %.2fs, Route: %s",
|
||||
vehicle.getType(), vehicle.getEntryTime(), vehicle.getRoute()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs when a vehicle arrives at an intersection.
|
||||
*/
|
||||
public void logArrival(String vehicleId, String intersection, double simulationTime) {
|
||||
if (!isTracking(vehicleId)) return;
|
||||
|
||||
VehicleTrace trace = trackedVehicles.get(vehicleId);
|
||||
if (trace != null) {
|
||||
trace.logEvent("ARRIVED", intersection,
|
||||
String.format("Arrived at %s (sim time: %.2fs)", intersection, simulationTime));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs when a vehicle is queued at a traffic light.
|
||||
*/
|
||||
public void logQueued(String vehicleId, String intersection, String direction, int queuePosition) {
|
||||
if (!isTracking(vehicleId)) return;
|
||||
|
||||
VehicleTrace trace = trackedVehicles.get(vehicleId);
|
||||
if (trace != null) {
|
||||
trace.logEvent("QUEUED", intersection,
|
||||
String.format("Queued at %s-%s (position: %d)", intersection, direction, queuePosition));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs when a vehicle starts waiting at a red light.
|
||||
*/
|
||||
public void logWaitingStart(String vehicleId, String intersection, String direction) {
|
||||
if (!isTracking(vehicleId)) return;
|
||||
|
||||
VehicleTrace trace = trackedVehicles.get(vehicleId);
|
||||
if (trace != null) {
|
||||
trace.logEvent("WAITING_START", intersection,
|
||||
String.format("Started waiting at %s-%s (light is RED)", intersection, direction));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs when a vehicle finishes waiting (light turns green).
|
||||
*/
|
||||
public void logWaitingEnd(String vehicleId, String intersection, String direction, double waitTime) {
|
||||
if (!isTracking(vehicleId)) return;
|
||||
|
||||
VehicleTrace trace = trackedVehicles.get(vehicleId);
|
||||
if (trace != null) {
|
||||
trace.logEvent("WAITING_END", intersection,
|
||||
String.format("Finished waiting at %s-%s (waited %.2fs)", intersection, direction, waitTime));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs when a vehicle starts crossing an intersection.
|
||||
*/
|
||||
public void logCrossingStart(String vehicleId, String intersection, String direction) {
|
||||
if (!isTracking(vehicleId)) return;
|
||||
|
||||
VehicleTrace trace = trackedVehicles.get(vehicleId);
|
||||
if (trace != null) {
|
||||
trace.logEvent("CROSSING_START", intersection,
|
||||
String.format("Started crossing %s-%s (light is GREEN)", intersection, direction));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs when a vehicle finishes crossing an intersection.
|
||||
*/
|
||||
public void logCrossingEnd(String vehicleId, String intersection, double crossingTime) {
|
||||
if (!isTracking(vehicleId)) return;
|
||||
|
||||
VehicleTrace trace = trackedVehicles.get(vehicleId);
|
||||
if (trace != null) {
|
||||
trace.logEvent("CROSSING_END", intersection,
|
||||
String.format("Finished crossing %s (took %.2fs)", intersection, crossingTime));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs when a vehicle departs from an intersection.
|
||||
*/
|
||||
public void logDeparture(String vehicleId, String intersection, String nextDestination) {
|
||||
if (!isTracking(vehicleId)) return;
|
||||
|
||||
VehicleTrace trace = trackedVehicles.get(vehicleId);
|
||||
if (trace != null) {
|
||||
trace.logEvent("DEPARTED", intersection,
|
||||
String.format("Departed from %s toward %s", intersection, nextDestination));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs when a vehicle exits the system.
|
||||
*/
|
||||
public void logExit(Vehicle vehicle, double systemTime) {
|
||||
if (!isTracking(vehicle.getId())) return;
|
||||
|
||||
VehicleTrace trace = trackedVehicles.get(vehicle.getId());
|
||||
if (trace != null) {
|
||||
trace.logEvent("EXITED", "Exit Node",
|
||||
String.format("Exited system - Total time: %.2fs, Waiting: %.2fs, Crossing: %.2fs",
|
||||
systemTime, vehicle.getTotalWaitingTime(), vehicle.getTotalCrossingTime()));
|
||||
|
||||
// Write summary
|
||||
trace.writeSummary(vehicle, systemTime);
|
||||
|
||||
// Stop tracking and close file
|
||||
stopTracking(vehicle.getId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuts down the tracer and closes all trace files.
|
||||
*/
|
||||
public void shutdown() {
|
||||
for (VehicleTrace trace : trackedVehicles.values()) {
|
||||
trace.close();
|
||||
}
|
||||
trackedVehicles.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal class to handle tracing for a single vehicle.
|
||||
*/
|
||||
private class VehicleTrace {
|
||||
private final String vehicleId;
|
||||
private final PrintWriter writer;
|
||||
private final long traceStartMillis;
|
||||
|
||||
VehicleTrace(String vehicleId, String directory) {
|
||||
this.vehicleId = vehicleId;
|
||||
this.traceStartMillis = System.currentTimeMillis();
|
||||
|
||||
PrintWriter w = null;
|
||||
try {
|
||||
String filename = String.format("%s/vehicle-%s.trace", directory, vehicleId);
|
||||
w = new PrintWriter(new BufferedWriter(new FileWriter(filename, false)), true);
|
||||
|
||||
// Write header
|
||||
w.println("=".repeat(80));
|
||||
w.println("VEHICLE TRACE: " + vehicleId);
|
||||
w.println("Trace Started: " + timestampFormat.format(new Date()));
|
||||
w.println("=".repeat(80));
|
||||
w.println();
|
||||
w.printf("%-23s | %-8s | %-15s | %-15s | %s\n",
|
||||
"TIMESTAMP", "REL_TIME", "EVENT", "LOCATION", "DESCRIPTION");
|
||||
w.println("-".repeat(80));
|
||||
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to create trace file for " + vehicleId + ": " + e.getMessage());
|
||||
}
|
||||
|
||||
this.writer = w;
|
||||
}
|
||||
|
||||
void logEvent(String eventType, String location, String description) {
|
||||
if (writer == null) return;
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
String timestamp = timestampFormat.format(new Date(now));
|
||||
double relativeTime = (now - traceStartMillis) / 1000.0;
|
||||
|
||||
writer.printf("%-23s | %8.3fs | %-15s | %-15s | %s\n",
|
||||
timestamp,
|
||||
relativeTime,
|
||||
truncate(eventType, 15),
|
||||
truncate(location, 15),
|
||||
description
|
||||
);
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
void writeSummary(Vehicle vehicle, double systemTime) {
|
||||
if (writer == null) return;
|
||||
|
||||
writer.println();
|
||||
writer.println("=".repeat(80));
|
||||
writer.println("JOURNEY SUMMARY");
|
||||
writer.println("=".repeat(80));
|
||||
writer.println("Vehicle ID: " + vehicle.getId());
|
||||
writer.println("Vehicle Type: " + vehicle.getType());
|
||||
writer.println("Route: " + vehicle.getRoute());
|
||||
writer.println();
|
||||
writer.printf("Entry Time: %.2f seconds\n", vehicle.getEntryTime());
|
||||
writer.printf("Total System Time: %.2f seconds\n", systemTime);
|
||||
writer.printf("Total Waiting Time: %.2f seconds (%.1f%%)\n",
|
||||
vehicle.getTotalWaitingTime(),
|
||||
100.0 * vehicle.getTotalWaitingTime() / systemTime);
|
||||
writer.printf("Total Crossing Time: %.2f seconds (%.1f%%)\n",
|
||||
vehicle.getTotalCrossingTime(),
|
||||
100.0 * vehicle.getTotalCrossingTime() / systemTime);
|
||||
writer.printf("Travel Time: %.2f seconds (%.1f%%)\n",
|
||||
systemTime - vehicle.getTotalWaitingTime() - vehicle.getTotalCrossingTime(),
|
||||
100.0 * (systemTime - vehicle.getTotalWaitingTime() - vehicle.getTotalCrossingTime()) / systemTime);
|
||||
writer.println("=".repeat(80));
|
||||
}
|
||||
|
||||
void close() {
|
||||
if (writer != null) {
|
||||
writer.println();
|
||||
writer.println("-".repeat(80));
|
||||
writer.println("END OF TRACE");
|
||||
writer.println("=".repeat(80));
|
||||
writer.close();
|
||||
}
|
||||
}
|
||||
|
||||
private String truncate(String str, int maxLength) {
|
||||
if (str == null) return "";
|
||||
return str.length() <= maxLength ? str : str.substring(0, maxLength);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package sd.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Represents an event in the discrete event simulation.
|
||||
* Events are ordered by timestamp for sequential processing.
|
||||
*/
|
||||
public class Event implements Comparable<Event>, Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final double timestamp; // Time when the event occurs
|
||||
private final EventType type;
|
||||
private final Object data; // Data associated with the event (e.g., Vehicle, traffic light id, etc.)
|
||||
private final String location; // Intersection or location where the event occurs
|
||||
|
||||
public Event(double timestamp, EventType type, Object data, String location) {
|
||||
this.timestamp = timestamp;
|
||||
this.type = type;
|
||||
this.data = data;
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
public Event(double timestamp, EventType type, Object data) {
|
||||
this(timestamp, type, data, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Event other) {
|
||||
// Sort by timestamp (earlier events have priority)
|
||||
int cmp = Double.compare(this.timestamp, other.timestamp);
|
||||
if (cmp == 0) {
|
||||
// If timestamps are equal, sort by event type
|
||||
return this.type.compareTo(other.type);
|
||||
}
|
||||
return cmp;
|
||||
}
|
||||
|
||||
// Getters
|
||||
public double getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public EventType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public Object getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("Event{t=%.2f, type=%s, loc=%s}",
|
||||
timestamp, type, location);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package sd.model;
|
||||
|
||||
/**
|
||||
* Enumeration representing event types in the simulation.
|
||||
*/
|
||||
public enum EventType {
|
||||
VEHICLE_ARRIVAL, // Vehicle arrives at an intersection
|
||||
TRAFFIC_LIGHT_CHANGE, // Traffic light changes state (green/red)
|
||||
CROSSING_START, // Vehicle starts crossing the intersection
|
||||
CROSSING_END, // Vehicle finishes crossing
|
||||
VEHICLE_GENERATION, // New vehicle is generated in the system
|
||||
STATISTICS_UPDATE // Time to send statistics to dashboard
|
||||
}
|
||||
@@ -6,23 +6,52 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Represents an intersection in the traffic simulation.
|
||||
* Representa uma interseção na simulação de tráfego.
|
||||
*
|
||||
* Each intersection coordinates multiple traffic lights - one for each direction -
|
||||
* and handles routing vehicles based on their next destination.
|
||||
* <p>Uma interseção funciona como um nó central da rede. Não controla lógica diretamente,
|
||||
* mas gere um conjunto de semáforos ({@link TrafficLight}).</p>
|
||||
*
|
||||
* <p>Responsabilidades principais:</p>
|
||||
* <ul>
|
||||
* <li>Manter um {@link TrafficLight} para cada direção (Norte, Este, etc.)</li>
|
||||
* <li>Gerir uma tabela de encaminhamento que mapeia destinos para direções</li>
|
||||
* <li>Receber veículos e colocá-los na fila do semáforo correto</li>
|
||||
* <li>Acompanhar estatísticas agregadas do tráfego</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class Intersection {
|
||||
|
||||
// Identity and configuration
|
||||
private final String id; // ex. "Cr1", "Cr2"
|
||||
private final Map<String, TrafficLight> trafficLights; // direction -> light
|
||||
private final Map<String, String> routing; // destination -> direction
|
||||
/** Identificador único da interseção (ex: "Cr1", "Cr2") */
|
||||
private final String id;
|
||||
|
||||
// Stats
|
||||
/**
|
||||
* Mapa com todos os semáforos desta interseção.
|
||||
* Chave: Direção (String, ex: "Norte", "Este")
|
||||
* Valor: Objeto {@link TrafficLight} correspondente
|
||||
*/
|
||||
private final Map<String, TrafficLight> trafficLights;
|
||||
|
||||
/**
|
||||
* Tabela de encaminhamento da interseção.
|
||||
* Chave: Próximo destino (String, ex: "Cr3", "S" para saída)
|
||||
* Valor: Direção que o veículo deve tomar nesta interseção
|
||||
*/
|
||||
private final Map<String, String> routing;
|
||||
/** Número total de veículos recebidos por esta interseção */
|
||||
private int totalVehiclesReceived;
|
||||
|
||||
/** Número total de veículos que partiram desta interseção */
|
||||
private int totalVehiclesSent;
|
||||
|
||||
/** Média acumulada do tempo de espera dos veículos nesta interseção */
|
||||
private double averageWaitingTime;
|
||||
|
||||
/**
|
||||
* Cria uma nova interseção.
|
||||
* Inicializa mapas vazios para semáforos e encaminhamento.
|
||||
*
|
||||
* @param id identificador único da interseção (ex: "Cr1")
|
||||
*/
|
||||
public Intersection(String id) {
|
||||
this.id = id;
|
||||
this.trafficLights = new HashMap<>();
|
||||
@@ -33,91 +62,166 @@ public class Intersection {
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a traffic light under this intersection.
|
||||
* The light is identified by its direction (ex., "North", "East").
|
||||
* Regista um novo semáforo nesta interseção.
|
||||
* O semáforo é mapeado pela sua direção.
|
||||
*
|
||||
* @param trafficLight o semáforo a adicionar
|
||||
*/
|
||||
public void addTrafficLight(TrafficLight trafficLight) {
|
||||
trafficLights.put(trafficLight.getDirection(), trafficLight);
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines how vehicles should be routed through this intersection.
|
||||
* Define uma regra de encaminhamento para esta interseção.
|
||||
*
|
||||
* @param nextDestination The next intersection or exit on the vehicle's route
|
||||
* @param direction The direction (traffic light) vehicles should take
|
||||
* <p>Por exemplo, {@code configureRoute("Cr3", "Este")} significa:
|
||||
* "Qualquer veículo que chegue aqui com destino 'Cr3' deve ser enviado
|
||||
* para a fila do semáforo da direção Este."</p>
|
||||
*
|
||||
* @param nextDestination ID da próxima interseção ou saída (ex: "Cr3", "S")
|
||||
* @param direction direção (e respetivo semáforo) a usar nesta interseção
|
||||
*/
|
||||
public void configureRoute(String nextDestination, String direction) {
|
||||
routing.put(nextDestination, direction);
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts an incoming vehicle and places it in the correct queue.
|
||||
* If the route or traffic light can't be found, logs an error.
|
||||
* Recebe um veículo e coloca-o na fila correta.
|
||||
*
|
||||
* <p>Passos executados:</p>
|
||||
* <ol>
|
||||
* <li>Incrementa o contador de veículos recebidos</li>
|
||||
* <li>Obtém o próximo destino do veículo</li>
|
||||
* <li>Consulta a tabela de encaminhamento para encontrar a direção</li>
|
||||
* <li>Adiciona o veículo à fila do semáforo apropriado</li>
|
||||
* </ol>
|
||||
*
|
||||
* @param vehicle o veículo que chega à interseção
|
||||
*/
|
||||
public void receiveVehicle(Vehicle vehicle) {
|
||||
totalVehiclesReceived++;
|
||||
|
||||
// Note: Route advancement is handled by SimulationEngine.handleVehicleArrival()
|
||||
// before calling this method, so we don't advance here.
|
||||
|
||||
String nextDestination = vehicle.getCurrentDestination();
|
||||
|
||||
// Check if vehicle reached final destination
|
||||
if (nextDestination == null) {
|
||||
System.out.printf("[%s] Vehicle %s reached final destination%n",
|
||||
this.id, vehicle.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
String direction = routing.get(nextDestination);
|
||||
|
||||
if (direction != null && trafficLights.containsKey(direction)) {
|
||||
// Found a valid route and light, add vehicle to the queue
|
||||
trafficLights.get(direction).addVehicle(vehicle);
|
||||
} else {
|
||||
// Routing error: No rule for this destination or no light for that direction
|
||||
System.err.printf(
|
||||
"Routing error: could not place vehicle %s (destination: %s)%n",
|
||||
vehicle.getId(), nextDestination
|
||||
"Routing error at %s: could not place vehicle %s (destination: %s, found direction: %s)%n",
|
||||
this.id, vehicle.getId(), nextDestination, direction
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the traffic light controlling the given direction, if any. */
|
||||
/**
|
||||
* Retorna a direção que um veículo deve tomar para alcançar um destino.
|
||||
*
|
||||
* @param destination o próximo destino (ex: "Cr3", "S")
|
||||
* @return a direção (ex: "Este"), ou null se não houver rota configurada
|
||||
*/
|
||||
public String getDirectionForDestination(String destination) {
|
||||
return routing.get(destination);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retorna o semáforo que controla uma determinada direção.
|
||||
*
|
||||
* @param direction a direção (ex: "Norte")
|
||||
* @return o objeto {@link TrafficLight}, ou null se não existir
|
||||
*/
|
||||
public TrafficLight getTrafficLight(String direction) {
|
||||
return trafficLights.get(direction);
|
||||
}
|
||||
|
||||
/** Returns all traffic lights belonging to this intersection. */
|
||||
/**
|
||||
* Retorna uma lista com todos os semáforos desta interseção.
|
||||
*
|
||||
* @return uma nova {@link List} com todos os semáforos
|
||||
*/
|
||||
public List<TrafficLight> getTrafficLights() {
|
||||
return new ArrayList<>(trafficLights.values());
|
||||
}
|
||||
|
||||
/** Returns the total number of vehicles currently queued across all directions. */
|
||||
/**
|
||||
* Retorna o número total de veículos em fila em todos os semáforos.
|
||||
* Usa Java Stream API para somar os tamanhos de todas as filas.
|
||||
*
|
||||
* @return a soma dos tamanhos de todas as filas
|
||||
*/
|
||||
public int getTotalQueueSize() {
|
||||
return trafficLights.values().stream()
|
||||
.mapToInt(TrafficLight::getQueueSize)
|
||||
.sum();
|
||||
}
|
||||
|
||||
// --- Stats and getters ---
|
||||
|
||||
/**
|
||||
* @return o identificador único desta interseção
|
||||
*/
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return o número total de veículos que chegaram a esta interseção
|
||||
*/
|
||||
public int getTotalVehiclesReceived() {
|
||||
return totalVehiclesReceived;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return o número total de veículos que partiram desta interseção
|
||||
*/
|
||||
public int getTotalVehiclesSent() {
|
||||
return totalVehiclesSent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Incrementa o contador de veículos que partiram com sucesso.
|
||||
* Tipicamente chamado após um veículo completar a travessia.
|
||||
*/
|
||||
public void incrementVehiclesSent() {
|
||||
totalVehiclesSent++;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return a média do tempo de espera dos veículos nesta interseção
|
||||
*/
|
||||
public double getAverageWaitingTime() {
|
||||
return averageWaitingTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the running average waiting time with a new sample.
|
||||
* Atualiza a média do tempo de espera com uma nova amostra.
|
||||
* Usa a fórmula: Nova Média = (Média Antiga * (N-1) + Novo Valor) / N
|
||||
*
|
||||
* @param newTime tempo de espera (em segundos) do veículo que acabou de partir
|
||||
*/
|
||||
public void updateAverageWaitingTime(double newTime) {
|
||||
// Weighted incremental average (avoids recalculating from scratch)
|
||||
averageWaitingTime = (averageWaitingTime * (totalVehiclesSent - 1) + newTime)
|
||||
/ totalVehiclesSent;
|
||||
if (totalVehiclesSent > 0) {
|
||||
averageWaitingTime = (averageWaitingTime * (totalVehiclesSent - 1) + newTime)
|
||||
/ totalVehiclesSent;
|
||||
} else if (totalVehiclesSent == 1) {
|
||||
averageWaitingTime = newTime;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return representação textual do estado atual da interseção
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format(
|
||||
|
||||
143
main/src/main/java/sd/model/Message.java
Normal file
143
main/src/main/java/sd/model/Message.java
Normal file
@@ -0,0 +1,143 @@
|
||||
package sd.model;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import sd.protocol.MessageProtocol;
|
||||
|
||||
/**
|
||||
* Representa uma mensagem trocada entre processos na simulação distribuída.
|
||||
*
|
||||
* <p>Cada mensagem tem um ID único, tipo, remetente, destino e payload.
|
||||
* Implementa {@link MessageProtocol} que estende Serializable para transmissão pela rede.</p>
|
||||
*/
|
||||
public class Message implements MessageProtocol {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** Identificador único desta mensagem */
|
||||
private final String messageId;
|
||||
|
||||
/** Tipo desta mensagem (ex: VEHICLE_TRANSFER, STATS_UPDATE) */
|
||||
private final MessageType type;
|
||||
|
||||
/** Identificador do processo que enviou esta mensagem */
|
||||
private final String senderId;
|
||||
|
||||
/** Identificador do processo de destino (pode ser null para broadcast) */
|
||||
private final String destinationId;
|
||||
|
||||
/** Dados a serem transmitidos (o tipo depende do tipo de mensagem) */
|
||||
private final Object payload;
|
||||
|
||||
/** Timestamp de criação da mensagem (tempo de simulação ou real) */
|
||||
private final long timestamp;
|
||||
|
||||
/**
|
||||
* Cria uma nova mensagem com todos os parâmetros.
|
||||
*
|
||||
* @param type tipo da mensagem
|
||||
* @param senderId ID do processo remetente
|
||||
* @param destinationId ID do processo de destino (null para broadcast)
|
||||
* @param payload conteúdo da mensagem
|
||||
* @param timestamp timestamp de criação da mensagem
|
||||
*/
|
||||
public Message(MessageType type, String senderId, String destinationId,
|
||||
Object payload, long timestamp) {
|
||||
this.messageId = UUID.randomUUID().toString();
|
||||
this.type = type;
|
||||
this.senderId = senderId;
|
||||
this.destinationId = destinationId;
|
||||
this.payload = payload;
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cria uma nova mensagem usando o tempo atual do sistema como timestamp.
|
||||
*
|
||||
* @param type tipo da mensagem
|
||||
* @param senderId ID do processo remetente
|
||||
* @param destinationId ID do processo de destino
|
||||
* @param payload conteúdo da mensagem
|
||||
*/
|
||||
public Message(MessageType type, String senderId, String destinationId, Object payload) {
|
||||
this(type, senderId, destinationId, payload, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
/**
|
||||
* Cria uma mensagem de broadcast (sem destino específico).
|
||||
*
|
||||
* @param type tipo da mensagem
|
||||
* @param senderId ID do processo remetente
|
||||
* @param payload conteúdo da mensagem
|
||||
*/
|
||||
public Message(MessageType type, String senderId, Object payload) {
|
||||
this(type, senderId, null, payload, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
//Getters
|
||||
|
||||
public String getMessageId() {
|
||||
return messageId;
|
||||
}
|
||||
|
||||
public MessageType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getSenderId() {
|
||||
return senderId;
|
||||
}
|
||||
|
||||
public String getDestinationId() {
|
||||
return destinationId;
|
||||
}
|
||||
|
||||
public Object getPayload() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if this is a broadcast message (no specific destination).
|
||||
*
|
||||
* @return true if destinationId is null, false otherwise
|
||||
*/
|
||||
public boolean isBroadcast() {
|
||||
return destinationId == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the payload cast to a specific type.
|
||||
* Use with caution and ensure type safety.
|
||||
*
|
||||
* @param <T> The expected payload type
|
||||
* @return The payload cast to type T
|
||||
* @throws ClassCastException if the payload is not of type T
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T getPayloadAs(Class<T> clazz) {
|
||||
return (T) payload;
|
||||
}
|
||||
|
||||
// Impl MessageProtocol interface
|
||||
@Override
|
||||
public String getSourceNode() {
|
||||
return senderId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDestinationNode() {
|
||||
return destinationId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("Message[id=%s, type=%s, from=%s, to=%s, timestamp=%d]",
|
||||
messageId, type, senderId,
|
||||
destinationId != null ? destinationId : "BROADCAST",
|
||||
timestamp);
|
||||
}
|
||||
}
|
||||
43
main/src/main/java/sd/model/MessageType.java
Normal file
43
main/src/main/java/sd/model/MessageType.java
Normal file
@@ -0,0 +1,43 @@
|
||||
package sd.model;
|
||||
|
||||
/**
|
||||
* Enumeração que representa todos os tipos de mensagens possíveis para
|
||||
* comunicação distribuída.
|
||||
* Estes tipos são usados para a comunicação entre processos dos diferentes
|
||||
* componentes
|
||||
* do sistema de simulação de tráfego distribuído.
|
||||
*/
|
||||
public enum MessageType {
|
||||
|
||||
/**
|
||||
* Mensagem para transferir um veículo entre interseções ou processos.
|
||||
* Payload: Objeto Vehicle com o estado atual
|
||||
*/
|
||||
VEHICLE_TRANSFER,
|
||||
|
||||
/**
|
||||
* Mensagem para atualizar estatísticas em todo o sistema distribuído.
|
||||
* Payload: Dados estatísticos (tempos de espera, tamanhos de fila, etc.)
|
||||
*/
|
||||
STATS_UPDATE,
|
||||
|
||||
/**
|
||||
* Mensagem para sincronizar a hora de início da simulação em todos os
|
||||
* processos.
|
||||
* Payload: Timestamp de início (long milissegundos)
|
||||
*/
|
||||
SIMULATION_START,
|
||||
|
||||
/**
|
||||
* Mensagem para notificar sobre a geração de um novo veículo.
|
||||
* Payload: Parâmetros de geração do veículo
|
||||
*/
|
||||
VEHICLE_SPAWN,
|
||||
|
||||
/**
|
||||
* Mensagem para sinalizar o encerramento de um processo.
|
||||
* Payload: ID do processo e motivo
|
||||
*/
|
||||
SHUTDOWN,
|
||||
|
||||
}
|
||||
@@ -1,40 +1,71 @@
|
||||
package sd.model;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
/**
|
||||
* Represents a single traffic light controlling one direction at an intersection.
|
||||
* Representa um semáforo numa interseção.
|
||||
*
|
||||
* Each light maintains its own queue of vehicles and alternates between
|
||||
* green and red states. It's designed to be thread-safe (maybe...), so multiple
|
||||
* threads (like vehicles or controllers) can safely interact with it.
|
||||
* <p>Cada semáforo controla uma direção específica e mantém uma fila de veículos à espera.
|
||||
* Alterna entre os estados VERDE e VERMELHO de acordo com a temporização configurada.</p>
|
||||
*
|
||||
* <p><strong>Thread-safety:</strong> Usa locks para permitir acesso concorrente seguro entre
|
||||
* a thread de processamento de eventos e as threads de I/O de rede.</p>
|
||||
*/
|
||||
public class TrafficLight {
|
||||
|
||||
// Identity and configuration
|
||||
private final String id; // ex. "Cr1-N"
|
||||
private final String direction; // ex. "North", "South", etc.
|
||||
/** Identificador único do semáforo (ex: "Cr1-N") */
|
||||
private final String id;
|
||||
|
||||
/** Direção que este semáforo controla (ex: "Norte", "Sul") */
|
||||
private final String direction;
|
||||
|
||||
/** Estado atual do semáforo (VERDE ou VERMELHO) */
|
||||
private TrafficLightState state;
|
||||
|
||||
// Vehicle management
|
||||
/** Fila de veículos à espera neste semáforo */
|
||||
private final Queue<Vehicle> queue;
|
||||
|
||||
// Synchronization primitives
|
||||
/**
|
||||
* Lock para proteger o estado mutável ({@link #queue} e {@link #state})
|
||||
* de acesso concorrente.
|
||||
*/
|
||||
private final Lock lock;
|
||||
|
||||
/** Variável de condição para sinalizar adição de veículos (uso futuro) */
|
||||
private final Condition vehicleAdded;
|
||||
|
||||
/** Variável de condição para sinalizar que o semáforo ficou verde (uso futuro) */
|
||||
private final Condition lightGreen;
|
||||
|
||||
// Timing configuration (seconds)
|
||||
/** Duração (segundos) que o semáforo permanece VERDE */
|
||||
private double greenTime;
|
||||
|
||||
/** Duração (segundos) que o semáforo permanece VERMELHO */
|
||||
private double redTime;
|
||||
|
||||
// Basic stats
|
||||
/** Número total de veículos processados por este semáforo */
|
||||
private int totalVehiclesProcessed;
|
||||
|
||||
/**
|
||||
* Regista quando os veículos chegam ao semáforo para cálculo do tempo de espera.
|
||||
* Mapeia ID do veículo para timestamp de chegada (milissegundos).
|
||||
*/
|
||||
private final Map<String, Long> vehicleArrivalTimes;
|
||||
|
||||
/**
|
||||
* Cria um novo semáforo.
|
||||
*
|
||||
* @param id identificador único (ex: "Cr1-N")
|
||||
* @param direction direção controlada (ex: "Norte")
|
||||
* @param greenTime duração do estado VERDE em segundos
|
||||
* @param redTime duração do estado VERMELHO em segundos
|
||||
*/
|
||||
public TrafficLight(String id, String direction, double greenTime, double redTime) {
|
||||
this.id = id;
|
||||
this.direction = direction;
|
||||
@@ -47,17 +78,23 @@ public class TrafficLight {
|
||||
|
||||
this.greenTime = greenTime;
|
||||
this.redTime = redTime;
|
||||
this.vehicleArrivalTimes = new HashMap<>();
|
||||
this.totalVehiclesProcessed = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a vehicle to the waiting queue.
|
||||
* Signals any waiting threads that a new vehicle has arrived.
|
||||
* Coloca um veículo na fila deste semáforo.
|
||||
*
|
||||
* Registamos a hora de chegada para podermos calcular mais tarde quanto tempo o
|
||||
* veículo esperou.
|
||||
*
|
||||
* @param vehicle O veículo que chega ao semáforo.
|
||||
*/
|
||||
public void addVehicle(Vehicle vehicle) {
|
||||
lock.lock();
|
||||
try {
|
||||
queue.offer(vehicle);
|
||||
vehicleArrivalTimes.put(vehicle.getId(), System.currentTimeMillis());
|
||||
vehicleAdded.signalAll();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
@@ -65,15 +102,32 @@ public class TrafficLight {
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to let one vehicle pass through.
|
||||
* Only works if the light is green; otherwise returns null.
|
||||
* Remove um veículo da fila para travessia.
|
||||
*
|
||||
* <p>Só remove se:</p>
|
||||
* <ul>
|
||||
* <li>O semáforo estiver VERDE</li>
|
||||
* <li>Existir pelo menos um veículo na fila</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Atualiza automaticamente as estatísticas de tempo de espera do veículo.</p>
|
||||
*
|
||||
* @return o veículo que vai atravessar, ou null se não for possível
|
||||
*/
|
||||
public Vehicle removeVehicle() {
|
||||
lock.lock();
|
||||
try {
|
||||
if (state == TrafficLightState.GREEN && !queue.isEmpty()) {
|
||||
Vehicle vehicle = queue.poll();
|
||||
totalVehiclesProcessed++;
|
||||
if (vehicle != null) {
|
||||
totalVehiclesProcessed++;
|
||||
|
||||
Long arrivalTime = vehicleArrivalTimes.remove(vehicle.getId());
|
||||
if (arrivalTime != null) {
|
||||
double waitTimeSeconds = (System.currentTimeMillis() - arrivalTime) / 1000.0;
|
||||
vehicle.addWaitingTime(waitTimeSeconds);
|
||||
}
|
||||
}
|
||||
return vehicle;
|
||||
}
|
||||
return null;
|
||||
@@ -83,9 +137,9 @@ public class TrafficLight {
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the light’s state (ex., RED -> GREEN).
|
||||
* When the light turns green, waiting threads are notified.
|
||||
* ¯\_(ツ)_/¯
|
||||
* Muda o estado do semáforo.
|
||||
*
|
||||
* @param newState novo estado (VERDE ou VERMELHO)
|
||||
*/
|
||||
public void changeState(TrafficLightState newState) {
|
||||
lock.lock();
|
||||
@@ -99,7 +153,12 @@ public class TrafficLight {
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns how many vehicles are currently queued. */
|
||||
/**
|
||||
* Retorna quantos veículos estão atualmente na fila.
|
||||
* Método thread-safe.
|
||||
*
|
||||
* @return tamanho da fila
|
||||
*/
|
||||
public int getQueueSize() {
|
||||
lock.lock();
|
||||
try {
|
||||
@@ -109,7 +168,12 @@ public class TrafficLight {
|
||||
}
|
||||
}
|
||||
|
||||
/** Checks whether there are no vehicles waiting. */
|
||||
/**
|
||||
* Verifica se a fila está vazia.
|
||||
* Método thread-safe.
|
||||
*
|
||||
* @return {@code true} se não houver veículos, {@code false} caso contrário
|
||||
*/
|
||||
public boolean isQueueEmpty() {
|
||||
lock.lock();
|
||||
try {
|
||||
@@ -119,16 +183,22 @@ public class TrafficLight {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Getters & Setters ---
|
||||
|
||||
/** @return identificador único do semáforo */
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/** @return direção controlada por este semáforo */
|
||||
public String getDirection() {
|
||||
return direction;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém o estado atual do semáforo.
|
||||
* Método thread-safe.
|
||||
*
|
||||
* @return estado atual (VERDE ou VERMELHO)
|
||||
*/
|
||||
public TrafficLightState getState() {
|
||||
lock.lock();
|
||||
try {
|
||||
@@ -138,43 +208,60 @@ public class TrafficLight {
|
||||
}
|
||||
}
|
||||
|
||||
/** @return duração configurada do sinal verde em segundos */
|
||||
public double getGreenTime() {
|
||||
return greenTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a duração do sinal verde.
|
||||
*
|
||||
* @param greenTime nova duração em segundos
|
||||
*/
|
||||
public void setGreenTime(double greenTime) {
|
||||
this.greenTime = greenTime;
|
||||
}
|
||||
|
||||
/** @return duração configurada do sinal vermelho em segundos */
|
||||
public double getRedTime() {
|
||||
return redTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a duração do sinal vermelho.
|
||||
*
|
||||
* @param redTime nova duração em segundos
|
||||
*/
|
||||
public void setRedTime(double redTime) {
|
||||
this.redTime = redTime;
|
||||
}
|
||||
|
||||
/** @return número total de veículos processados por este semáforo */
|
||||
public int getTotalVehiclesProcessed() {
|
||||
return totalVehiclesProcessed;
|
||||
}
|
||||
|
||||
/** @return objeto {@link Lock} para sincronização avançada */
|
||||
public Lock getLock() {
|
||||
return lock;
|
||||
}
|
||||
|
||||
/** @return condição para adição de veículos */
|
||||
public Condition getVehicleAdded() {
|
||||
return vehicleAdded;
|
||||
}
|
||||
|
||||
/** @return condição para semáforo ficar verde */
|
||||
public Condition getLightGreen() {
|
||||
return lightGreen;
|
||||
}
|
||||
|
||||
/** @return representação textual do estado atual do semáforo */
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format(
|
||||
"TrafficLight{id='%s', direction='%s', state=%s, queueSize=%d}",
|
||||
id, direction, state, getQueueSize()
|
||||
"TrafficLight{id='%s', direction='%s', state=%s, queueSize=%d}",
|
||||
id, direction, getState(), getQueueSize()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
package sd.model;
|
||||
|
||||
/**
|
||||
* Enumeration representing the state of a traffic light.
|
||||
* Estados possíveis de um semáforo ({@link TrafficLight}).
|
||||
*/
|
||||
public enum TrafficLightState {
|
||||
GREEN, // Allows passage
|
||||
RED // Blocks passage
|
||||
|
||||
/** Sinal verde - veículos podem passar */
|
||||
GREEN,
|
||||
|
||||
/** Sinal vermelho - veículos aguardam na fila */
|
||||
RED
|
||||
}
|
||||
@@ -5,27 +5,57 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Represents a single vehicle moving through the simulation.
|
||||
* Representa um veículo que se move pela rede de interseções.
|
||||
*
|
||||
* Each vehicle has a route - a sequence of intersections it will pass through -
|
||||
* and keeps track of how long it has waited and traveled overall.
|
||||
* <p>Esta classe é o "gémeo digital" de um carro, mota ou camião.
|
||||
* Mantém toda a informação necessária:</p>
|
||||
* <ul>
|
||||
* <li>Identificação e tipo do veículo</li>
|
||||
* <li>Rota completa a percorrer</li>
|
||||
* <li>Métricas de tempo (espera, travessia, total)</li>
|
||||
* </ul>
|
||||
*
|
||||
* Serializable so it can be sent between processes or nodes over sockets. type shit
|
||||
* <p>O objeto é serializado e enviado pela rede à medida que o veículo
|
||||
* se move entre processos distribuídos.</p>
|
||||
*/
|
||||
public class Vehicle implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
// Identity and configuration
|
||||
/** Identificador único do veículo (ex: "V1", "V2") */
|
||||
private final String id;
|
||||
|
||||
/** Tipo de veículo (BIKE, LIGHT, HEAVY) */
|
||||
private final VehicleType type;
|
||||
private final double entryTime; // When it entered the system
|
||||
private final List<String> route; // ex., ["Cr1", "Cr3", "S"]
|
||||
private int currentRouteIndex; // Current position in the route
|
||||
|
||||
// Metrics
|
||||
private double totalWaitingTime; // Total time spent waiting at red lights
|
||||
private double totalCrossingTime; // Time spent actually moving between intersections
|
||||
/** Tempo de simulação (em segundos) em que o veículo foi gerado */
|
||||
private final double entryTime;
|
||||
|
||||
/**
|
||||
* Lista ordenada completa de destinos (IDs de interseções e saída "S").
|
||||
* Exemplo: ["Cr1", "Cr3", "S"]
|
||||
*/
|
||||
private final List<String> route;
|
||||
|
||||
/**
|
||||
* Índice que acompanha o progresso do veículo ao longo da {@link #route}.
|
||||
* {@code route.get(currentRouteIndex)} é o destino *atual* do veículo.
|
||||
*/
|
||||
private int currentRouteIndex;
|
||||
|
||||
/** Tempo total acumulado (segundos) que o veículo passou à espera em semáforos vermelhos */
|
||||
private double totalWaitingTime;
|
||||
|
||||
/** Tempo total acumulado (segundos) que o veículo passou a atravessar interseções */
|
||||
private double totalCrossingTime;
|
||||
|
||||
/**
|
||||
* Cria um novo veículo pronto para se fazer à estrada.
|
||||
*
|
||||
* @param id Identificador único (ex: "V1").
|
||||
* @param type O tipo de veículo (determina velocidade/tamanho).
|
||||
* @param entryTime Quando este veículo entrou na simulação (segundos).
|
||||
* @param route A lista ordenada de paragens (Interseções -> Saída).
|
||||
*/
|
||||
public Vehicle(String id, VehicleType type, double entryTime, List<String> route) {
|
||||
this.id = id;
|
||||
this.type = type;
|
||||
@@ -37,9 +67,12 @@ public class Vehicle implements Serializable {
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the vehicle to the next stop in its route.
|
||||
* Move o GPS interno do veículo para o próximo destino.
|
||||
*
|
||||
* @return true if there are still destinations ahead, false if the route is finished
|
||||
* Chame isto quando um veículo chega a uma interseção para atualizar para onde
|
||||
* deve ir a seguir.
|
||||
*
|
||||
* @return true se houver mais paragens, false se a viagem terminou.
|
||||
*/
|
||||
public boolean advanceRoute() {
|
||||
currentRouteIndex++;
|
||||
@@ -47,71 +80,93 @@ public class Vehicle implements Serializable {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current destination (the next intersection or exit).
|
||||
* Returns null if the route is already complete.
|
||||
* Obtém o destino atual (próxima interseção ou saída) para onde o veículo se dirige.
|
||||
*
|
||||
* @return ID do destino atual (ex: "Cr1"), ou {@code null} se a rota terminou
|
||||
*/
|
||||
public String getCurrentDestination() {
|
||||
return (currentRouteIndex < route.size()) ? route.get(currentRouteIndex) : null;
|
||||
}
|
||||
|
||||
/** Returns true if the vehicle has completed its entire route. */
|
||||
/**
|
||||
* Verifica se o veículo completou toda a sua rota.
|
||||
*
|
||||
* @return {@code true} se chegou ao fim da rota, {@code false} caso contrário
|
||||
*/
|
||||
public boolean hasReachedEnd() {
|
||||
return currentRouteIndex >= route.size();
|
||||
}
|
||||
|
||||
// --- Getters and metrics management ---
|
||||
|
||||
/** @return identificador único do veículo */
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/** @return tipo do veículo */
|
||||
public VehicleType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/** @return tempo de simulação em que o veículo entrou no sistema */
|
||||
public double getEntryTime() {
|
||||
return entryTime;
|
||||
}
|
||||
|
||||
/** @return cópia da rota completa do veículo */
|
||||
public List<String> getRoute() {
|
||||
return new ArrayList<>(route);
|
||||
}
|
||||
|
||||
/** @return índice atual apontando para o destino do veículo na sua rota */
|
||||
public int getCurrentRouteIndex() {
|
||||
return currentRouteIndex;
|
||||
}
|
||||
|
||||
/** @return tempo total acumulado de espera em segundos */
|
||||
public double getTotalWaitingTime() {
|
||||
return totalWaitingTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adiciona uma duração ao tempo total de espera do veículo.
|
||||
* Chamado quando um veículo começa a atravessar uma interseção.
|
||||
*
|
||||
* @param time duração (em segundos) a adicionar
|
||||
*/
|
||||
public void addWaitingTime(double time) {
|
||||
totalWaitingTime += time;
|
||||
}
|
||||
|
||||
/** @return tempo total acumulado de travessia em segundos */
|
||||
public double getTotalCrossingTime() {
|
||||
return totalCrossingTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adiciona uma duração ao tempo total de travessia do veículo.
|
||||
* Chamado quando um veículo termina de atravessar uma interseção.
|
||||
*
|
||||
* @param time duração (em segundos) a adicionar
|
||||
*/
|
||||
public void addCrossingTime(double time) {
|
||||
totalCrossingTime += time;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates how long the vehicle has been in the system so far.
|
||||
* Calcula o tempo total que o veículo passou no sistema até agora.
|
||||
*
|
||||
* @param currentTime the current simulation time
|
||||
* @return total elapsed time since the vehicle entered
|
||||
* @param currentTime tempo atual da simulação
|
||||
* @return tempo total decorrido (em segundos) desde que o veículo foi gerado
|
||||
*/
|
||||
public double getTotalTravelTime(double currentTime) {
|
||||
return currentTime - entryTime;
|
||||
}
|
||||
|
||||
/** @return representação textual do estado atual do veículo */
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format(
|
||||
"Vehicle{id='%s', type=%s, next='%s', route=%s}",
|
||||
id, type, getCurrentDestination(), route
|
||||
);
|
||||
"Vehicle{id='%s', type=%s, next='%s', route=%s}",
|
||||
id, type, getCurrentDestination(), route);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,19 @@
|
||||
package sd.model;
|
||||
|
||||
/**
|
||||
* Enumeration representing vehicle types in the simulation.
|
||||
* Enumeração dos diferentes tipos de veículos na simulação.
|
||||
*
|
||||
* <p>Cada tipo pode ter propriedades diferentes como tempo de travessia
|
||||
* e probabilidade de geração, definidas na {@link sd.config.SimulationConfig}.</p>
|
||||
*/
|
||||
public enum VehicleType {
|
||||
BIKE, // Motorcycle
|
||||
LIGHT, // Light vehicle (car)
|
||||
HEAVY // Heavy vehicle (truck, bus)
|
||||
|
||||
/** Bicicleta ou motocicleta - tempo de travessia curto */
|
||||
BIKE,
|
||||
|
||||
/** Veículo ligeiro padrão (carro) - tipo mais comum */
|
||||
LIGHT,
|
||||
|
||||
/** Veículo pesado (camião ou autocarro) - tempo de travessia longo */
|
||||
HEAVY
|
||||
}
|
||||
45
main/src/main/java/sd/protocol/MessageProtocol.java
Normal file
45
main/src/main/java/sd/protocol/MessageProtocol.java
Normal file
@@ -0,0 +1,45 @@
|
||||
package sd.protocol;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import sd.model.MessageType; // Assuming MessageType is in sd.model or sd.protocol
|
||||
|
||||
/**
|
||||
* Contrato para todas as mensagens trocadas no simulador.
|
||||
*
|
||||
* <p>Garante que mensagens podem ser identificadas e encaminhadas.
|
||||
* Extende Serializable para permitir envio via sockets.
|
||||
*/
|
||||
public interface MessageProtocol extends Serializable {
|
||||
|
||||
/**
|
||||
* Tipo da mensagem, indicando o seu propósito.
|
||||
* @return tipo (ex: VEHICLE_TRANSFER, STATS_UPDATE)
|
||||
*/
|
||||
MessageType getType();
|
||||
|
||||
/**
|
||||
* Dados (payload) que esta mensagem transporta.
|
||||
*
|
||||
* <p>Tipo depende do MessageType:
|
||||
* <ul>
|
||||
* <li>VEHICLE_TRANSFER → objeto Vehicle
|
||||
* <li>STATS_UPDATE → objeto de estatísticas
|
||||
* </ul>
|
||||
*
|
||||
* @return payload (deve ser Serializable)
|
||||
*/
|
||||
Object getPayload();
|
||||
|
||||
/**
|
||||
* ID do nó (processo) que enviou a mensagem.
|
||||
* @return ID de origem (ex: "Cr1", "Cr5", "S")
|
||||
*/
|
||||
String getSourceNode();
|
||||
|
||||
/**
|
||||
* ID do nó de destino.
|
||||
* @return ID de destino (ex: "Cr2", "DashboardServer")
|
||||
*/
|
||||
String getDestinationNode();
|
||||
}
|
||||
196
main/src/main/java/sd/protocol/SocketConnection.java
Normal file
196
main/src/main/java/sd/protocol/SocketConnection.java
Normal file
@@ -0,0 +1,196 @@
|
||||
package sd.protocol;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.ConnectException;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import sd.serialization.MessageSerializer;
|
||||
import sd.serialization.SerializationException;
|
||||
import sd.serialization.SerializerFactory;
|
||||
|
||||
|
||||
/**
|
||||
* Simplifica comunicação via sockets.
|
||||
* Inclui lógica de retry para robustez.
|
||||
*/
|
||||
public class SocketConnection implements Closeable {
|
||||
|
||||
private final Socket socket;
|
||||
private final OutputStream outputStream;
|
||||
private final InputStream inputStream;
|
||||
private final MessageSerializer serializer;
|
||||
|
||||
/** Número máximo de tentativas de ligação */
|
||||
private static final int MAX_RETRIES = 5;
|
||||
/** Atraso entre tentativas (milissegundos) */
|
||||
private static final long RETRY_DELAY_MS = 1000;
|
||||
|
||||
/**
|
||||
* Construtor do cliente que inicia a ligação.
|
||||
* Tenta ligar a um servidor já em escuta, com retry.
|
||||
*
|
||||
* @param host endereço do host (ex: "localhost")
|
||||
* @param port número da porta
|
||||
* @throws IOException se falhar após todas as tentativas
|
||||
* @throws UnknownHostException se o host não for encontrado
|
||||
* @throws InterruptedException se a thread for interrompida
|
||||
*/
|
||||
public SocketConnection(String host, int port) throws IOException, UnknownHostException, InterruptedException {
|
||||
Socket tempSocket = null;
|
||||
IOException lastException = null;
|
||||
|
||||
System.out.printf("[SocketConnection] Attempting to connect to %s:%d...%n", host, port);
|
||||
|
||||
// --- Retry Loop ---
|
||||
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
// Try to establish the connection
|
||||
tempSocket = new Socket(host, port);
|
||||
|
||||
// If successful, break out of the retry loop
|
||||
System.out.printf("[SocketConnection] Connected successfully on attempt %d.%n", attempt);
|
||||
lastException = null; // Clear last error on success
|
||||
break;
|
||||
|
||||
} catch (ConnectException | SocketTimeoutException e) {
|
||||
// These are common errors indicating the server might not be ready.
|
||||
lastException = e;
|
||||
System.out.printf("[SocketConnection] Attempt %d/%d failed: %s. Retrying in %d ms...%n",
|
||||
attempt, MAX_RETRIES, e.getMessage(), RETRY_DELAY_MS);
|
||||
|
||||
if (attempt < MAX_RETRIES) {
|
||||
// Wait before the next attempt
|
||||
TimeUnit.MILLISECONDS.sleep(RETRY_DELAY_MS);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Other IOExceptions might be more permanent, but we retry anyway.
|
||||
lastException = e;
|
||||
System.out.printf("[SocketConnection] Attempt %d/%d failed with IOException: %s. Retrying in %d ms...%n",
|
||||
attempt, MAX_RETRIES, e.getMessage(), RETRY_DELAY_MS);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
TimeUnit.MILLISECONDS.sleep(RETRY_DELAY_MS);
|
||||
}
|
||||
}
|
||||
} // --- End of Retry Loop ---
|
||||
|
||||
// If after all retries tempSocket is still null, it means connection failed permanently.
|
||||
if (tempSocket == null) {
|
||||
System.err.printf("[SocketConnection] Failed to connect to %s:%d after %d attempts.%n", host, port, MAX_RETRIES);
|
||||
if (lastException != null) {
|
||||
throw lastException; // Throw the last exception encountered
|
||||
} else {
|
||||
// Should not happen if loop ran, but as a fallback
|
||||
throw new IOException("Failed to connect after " + MAX_RETRIES + " attempts, reason unknown.");
|
||||
}
|
||||
}
|
||||
|
||||
// If connection was successful, assign to final variable and create streams
|
||||
this.socket = tempSocket;
|
||||
|
||||
this.outputStream = socket.getOutputStream();
|
||||
this.inputStream = socket.getInputStream();
|
||||
this.serializer = SerializerFactory.createDefault();
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Constructor for the "Server" (who accepts the connection).
|
||||
* Receives a Socket that has already been accepted by a ServerSocket.
|
||||
* No retry logic needed here as the connection is already established.
|
||||
*
|
||||
* @param acceptedSocket The Socket returned by serverSocket.accept().
|
||||
* @throws IOException If stream creation fails.
|
||||
*/
|
||||
public SocketConnection(Socket acceptedSocket) throws IOException {
|
||||
this.socket = acceptedSocket;
|
||||
this.outputStream = socket.getOutputStream();
|
||||
this.inputStream = socket.getInputStream();
|
||||
this.serializer = SerializerFactory.createDefault();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends (serializes) a MessageProtocol object over the socket.
|
||||
*
|
||||
* @param message The "envelope" (which contains the Vehicle) to be sent.
|
||||
* @throws IOException If writing to the stream fails or socket is not connected.
|
||||
*/
|
||||
public synchronized void sendMessage(MessageProtocol message) throws IOException {
|
||||
if (socket == null || !socket.isConnected()) {
|
||||
throw new IOException("Socket is not connected");
|
||||
}
|
||||
|
||||
try {
|
||||
// Serializa para bytes JSON
|
||||
byte[] data = serializer.serialize(message);
|
||||
|
||||
// Write 4-byte length prefix
|
||||
DataOutputStream dataOut = new DataOutputStream(outputStream);
|
||||
dataOut.writeInt(data.length);
|
||||
dataOut.write(data);
|
||||
dataOut.flush();
|
||||
|
||||
} catch (SerializationException e) {
|
||||
throw new IOException("Failed to serialize message", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to read (deserialize) a MessageProtocol object from the socket.
|
||||
*
|
||||
* @return The "envelope" (MessageProtocol) that was received.
|
||||
* @throws IOException If the connection is lost, the stream is corrupted, or socket is not connected.
|
||||
* @throws ClassNotFoundException If the received object is unknown.
|
||||
*/
|
||||
public MessageProtocol receiveMessage() throws IOException, ClassNotFoundException {
|
||||
if (socket == null || !socket.isConnected()) {
|
||||
throw new IOException("Socket is not connected");
|
||||
}
|
||||
|
||||
try {
|
||||
// Lê um prefixo de 4 bytes - indicador de tamanho
|
||||
DataInputStream dataIn = new DataInputStream(inputStream);
|
||||
int length = dataIn.readInt();
|
||||
|
||||
if (length <= 0 || length > 10_000_000) { // Sanity check (10MB max)
|
||||
throw new IOException("Invalid message length: " + length);
|
||||
}
|
||||
|
||||
// Ler dados da mensagem
|
||||
byte[] data = new byte[length];
|
||||
dataIn.readFully(data);
|
||||
|
||||
// Deserialize do JSON - use concrete Message class, not interface
|
||||
return serializer.deserialize(data, sd.model.Message.class);
|
||||
|
||||
} catch (SerializationException e) {
|
||||
throw new IOException("Failed to deserialize message", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the socket and all streams (Input and Output).
|
||||
*/
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
if (inputStream != null) inputStream.close();
|
||||
if (outputStream != null) outputStream.close();
|
||||
if (socket != null) socket.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if the socket is still connected and not closed.
|
||||
*/
|
||||
public boolean isConnected() {
|
||||
return socket != null && socket.isConnected() && !socket.isClosed();
|
||||
}
|
||||
}
|
||||
114
main/src/main/java/sd/serialization/JsonMessageSerializer.java
Normal file
114
main/src/main/java/sd/serialization/JsonMessageSerializer.java
Normal file
@@ -0,0 +1,114 @@
|
||||
package sd.serialization;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* JSON-based implementation of {@link MessageSerializer} using Google's Gson library.
|
||||
*
|
||||
* This serializer converts objects to JSON format for transmission, providing:
|
||||
* - Human-readable message format (easy debugging)
|
||||
* - Cross-platform compatibility
|
||||
* - Smaller message sizes compared to Java native serialization
|
||||
* - Better security (no code execution during deserialization)
|
||||
*
|
||||
* The serializer is configured with pretty printing disabled by default for
|
||||
* production use, but can be enabled for debugging purposes.
|
||||
*
|
||||
* Thread-safety: This class is thread-safe as Gson instances are thread-safe.
|
||||
*
|
||||
* @see MessageSerializer
|
||||
*/
|
||||
public class JsonMessageSerializer implements MessageSerializer {
|
||||
|
||||
private final Gson gson;
|
||||
private final boolean prettyPrint;
|
||||
|
||||
/**
|
||||
* Creates a new JSON serializer with default configuration (no pretty printing).
|
||||
*/
|
||||
public JsonMessageSerializer() {
|
||||
this(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new JSON serializer with optional pretty printing.
|
||||
*
|
||||
* @param prettyPrint If true, JSON output will be formatted with indentation
|
||||
*/
|
||||
public JsonMessageSerializer(boolean prettyPrint) {
|
||||
this.prettyPrint = prettyPrint;
|
||||
GsonBuilder builder = new GsonBuilder();
|
||||
|
||||
if (prettyPrint) {
|
||||
builder.setPrettyPrinting();
|
||||
}
|
||||
|
||||
// Register custom type adapters here if needed
|
||||
// builder.registerTypeAdapter(Vehicle.class, new VehicleAdapter());
|
||||
|
||||
this.gson = builder.create();
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] serialize(Object object) throws SerializationException {
|
||||
if (object == null) {
|
||||
throw new IllegalArgumentException("Cannot serialize null object");
|
||||
}
|
||||
|
||||
try {
|
||||
String json = gson.toJson(object);
|
||||
return json.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
throw new SerializationException(
|
||||
"Failed to serialize object of type " + object.getClass().getName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T deserialize(byte[] data, Class<T> clazz) throws SerializationException {
|
||||
if (data == null) {
|
||||
throw new IllegalArgumentException("Cannot deserialize null data");
|
||||
}
|
||||
if (clazz == null) {
|
||||
throw new IllegalArgumentException("Class type cannot be null");
|
||||
}
|
||||
|
||||
try {
|
||||
String json = new String(data, StandardCharsets.UTF_8);
|
||||
return gson.fromJson(json, clazz);
|
||||
} catch (JsonSyntaxException e) {
|
||||
throw new SerializationException(
|
||||
"Failed to parse JSON for type " + clazz.getName(), e);
|
||||
} catch (Exception e) {
|
||||
throw new SerializationException(
|
||||
"Failed to deserialize object of type " + clazz.getName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "JSON (Gson)";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying Gson instance for advanced usage.
|
||||
*
|
||||
* @return The Gson instance
|
||||
*/
|
||||
public Gson getGson() {
|
||||
return gson;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if pretty printing is enabled.
|
||||
*
|
||||
* @return true if pretty printing is enabled
|
||||
*/
|
||||
public boolean isPrettyPrint() {
|
||||
return prettyPrint;
|
||||
}
|
||||
}
|
||||
48
main/src/main/java/sd/serialization/MessageSerializer.java
Normal file
48
main/src/main/java/sd/serialization/MessageSerializer.java
Normal file
@@ -0,0 +1,48 @@
|
||||
package sd.serialization;
|
||||
|
||||
/**
|
||||
* Interface for serializing and deserializing objects for network transmission.
|
||||
*
|
||||
* This interface provides a common abstraction for different serialization strategies
|
||||
* allowing the system to switch between implementations without changing the communication layer.
|
||||
*
|
||||
* Implementations must ensure:
|
||||
* - Thread-safety if used in concurrent contexts
|
||||
* - Proper exception handling with meaningful error messages
|
||||
* - Preservation of object state during round-trip serialization
|
||||
*
|
||||
* @see JsonMessageSerializer
|
||||
*/
|
||||
public interface MessageSerializer {
|
||||
|
||||
/**
|
||||
* Serializes an object into a byte array for transmission.
|
||||
*
|
||||
* @param object The object to serialize (must not be null)
|
||||
* @return A byte array containing the serialized representation
|
||||
* @throws SerializationException If serialization fails
|
||||
* @throws IllegalArgumentException If object is null
|
||||
*/
|
||||
byte[] serialize(Object object) throws SerializationException;
|
||||
|
||||
/**
|
||||
* Deserializes a byte array back into an object of the specified type.
|
||||
*
|
||||
* @param <T> The expected type of the deserialized object
|
||||
* @param data The byte array containing serialized data (must not be null)
|
||||
* @param clazz The class of the expected object type (must not be null)
|
||||
* @return The deserialized object
|
||||
* @throws SerializationException If deserialization fails
|
||||
* @throws IllegalArgumentException If data or clazz is null
|
||||
*/
|
||||
<T> T deserialize(byte[] data, Class<T> clazz) throws SerializationException;
|
||||
|
||||
/**
|
||||
* Gets the name of this serialization strategy (e.g., "JSON", "Java Native").
|
||||
* Useful for logging and debugging.
|
||||
*
|
||||
* @return The serializer name
|
||||
*/
|
||||
String getName();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package sd.serialization;
|
||||
|
||||
/**
|
||||
* Exception thrown when serialization or deserialization operations fail.
|
||||
*
|
||||
* This exception wraps underlying errors (I/O exceptions, parsing errors, etc.)
|
||||
* and provides context about what went wrong during the serialization process.
|
||||
*/
|
||||
public class SerializationException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = 1L; // Long(64bits) instead of int(32bits)
|
||||
|
||||
/**
|
||||
* Constructs a new serialization exception with the specified detail message.
|
||||
*
|
||||
* @param message The detail message
|
||||
*/
|
||||
public SerializationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new serialization exception with the specified detail message
|
||||
* and cause.
|
||||
*
|
||||
* @param message The detail message
|
||||
* @param cause The cause of this exception
|
||||
*/
|
||||
public SerializationException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new serialization exception with the specified cause.
|
||||
*
|
||||
* @param cause The cause of this exception
|
||||
*/
|
||||
public SerializationException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
66
main/src/main/java/sd/serialization/SerializerFactory.java
Normal file
66
main/src/main/java/sd/serialization/SerializerFactory.java
Normal file
@@ -0,0 +1,66 @@
|
||||
package sd.serialization;
|
||||
|
||||
/**
|
||||
* Factory for creating {@link MessageSerializer} instances.
|
||||
*
|
||||
* This factory provides a centralized way to create and configure JSON serializers
|
||||
* using Gson, making it easy to configure serialization throughout the application.
|
||||
*
|
||||
* The factory can be configured via system properties for easy deployment configuration.
|
||||
*
|
||||
* Example usage:
|
||||
* <pre>
|
||||
* MessageSerializer serializer = SerializerFactory.createDefault();
|
||||
* byte[] data = serializer.serialize(myObject);
|
||||
* </pre>
|
||||
*/
|
||||
public class SerializerFactory {
|
||||
|
||||
/**
|
||||
* System property key for enabling pretty-print in JSON serialization.
|
||||
* Set to "true" for debugging, "false" for production.
|
||||
*/
|
||||
public static final String JSON_PRETTY_PRINT_PROPERTY = "sd.serialization.json.prettyPrint";
|
||||
|
||||
// Default configuration
|
||||
private static final boolean DEFAULT_JSON_PRETTY_PRINT = false;
|
||||
|
||||
/**
|
||||
* Private constructor to prevent instantiation.
|
||||
*/
|
||||
private SerializerFactory() {
|
||||
throw new UnsupportedOperationException("Factory class cannot be instantiated");
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a JSON serializer based on system configuration.
|
||||
*
|
||||
* Pretty-print is determined by checking the system property
|
||||
* {@value #JSON_PRETTY_PRINT_PROPERTY}. If not set, defaults to false.
|
||||
*
|
||||
* @return A configured JsonMessageSerializer instance
|
||||
*/
|
||||
public static MessageSerializer createDefault() {
|
||||
boolean prettyPrint = Boolean.getBoolean(JSON_PRETTY_PRINT_PROPERTY);
|
||||
return new JsonMessageSerializer(prettyPrint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a JSON serializer with default configuration (no pretty printing).
|
||||
*
|
||||
* @return A JsonMessageSerializer instance
|
||||
*/
|
||||
public static MessageSerializer createSerializer() {
|
||||
return createSerializer(DEFAULT_JSON_PRETTY_PRINT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a JSON serializer with specified pretty-print setting.
|
||||
*
|
||||
* @param prettyPrint Whether to enable pretty printing
|
||||
* @return A JsonMessageSerializer instance
|
||||
*/
|
||||
public static MessageSerializer createSerializer(boolean prettyPrint) {
|
||||
return new JsonMessageSerializer(prettyPrint);
|
||||
}
|
||||
}
|
||||
@@ -3,64 +3,98 @@ package sd.util;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Utility class for generating random values used throughout the simulation.
|
||||
* Utilitário para gerar valores aleatórios usados na simulação.
|
||||
*
|
||||
* Includes helpers for exponential distributions (for vehicle arrivals),
|
||||
* uniform randoms, and probability-based decisions.
|
||||
* <p>Fornece métodos estáticos para:</p>
|
||||
* <ul>
|
||||
* <li>Gerar intervalos exponencialmente distribuídos (processos de Poisson)</li>
|
||||
* <li>Gerar inteiros e doubles aleatórios num intervalo</li>
|
||||
* <li>Tomar decisões baseadas em probabilidade</li>
|
||||
* <li>Escolher elementos aleatórios de um array</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Usa uma única instância estática de {@link Random}.</p>
|
||||
*/
|
||||
public class RandomGenerator {
|
||||
|
||||
/** Instância partilhada de Random para toda a simulação */
|
||||
private static final Random random = new Random();
|
||||
|
||||
/**
|
||||
* Returns a random time interval that follows an exponential distribution.
|
||||
* Retorna um intervalo de tempo que segue uma distribuição exponencial.
|
||||
*
|
||||
* Useful for modeling inter-arrival times in a Poisson process.
|
||||
* <p>Componente essencial para modelar processos de Poisson, onde os
|
||||
* tempos entre chegadas seguem uma distribuição exponencial.</p>
|
||||
*
|
||||
* @param lambda the arrival rate (λ)
|
||||
* @return the time interval until the next arrival
|
||||
* <p>Fórmula: {@code Time = -ln(1 - U) / λ}<br>
|
||||
* onde U é um número aleatório uniforme [0, 1) e λ (lambda) é a taxa média de chegada.</p>
|
||||
*
|
||||
* @param lambda taxa média de chegada λ (ex: 0.5 veículos por segundo)
|
||||
* @return intervalo de tempo (segundos) até à próxima chegada
|
||||
*/
|
||||
public static double generateExponentialInterval(double lambda) {
|
||||
return Math.log(1 - random.nextDouble()) / -lambda;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random integer between {@code min} and {@code max}, inclusive.
|
||||
* Retorna um inteiro aleatório entre {@code min} e {@code max}, inclusive.
|
||||
*
|
||||
* @param min valor mínimo possível
|
||||
* @param max valor máximo possível
|
||||
* @return inteiro aleatório no intervalo [min, max]
|
||||
*/
|
||||
public static int generateRandomInt(int min, int max) {
|
||||
return random.nextInt(max - min + 1) + min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random double between {@code min} (inclusive) and {@code max} (exclusive).
|
||||
* Retorna um double aleatório entre {@code min} (inclusive) e {@code max} (exclusivo).
|
||||
*
|
||||
* @param min valor mínimo possível
|
||||
* @param max valor máximo possível
|
||||
* @return double aleatório no intervalo [min, max)
|
||||
*/
|
||||
public static double generateRandomDouble(double min, double max) {
|
||||
return min + (max - min) * random.nextDouble();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} with the given probability.
|
||||
* Retorna {@code true} com uma dada probabilidade.
|
||||
*
|
||||
* @param probability a value between 0.0 and 1.0
|
||||
* <p>Útil para tomar decisões ponderadas. Por exemplo,
|
||||
* {@code occursWithProbability(0.3)} retorna {@code true}
|
||||
* aproximadamente 30% das vezes.</p>
|
||||
*
|
||||
* @param probability valor entre 0.0 (nunca) e 1.0 (sempre)
|
||||
* @return {@code true} ou {@code false}, baseado na probabilidade
|
||||
*/
|
||||
public static boolean occursWithProbability(double probability) {
|
||||
return random.nextDouble() < probability;
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks a random element from the given array.
|
||||
* Escolhe um elemento aleatório do array fornecido.
|
||||
*
|
||||
* @throws IllegalArgumentException if the array is empty
|
||||
* @param <T> tipo genérico do array
|
||||
* @param array array de onde escolher
|
||||
* @return elemento selecionado aleatoriamente
|
||||
* @throws IllegalArgumentException se o array for null ou vazio
|
||||
*/
|
||||
public static <T> T chooseRandom(T[] array) {
|
||||
if (array.length == 0) {
|
||||
throw new IllegalArgumentException("Array cannot be empty.");
|
||||
if (array == null || array.length == 0) {
|
||||
throw new IllegalArgumentException("Array cannot be null or empty.");
|
||||
}
|
||||
return array[random.nextInt(array.length)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the random generator’s seed, allowing reproducible results.
|
||||
* Define a seed do gerador de números aleatórios partilhado.
|
||||
*
|
||||
* <p>Extremamente útil para debugging e testes, pois permite executar
|
||||
* a simulação múltiplas vezes com a mesma sequência de eventos "aleatórios",
|
||||
* tornando os resultados reproduzíveis.</p>
|
||||
*
|
||||
* @param seed seed a usar
|
||||
*/
|
||||
public static void setSeed(long seed) {
|
||||
random.setSeed(seed);
|
||||
|
||||
230
main/src/main/java/sd/util/VehicleGenerator.java
Normal file
230
main/src/main/java/sd/util/VehicleGenerator.java
Normal file
@@ -0,0 +1,230 @@
|
||||
package sd.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import sd.config.SimulationConfig;
|
||||
import sd.model.Vehicle;
|
||||
import sd.model.VehicleType;
|
||||
|
||||
/**
|
||||
* Gera veículos para a simulação.
|
||||
*
|
||||
* <p>Esta classe é responsável por duas tarefas principais:</p>
|
||||
* <ol>
|
||||
* <li>Determinar <em>quando</em> o próximo veículo deve chegar, baseado no
|
||||
* modelo de chegada (POISSON ou FIXED) da {@link SimulationConfig}</li>
|
||||
* <li>Criar um novo objeto {@link Vehicle} com tipo e rota selecionados aleatoriamente</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>As rotas são predefinidas e organizadas por ponto de entrada (E1, E2, E3).</p>
|
||||
*/
|
||||
public class VehicleGenerator {
|
||||
|
||||
private final SimulationConfig config;
|
||||
private final String arrivalModel;
|
||||
/** Lambda (λ) para modelo POISSON */
|
||||
private final double arrivalRate;
|
||||
/** Intervalo para modelo FIXED */
|
||||
private final double fixedInterval;
|
||||
|
||||
/** Rotas possíveis a partir do ponto de entrada E1 */
|
||||
private final List<RouteWithProbability> e1Routes;
|
||||
/** Rotas possíveis a partir do ponto de entrada E2 */
|
||||
private final List<RouteWithProbability> e2Routes;
|
||||
/** Rotas possíveis a partir do ponto de entrada E3 */
|
||||
private final List<RouteWithProbability> e3Routes;
|
||||
|
||||
/**
|
||||
* Cria um novo gerador de veículos.
|
||||
* Lê a configuração necessária e inicializa as rotas predefinidas.
|
||||
*
|
||||
* @param config objeto de {@link SimulationConfig}
|
||||
*/
|
||||
public VehicleGenerator(SimulationConfig config) {
|
||||
this.config = config;
|
||||
|
||||
// Cache configuration values for performance
|
||||
this.arrivalModel = config.getArrivalModel();
|
||||
this.arrivalRate = config.getArrivalRate();
|
||||
this.fixedInterval = config.getFixedArrivalInterval();
|
||||
|
||||
// Initialize route lists
|
||||
this.e1Routes = new ArrayList<>();
|
||||
this.e2Routes = new ArrayList<>();
|
||||
this.e3Routes = new ArrayList<>();
|
||||
initializePossibleRoutes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Define todas as rotas possíveis que os veículos podem tomar.
|
||||
* As rotas são organizadas por ponto de entrada (E1, E2, E3).
|
||||
* Cada rota tem uma probabilidade que determina a frequência com que é escolhida.
|
||||
*/
|
||||
private void initializePossibleRoutes() {
|
||||
e1Routes.add(new RouteWithProbability(
|
||||
Arrays.asList("Cr1", "Cr4", "Cr5", "S"), 0.34));
|
||||
e1Routes.add(new RouteWithProbability(
|
||||
Arrays.asList("Cr1", "Cr2", "Cr5", "S"), 0.33));
|
||||
e1Routes.add(new RouteWithProbability(
|
||||
Arrays.asList("Cr1", "Cr2", "Cr3", "S"), 0.33));
|
||||
|
||||
e2Routes.add(new RouteWithProbability(
|
||||
Arrays.asList("Cr2", "Cr5", "S"), 0.34));
|
||||
e2Routes.add(new RouteWithProbability(
|
||||
Arrays.asList("Cr2", "Cr3", "S"), 0.33));
|
||||
e2Routes.add(new RouteWithProbability(
|
||||
Arrays.asList("Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33));
|
||||
|
||||
e3Routes.add(new RouteWithProbability(
|
||||
Arrays.asList("Cr3", "S"), 0.34));
|
||||
e3Routes.add(new RouteWithProbability(
|
||||
Arrays.asList("Cr3", "Cr2", "Cr5", "S"), 0.33));
|
||||
e3Routes.add(new RouteWithProbability(
|
||||
Arrays.asList("Cr3", "Cr2", "Cr1", "Cr4", "Cr5", "S"), 0.33));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcula o tempo <em>absoluto</em> da próxima chegada de veículo
|
||||
* baseado no modelo configurado.
|
||||
*
|
||||
* @param currentTime tempo atual da simulação, usado como base
|
||||
* @return tempo absoluto (ex: {@code currentTime + intervalo})
|
||||
* em que o próximo veículo deve ser gerado
|
||||
*/
|
||||
public double getNextArrivalTime(double currentTime) {
|
||||
if ("POISSON".equalsIgnoreCase(arrivalModel)) {
|
||||
double interval = RandomGenerator.generateExponentialInterval(arrivalRate);
|
||||
return currentTime + interval;
|
||||
} else {
|
||||
return currentTime + fixedInterval;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gera um novo objeto {@link Vehicle}.
|
||||
*
|
||||
* <p>Passos executados:</p>
|
||||
* <ol>
|
||||
* <li>Seleciona um {@link VehicleType} aleatório baseado em probabilidades</li>
|
||||
* <li>Seleciona uma rota aleatória (ponto de entrada + caminho)</li>
|
||||
* </ol>
|
||||
*
|
||||
* @param vehicleId identificador único do novo veículo (ex: "V123")
|
||||
* @param entryTime tempo de simulação em que o veículo é criado
|
||||
* @return novo objeto {@link Vehicle} configurado
|
||||
*/
|
||||
public Vehicle generateVehicle(String vehicleId, double entryTime) {
|
||||
VehicleType type = selectVehicleType();
|
||||
List<String> route = selectRandomRoute();
|
||||
|
||||
return new Vehicle(vehicleId, type, entryTime, route);
|
||||
}
|
||||
|
||||
/**
|
||||
* Seleciona um {@link VehicleType} (BIKE, LIGHT, HEAVY) baseado nas
|
||||
* probabilidades definidas na {@link SimulationConfig}.
|
||||
*
|
||||
* <p>Usa técnica de "probabilidade cumulativa":</p>
|
||||
* <ol>
|
||||
* <li>Obtém número aleatório {@code rand} de [0, 1)</li>
|
||||
* <li>Se {@code rand < P(Bike)}, retorna BIKE</li>
|
||||
* <li>Senão se {@code rand < P(Bike) + P(Light)}, retorna LIGHT</li>
|
||||
* <li>Caso contrário, retorna HEAVY</li>
|
||||
* </ol>
|
||||
*
|
||||
* @return tipo de veículo selecionado
|
||||
*/
|
||||
private VehicleType selectVehicleType() {
|
||||
double bikeProbability = config.getBikeVehicleProbability();
|
||||
double lightProbability = config.getLightVehicleProbability();
|
||||
double heavyProbability = config.getHeavyVehicleProbability();
|
||||
|
||||
double total = bikeProbability + lightProbability + heavyProbability;
|
||||
if (total == 0) return VehicleType.LIGHT; // Avoid division by zero
|
||||
bikeProbability /= total;
|
||||
lightProbability /= total;
|
||||
|
||||
double rand = Math.random();
|
||||
|
||||
if (rand < bikeProbability) {
|
||||
return VehicleType.BIKE;
|
||||
} else if (rand < bikeProbability + lightProbability) {
|
||||
return VehicleType.LIGHT;
|
||||
} else {
|
||||
return VehicleType.HEAVY;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects a random route for a new vehicle.
|
||||
* This is a two-step process:
|
||||
* 1. Randomly select an entry point (E1, E2, or E3) with equal probability.
|
||||
* 2. From the chosen entry point's list of routes, select one
|
||||
* based on their defined probabilities (using cumulative probability).
|
||||
*
|
||||
* @return A {@link List} of strings representing the chosen route (e.g., ["Cr1", "Cr4", "S"]).
|
||||
*/
|
||||
private List<String> selectRandomRoute() {
|
||||
// Step 1: Randomly select an entry point (E1, E2, or E3)
|
||||
double entryRandom = Math.random();
|
||||
List<RouteWithProbability> selectedRoutes;
|
||||
|
||||
if (entryRandom < 0.333) {
|
||||
selectedRoutes = e1Routes;
|
||||
} else if (entryRandom < 0.666) {
|
||||
selectedRoutes = e2Routes;
|
||||
} else {
|
||||
selectedRoutes = e3Routes;
|
||||
}
|
||||
|
||||
// Step 2: Select a route from the chosen list based on cumulative probabilities
|
||||
double routeRand = Math.random();
|
||||
double cumulative = 0.0;
|
||||
|
||||
for (RouteWithProbability routeWithProb : selectedRoutes) {
|
||||
cumulative += routeWithProb.probability;
|
||||
if (routeRand <= cumulative) {
|
||||
// Return a *copy* of the route to prevent modification
|
||||
return new ArrayList<>(routeWithProb.route);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: This should only be reached if probabilities don't sum to 1
|
||||
// (due to floating point errors)
|
||||
return new ArrayList<>(selectedRoutes.get(0).route);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A string providing information about the generator's configuration.
|
||||
*/
|
||||
public String getInfo() {
|
||||
int totalRoutes = e1Routes.size() + e2Routes.size() + e3Routes.size();
|
||||
return String.format(
|
||||
"VehicleGenerator{model=%s, rate=%.2f, interval=%.2f, routes=%d (E1:%d, E2:%d, E3:%d)}",
|
||||
arrivalModel, arrivalRate, fixedInterval, totalRoutes,
|
||||
e1Routes.size(), e2Routes.size(), e3Routes.size()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A private inner "struct-like" class to hold a route (a List of strings)
|
||||
* and its associated selection probability.
|
||||
*/
|
||||
private static class RouteWithProbability {
|
||||
final List<String> route;
|
||||
final double probability;
|
||||
|
||||
/**
|
||||
* Constructs a new RouteWithProbability pair.
|
||||
* @param route The list of intersection IDs.
|
||||
* @param probability The probability (0.0 to 1.0) of this route
|
||||
* being chosen *from its entry group*.
|
||||
*/
|
||||
RouteWithProbability(List<String> route, double probability) {
|
||||
this.route = route;
|
||||
this.probability = probability;
|
||||
}
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
46
main/src/main/resources/network_config.json
Normal file
46
main/src/main/resources/network_config.json
Normal file
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"intersections": [
|
||||
{
|
||||
"id": "Cr1",
|
||||
"lights": ["East", "South"],
|
||||
"routes": {
|
||||
"Cr2": "East",
|
||||
"Cr4": "South"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "Cr2",
|
||||
"lights": ["West", "East", "South"],
|
||||
"routes": {
|
||||
"Cr1": "West",
|
||||
"Cr3": "East",
|
||||
"Cr5": "South"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "Cr3",
|
||||
"lights": ["West", "South"],
|
||||
"routes": {
|
||||
"Cr2": "West",
|
||||
"S": "South"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "Cr4",
|
||||
"lights": ["East", "West"],
|
||||
"routes": {
|
||||
"Cr1": "North",
|
||||
"Cr5": "East"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "Cr5",
|
||||
"lights": ["East", "West", "North"],
|
||||
"routes": {
|
||||
"Cr2": "North",
|
||||
"Cr4": "West",
|
||||
"S": "East"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
117
main/src/main/resources/simulation-high.properties
Normal file
117
main/src/main/resources/simulation-high.properties
Normal file
@@ -0,0 +1,117 @@
|
||||
# =========================================================
|
||||
# Traffic Simulation Configuration - HIGH LOAD SCENARIO
|
||||
# ---------------------------------------------------------
|
||||
# High traffic scenario for testing system under heavy load.
|
||||
# Expected: Significant congestion, large queues, system stress test
|
||||
# =========================================================
|
||||
|
||||
# === NETWORK CONFIGURATION ===
|
||||
|
||||
# Intersections (each with its host and port)
|
||||
intersection.Cr1.host=localhost
|
||||
intersection.Cr1.port=8001
|
||||
intersection.Cr2.host=localhost
|
||||
intersection.Cr2.port=8002
|
||||
intersection.Cr3.host=localhost
|
||||
intersection.Cr3.port=8003
|
||||
intersection.Cr4.host=localhost
|
||||
intersection.Cr4.port=8004
|
||||
intersection.Cr5.host=localhost
|
||||
intersection.Cr5.port=8005
|
||||
|
||||
# Exit node
|
||||
exit.host=localhost
|
||||
exit.port=9001
|
||||
|
||||
# Dashboard server
|
||||
dashboard.host=localhost
|
||||
dashboard.port=9000
|
||||
|
||||
|
||||
# === SIMULATION CONFIGURATION ===
|
||||
|
||||
# Total duration in seconds (1800 = 30 minutes)
|
||||
simulation.duration=1800
|
||||
|
||||
# Vehicle arrival model: FIXED or POISSON
|
||||
simulation.arrival.model=POISSON
|
||||
|
||||
# λ (lambda): HIGH LOAD = 1.0 vehicle per second (60 vehicles/minute, 3600 vehicles/hour)
|
||||
# This is 2x medium load - tests system capacity limits
|
||||
simulation.arrival.rate=1.0
|
||||
|
||||
# Fixed interval between arrivals (only used if model=FIXED)
|
||||
simulation.arrival.fixed.interval=1.0
|
||||
|
||||
|
||||
# === TRAFFIC LIGHT TIMINGS ===
|
||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
||||
# Aggressive timings to maximize throughput under high load
|
||||
|
||||
# Intersection 1 (Entry point - longer greens to prevent early backup)
|
||||
trafficlight.Cr1.South.green=60.0
|
||||
trafficlight.Cr1.South.red=3.0
|
||||
trafficlight.Cr1.East.green=60.0
|
||||
trafficlight.Cr1.East.red=3.0
|
||||
|
||||
# Intersection 2 (Main hub - CRITICAL BOTTLENECK, maximum green times)
|
||||
# This is the most critical intersection - all routes converge here
|
||||
trafficlight.Cr2.South.green=70.0
|
||||
trafficlight.Cr2.South.red=3.0
|
||||
trafficlight.Cr2.East.green=80.0
|
||||
trafficlight.Cr2.East.red=3.0
|
||||
trafficlight.Cr2.West.green=70.0
|
||||
trafficlight.Cr2.West.red=3.0
|
||||
|
||||
# Intersection 3 (Path to exit - maximize East throughput to exit)
|
||||
trafficlight.Cr3.South.green=50.0
|
||||
trafficlight.Cr3.South.red=3.0
|
||||
trafficlight.Cr3.West.green=40.0
|
||||
trafficlight.Cr3.West.red=3.0
|
||||
|
||||
# Intersection 4 (High throughput needed toward Cr5)
|
||||
trafficlight.Cr4.East.green=70.0
|
||||
trafficlight.Cr4.East.red=3.0
|
||||
|
||||
# Intersection 5 (Near exit - MAJOR BOTTLENECK, longest green time)
|
||||
# All routes funnel through here before exit
|
||||
trafficlight.Cr5.East.green=90.0
|
||||
trafficlight.Cr5.East.red=3.0
|
||||
|
||||
|
||||
# === VEHICLE CONFIGURATION ===
|
||||
# Probability distribution for vehicle types (must sum to 1.0)
|
||||
vehicle.probability.bike=0.2
|
||||
vehicle.probability.light=0.6
|
||||
vehicle.probability.heavy=0.2
|
||||
|
||||
# Average crossing times (in seconds)
|
||||
vehicle.crossing.time.bike=1.0
|
||||
vehicle.crossing.time.light=2.0
|
||||
vehicle.crossing.time.heavy=4.0
|
||||
|
||||
# Travel times between intersections (in seconds)
|
||||
# Base time for light vehicles (cars)
|
||||
vehicle.travel.time.base=1.0
|
||||
# Bike travel time = 0.5 × car travel time
|
||||
vehicle.travel.time.bike.multiplier=0.5
|
||||
# Heavy vehicle travel time = 4.0 x base travel time
|
||||
vehicle.travel.time.heavy.multiplier=4.0
|
||||
|
||||
# === STATISTICS ===
|
||||
|
||||
# Interval between dashboard updates (seconds)
|
||||
statistics.update.interval=10.0
|
||||
|
||||
# === EXPECTED BEHAVIOR - HIGH LOAD ===
|
||||
# - Average system time: 200-400+ seconds (3-7+ minutes)
|
||||
# - Maximum queue sizes: 15-30+ vehicles at Cr2 and Cr5
|
||||
# - Average queue sizes: 8-15+ vehicles
|
||||
# - Severe congestion at Cr2 (main convergence point)
|
||||
# - Severe congestion at Cr5 (pre-exit bottleneck)
|
||||
# - System utilization: ~80-95%
|
||||
# - Many vehicles will remain in system at simulation end
|
||||
# - Queue growth may be unbounded if arrival rate exceeds service rate
|
||||
# - Primary bottlenecks: Cr2 (3-way convergence) and Cr5 (final funnel)
|
||||
# - This scenario tests maximum system capacity and traffic light optimization
|
||||
# - Expected to demonstrate need for adaptive traffic light policies
|
||||
111
main/src/main/resources/simulation-low.properties
Normal file
111
main/src/main/resources/simulation-low.properties
Normal file
@@ -0,0 +1,111 @@
|
||||
# =========================================================
|
||||
# Traffic Simulation Configuration - LOW LOAD SCENARIO
|
||||
# ---------------------------------------------------------
|
||||
# Low traffic scenario for testing system under light load.
|
||||
# Expected: No congestion, minimal queues, fast vehicle throughput
|
||||
# =========================================================
|
||||
|
||||
# === NETWORK CONFIGURATION ===
|
||||
|
||||
# Intersections (each with its host and port)
|
||||
intersection.Cr1.host=localhost
|
||||
intersection.Cr1.port=8001
|
||||
intersection.Cr2.host=localhost
|
||||
intersection.Cr2.port=8002
|
||||
intersection.Cr3.host=localhost
|
||||
intersection.Cr3.port=8003
|
||||
intersection.Cr4.host=localhost
|
||||
intersection.Cr4.port=8004
|
||||
intersection.Cr5.host=localhost
|
||||
intersection.Cr5.port=8005
|
||||
|
||||
# Exit node
|
||||
exit.host=localhost
|
||||
exit.port=9001
|
||||
|
||||
# Dashboard server
|
||||
dashboard.host=localhost
|
||||
dashboard.port=9000
|
||||
|
||||
|
||||
# === SIMULATION CONFIGURATION ===
|
||||
|
||||
# Total duration in seconds (1800 = 30 minutes)
|
||||
simulation.duration=1800
|
||||
|
||||
# Vehicle arrival model: FIXED or POISSON
|
||||
simulation.arrival.model=POISSON
|
||||
|
||||
# λ (lambda): LOW LOAD = 0.2 vehicles per second (12 vehicles/minute, 720 vehicles/hour)
|
||||
# This is approximately 40% of medium load
|
||||
simulation.arrival.rate=0.2
|
||||
|
||||
# Fixed interval between arrivals (only used if model=FIXED)
|
||||
simulation.arrival.fixed.interval=5.0
|
||||
|
||||
|
||||
# === TRAFFIC LIGHT TIMINGS ===
|
||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
||||
# Standard timings - should be more than adequate for low load
|
||||
|
||||
# Intersection 1 (Entry point - balanced)
|
||||
trafficlight.Cr1.South.green=30.0
|
||||
trafficlight.Cr1.South.red=5.0
|
||||
trafficlight.Cr1.East.green=30.0
|
||||
trafficlight.Cr1.East.red=5.0
|
||||
|
||||
# Intersection 2 (Main hub - shorter cycles, favor East-West)
|
||||
trafficlight.Cr2.South.green=30.0
|
||||
trafficlight.Cr2.South.red=5.0
|
||||
trafficlight.Cr2.East.green=30.0
|
||||
trafficlight.Cr2.East.red=5.0
|
||||
trafficlight.Cr2.West.green=30.0
|
||||
trafficlight.Cr2.West.red=5.0
|
||||
|
||||
# Intersection 3 (Path to exit - favor East)
|
||||
trafficlight.Cr3.South.green=30.0
|
||||
trafficlight.Cr3.South.red=5.0
|
||||
trafficlight.Cr3.West.green=30.0
|
||||
trafficlight.Cr3.West.red=5.0
|
||||
|
||||
# Intersection 4 (Favor East toward Cr5)
|
||||
trafficlight.Cr4.East.green=30.0
|
||||
trafficlight.Cr4.East.red=5.0
|
||||
|
||||
# Intersection 5 (Near exit - favor East)
|
||||
trafficlight.Cr5.East.green=30.0
|
||||
trafficlight.Cr5.East.red=5.0
|
||||
|
||||
|
||||
# === VEHICLE CONFIGURATION ===
|
||||
# Probability distribution for vehicle types (must sum to 1.0)
|
||||
vehicle.probability.bike=0.2
|
||||
vehicle.probability.light=0.6
|
||||
vehicle.probability.heavy=0.2
|
||||
|
||||
# Average crossing times (in seconds)
|
||||
vehicle.crossing.time.bike=1.0
|
||||
vehicle.crossing.time.light=2.0
|
||||
vehicle.crossing.time.heavy=4.0
|
||||
|
||||
# Travel times between intersections (in seconds)
|
||||
# Base time for light vehicles (cars)
|
||||
vehicle.travel.time.base=1.0
|
||||
# Bike travel time = 0.5 × car travel time
|
||||
vehicle.travel.time.bike.multiplier=0.5
|
||||
# Heavy vehicle travel time = 4.0 x base travel time
|
||||
vehicle.travel.time.heavy.multiplier=4.0
|
||||
|
||||
# === STATISTICS ===
|
||||
|
||||
# Interval between dashboard updates (seconds)
|
||||
statistics.update.interval=10.0
|
||||
|
||||
# === EXPECTED BEHAVIOR - LOW LOAD ===
|
||||
# - Average system time: 40-80 seconds
|
||||
# - Maximum queue sizes: 1-3 vehicles
|
||||
# - Average queue sizes: < 1 vehicle
|
||||
# - Vehicles should flow smoothly through the system
|
||||
# - Minimal waiting at traffic lights (mostly travel time)
|
||||
# - System utilization: ~20-30%
|
||||
# - All vehicles should exit within simulation time
|
||||
112
main/src/main/resources/simulation-medium.properties
Normal file
112
main/src/main/resources/simulation-medium.properties
Normal file
@@ -0,0 +1,112 @@
|
||||
# =========================================================
|
||||
# Traffic Simulation Configuration - MEDIUM LOAD SCENARIO
|
||||
# ---------------------------------------------------------
|
||||
# Medium traffic scenario for testing system under normal load.
|
||||
# Expected: Moderate queues, some congestion at peak intersections
|
||||
# =========================================================
|
||||
|
||||
# === NETWORK CONFIGURATION ===
|
||||
|
||||
# Intersections (each with its host and port)
|
||||
intersection.Cr1.host=localhost
|
||||
intersection.Cr1.port=8001
|
||||
intersection.Cr2.host=localhost
|
||||
intersection.Cr2.port=8002
|
||||
intersection.Cr3.host=localhost
|
||||
intersection.Cr3.port=8003
|
||||
intersection.Cr4.host=localhost
|
||||
intersection.Cr4.port=8004
|
||||
intersection.Cr5.host=localhost
|
||||
intersection.Cr5.port=8005
|
||||
|
||||
# Exit node
|
||||
exit.host=localhost
|
||||
exit.port=9001
|
||||
|
||||
# Dashboard server
|
||||
dashboard.host=localhost
|
||||
dashboard.port=9000
|
||||
|
||||
|
||||
# === SIMULATION CONFIGURATION ===
|
||||
|
||||
# Total duration in seconds (1800 = 30 minutes)
|
||||
simulation.duration=1800
|
||||
|
||||
# Vehicle arrival model: FIXED or POISSON
|
||||
simulation.arrival.model=POISSON
|
||||
|
||||
# λ (lambda): MEDIUM LOAD = 0.5 vehicles per second (30 vehicles/minute, 1800 vehicles/hour)
|
||||
# This represents normal traffic conditions
|
||||
simulation.arrival.rate=0.5
|
||||
|
||||
# Fixed interval between arrivals (only used if model=FIXED)
|
||||
simulation.arrival.fixed.interval=2.0
|
||||
|
||||
|
||||
# === TRAFFIC LIGHT TIMINGS ===
|
||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
||||
# Optimized timings for medium load
|
||||
|
||||
# Intersection 1 (Entry point - balanced)
|
||||
trafficlight.Cr1.South.green=40.0
|
||||
trafficlight.Cr1.South.red=5.0
|
||||
trafficlight.Cr1.East.green=40.0
|
||||
trafficlight.Cr1.East.red=5.0
|
||||
|
||||
# Intersection 2 (Main hub - CRITICAL BOTTLENECK, longer green times)
|
||||
trafficlight.Cr2.South.green=45.0
|
||||
trafficlight.Cr2.South.red=5.0
|
||||
trafficlight.Cr2.East.green=50.0
|
||||
trafficlight.Cr2.East.red=5.0
|
||||
trafficlight.Cr2.West.green=45.0
|
||||
trafficlight.Cr2.West.red=5.0
|
||||
|
||||
# Intersection 3 (Path to exit - favor East toward exit)
|
||||
trafficlight.Cr3.South.green=40.0
|
||||
trafficlight.Cr3.South.red=5.0
|
||||
trafficlight.Cr3.West.green=35.0
|
||||
trafficlight.Cr3.West.red=5.0
|
||||
|
||||
# Intersection 4 (Favor East toward Cr5)
|
||||
trafficlight.Cr4.East.green=40.0
|
||||
trafficlight.Cr4.East.red=5.0
|
||||
|
||||
# Intersection 5 (Near exit - POTENTIAL BOTTLENECK, longer green)
|
||||
trafficlight.Cr5.East.green=50.0
|
||||
trafficlight.Cr5.East.red=5.0
|
||||
|
||||
|
||||
# === VEHICLE CONFIGURATION ===
|
||||
# Probability distribution for vehicle types (must sum to 1.0)
|
||||
vehicle.probability.bike=0.2
|
||||
vehicle.probability.light=0.6
|
||||
vehicle.probability.heavy=0.2
|
||||
|
||||
# Average crossing times (in seconds)
|
||||
vehicle.crossing.time.bike=1.0
|
||||
vehicle.crossing.time.light=2.0
|
||||
vehicle.crossing.time.heavy=4.0
|
||||
|
||||
# Travel times between intersections (in seconds)
|
||||
# Base time for light vehicles (cars)
|
||||
vehicle.travel.time.base=1.0
|
||||
# Bike travel time = 0.5 × car travel time
|
||||
vehicle.travel.time.bike.multiplier=0.5
|
||||
# Heavy vehicle travel time = 4.0 x base travel time
|
||||
vehicle.travel.time.heavy.multiplier=4.0
|
||||
|
||||
# === STATISTICS ===
|
||||
|
||||
# Interval between dashboard updates (seconds)
|
||||
statistics.update.interval=10.0
|
||||
|
||||
# === EXPECTED BEHAVIOR - MEDIUM LOAD ===
|
||||
# - Average system time: 80-150 seconds
|
||||
# - Maximum queue sizes: 5-10 vehicles at Cr2 and Cr5
|
||||
# - Average queue sizes: 2-5 vehicles
|
||||
# - Moderate congestion at Cr2 (main hub) and Cr5 (pre-exit)
|
||||
# - System utilization: ~50-60%
|
||||
# - Most vehicles should exit, some may remain at simulation end
|
||||
# - Cr2 is the primary bottleneck (3 directions converge)
|
||||
# - Cr5 is secondary bottleneck (all routes pass through)
|
||||
@@ -31,7 +31,11 @@ dashboard.port=9000
|
||||
# === SIMULATION CONFIGURATION ===
|
||||
|
||||
# Total duration in seconds (3600 = 1 hour)
|
||||
simulation.duration=3600.0
|
||||
simulation.duration=300
|
||||
|
||||
# Time scaling factor for visualization (real_seconds = sim_seconds * scale)
|
||||
# 0 = instant (pure DES), 0.01 = 100x speed, 0.1 = 10x speed, 1.0 = real-time
|
||||
simulation.time.scale=0.01
|
||||
|
||||
# Vehicle arrival model: FIXED or POISSON
|
||||
simulation.arrival.model=POISSON
|
||||
@@ -46,55 +50,34 @@ simulation.arrival.fixed.interval=2.0
|
||||
# === TRAFFIC LIGHT TIMINGS ===
|
||||
# Format: trafficlight.<intersection>.<direction>.<state>=<seconds>
|
||||
|
||||
# Intersection 1
|
||||
trafficlight.Cr1.North.green=30.0
|
||||
trafficlight.Cr1.North.red=30.0
|
||||
trafficlight.Cr1.South.green=30.0
|
||||
trafficlight.Cr1.South.red=30.0
|
||||
trafficlight.Cr1.East.green=30.0
|
||||
trafficlight.Cr1.East.red=30.0
|
||||
trafficlight.Cr1.West.green=30.0
|
||||
trafficlight.Cr1.West.red=30.0
|
||||
# Intersection 1 (Entry point - balanced)
|
||||
trafficlight.Cr1.South.green=60.0
|
||||
trafficlight.Cr1.South.red=5.0
|
||||
trafficlight.Cr1.East.green=60.0
|
||||
trafficlight.Cr1.East.red=5.0
|
||||
|
||||
# Intersection 2
|
||||
trafficlight.Cr2.North.green=25.0
|
||||
trafficlight.Cr2.North.red=35.0
|
||||
trafficlight.Cr2.South.green=25.0
|
||||
trafficlight.Cr2.South.red=35.0
|
||||
trafficlight.Cr2.East.green=35.0
|
||||
trafficlight.Cr2.East.red=25.0
|
||||
trafficlight.Cr2.West.green=35.0
|
||||
trafficlight.Cr2.West.red=25.0
|
||||
# Intersection 2 (Main hub - shorter cycles, favor East-West)
|
||||
trafficlight.Cr2.South.green=60.0
|
||||
trafficlight.Cr2.South.red=5.0
|
||||
trafficlight.Cr2.East.green=60.0
|
||||
trafficlight.Cr2.East.red=5.0
|
||||
trafficlight.Cr2.West.green=60.0
|
||||
trafficlight.Cr2.West.red=5.0
|
||||
|
||||
# Intersection 3
|
||||
trafficlight.Cr3.North.green=30.0
|
||||
trafficlight.Cr3.North.red=30.0
|
||||
trafficlight.Cr3.South.green=30.0
|
||||
trafficlight.Cr3.South.red=30.0
|
||||
trafficlight.Cr3.East.green=30.0
|
||||
trafficlight.Cr3.East.red=30.0
|
||||
trafficlight.Cr3.West.green=30.0
|
||||
trafficlight.Cr3.West.red=30.0
|
||||
# Intersection 3 (Path to exit - favor East)
|
||||
trafficlight.Cr3.South.green=60.0
|
||||
trafficlight.Cr3.South.red=5.0
|
||||
trafficlight.Cr3.West.green=60.0
|
||||
trafficlight.Cr3.West.red=5.0
|
||||
|
||||
# Intersection 4
|
||||
trafficlight.Cr4.North.green=30.0
|
||||
trafficlight.Cr4.North.red=30.0
|
||||
trafficlight.Cr4.South.green=30.0
|
||||
trafficlight.Cr4.South.red=30.0
|
||||
trafficlight.Cr4.East.green=30.0
|
||||
trafficlight.Cr4.East.red=30.0
|
||||
trafficlight.Cr4.West.green=30.0
|
||||
trafficlight.Cr4.West.red=30.0
|
||||
# Intersection 4 (Favor East toward Cr5)
|
||||
trafficlight.Cr4.East.green=60.0
|
||||
trafficlight.Cr4.East.red=5.0
|
||||
|
||||
# Intersection 5 (Near exit - favor East)
|
||||
trafficlight.Cr5.East.green=60.0
|
||||
trafficlight.Cr5.East.red=5.0
|
||||
|
||||
# Intersection 5
|
||||
trafficlight.Cr5.North.green=30.0
|
||||
trafficlight.Cr5.North.red=30.0
|
||||
trafficlight.Cr5.South.green=30.0
|
||||
trafficlight.Cr5.South.red=30.0
|
||||
trafficlight.Cr5.East.green=30.0
|
||||
trafficlight.Cr5.East.red=30.0
|
||||
trafficlight.Cr5.West.green=30.0
|
||||
trafficlight.Cr5.West.red=30.0
|
||||
|
||||
# === VEHICLE CONFIGURATION ===
|
||||
# Probability distribution for vehicle types (must sum to 1.0)
|
||||
@@ -103,11 +86,19 @@ vehicle.probability.light=0.6
|
||||
vehicle.probability.heavy=0.2
|
||||
|
||||
# Average crossing times (in seconds)
|
||||
vehicle.crossing.time.bike=1.5
|
||||
vehicle.crossing.time.bike=1.0
|
||||
vehicle.crossing.time.light=2.0
|
||||
vehicle.crossing.time.heavy=4.0
|
||||
|
||||
# Travel times between intersections (in seconds)
|
||||
# Base time for light vehicles (cars)
|
||||
vehicle.travel.time.base=1.0
|
||||
# Bike travel time = 0.5 × car travel time
|
||||
vehicle.travel.time.bike.multiplier=0.5
|
||||
# Heavy vehicle travel time = 4.0 x base travel time
|
||||
vehicle.travel.time.heavy.multiplier=4.0
|
||||
|
||||
# === STATISTICS ===
|
||||
|
||||
# Interval between dashboard updates (seconds)
|
||||
statistics.update.interval=10.0
|
||||
statistics.update.interval=0.1
|
||||
|
||||
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 ""
|
||||
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